Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3a272096c0 |
@@ -1,19 +0,0 @@
|
|||||||
# To get started with Dependabot version updates, you'll need to specify which
|
|
||||||
# package ecosystems to update and where the package manifests are located.
|
|
||||||
# Please see the documentation for all configuration options:
|
|
||||||
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
|
|
||||||
|
|
||||||
version: 2
|
|
||||||
updates:
|
|
||||||
- package-ecosystem: "cargo" # See documentation for possible values
|
|
||||||
directory: "/" # Location of package manifests
|
|
||||||
schedule:
|
|
||||||
interval: "weekly"
|
|
||||||
|
|
||||||
# Enable version updates for GitHub Actions
|
|
||||||
- package-ecosystem: "github-actions"
|
|
||||||
# Workflow files stored in the default location of `.github/workflows`
|
|
||||||
# You don't need to specify `/.github/workflows` for `directory`. You can use `directory: "/"`.
|
|
||||||
directory: "/"
|
|
||||||
schedule:
|
|
||||||
interval: "weekly"
|
|
||||||
@@ -1,567 +0,0 @@
|
|||||||
name: "CI"
|
|
||||||
|
|
||||||
on:
|
|
||||||
workflow_dispatch:
|
|
||||||
inputs:
|
|
||||||
Docker:
|
|
||||||
required: false
|
|
||||||
default: false
|
|
||||||
type: boolean
|
|
||||||
Release:
|
|
||||||
required: false
|
|
||||||
default: false
|
|
||||||
type: boolean
|
|
||||||
push:
|
|
||||||
tags: ["v*.*.*"]
|
|
||||||
|
|
||||||
env:
|
|
||||||
SCCACHE_GHA_ENABLED: true
|
|
||||||
RUSTC_WRAPPER: sccache
|
|
||||||
CARGO_TERM_COLOR: always
|
|
||||||
CARGO_NET_RETRY: 10
|
|
||||||
CARGO_NET_GIT_FETCH_WITH_CLI: true
|
|
||||||
AWS_LC_SYS_PREBUILT_NASM: 1
|
|
||||||
|
|
||||||
concurrency:
|
|
||||||
group: ${{ github.workflow }}-${{ github.ref }}
|
|
||||||
cancel-in-progress: true
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
multiarch:
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
include:
|
|
||||||
- variant: gnu
|
|
||||||
- variant: musl
|
|
||||||
name: Merge image / ${{matrix.variant}}
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
|
||||||
id-token: write
|
|
||||||
contents: read
|
|
||||||
attestations: write
|
|
||||||
packages: write
|
|
||||||
needs: [linux]
|
|
||||||
if: github.event_name == 'push' || inputs.Docker
|
|
||||||
steps:
|
|
||||||
- name: Install Cosign
|
|
||||||
uses: sigstore/[email protected]
|
|
||||||
- name: Log In to GitHub Container Registry
|
|
||||||
uses: docker/login-action@v4
|
|
||||||
with:
|
|
||||||
registry: ghcr.io
|
|
||||||
username: ${{github.repository_owner}}
|
|
||||||
password: ${{github.token}}
|
|
||||||
|
|
||||||
- name: Log In to DockerHub
|
|
||||||
uses: docker/login-action@v4
|
|
||||||
with:
|
|
||||||
username: ${{secrets.DOCKERHUB_USERNAME}}
|
|
||||||
password: ${{secrets.DOCKERHUB_TOKEN}}
|
|
||||||
|
|
||||||
- name: Download ${{matrix.variant}} meta bake definition
|
|
||||||
uses: actions/download-artifact@v8
|
|
||||||
with:
|
|
||||||
name: bake-meta-${{matrix.variant}}
|
|
||||||
path: ${{ runner.temp }}/${{matrix.variant}}
|
|
||||||
|
|
||||||
- name: Download ${{matrix.variant}} digests
|
|
||||||
uses: actions/download-artifact@v8
|
|
||||||
with:
|
|
||||||
path: ${{ runner.temp }}/${{matrix.variant}}/digests
|
|
||||||
pattern: digests-${{matrix.variant}}-*
|
|
||||||
merge-multiple: true
|
|
||||||
|
|
||||||
- name: Create ${{matrix.variant}} manifest list and push
|
|
||||||
working-directory: ${{ runner.temp }}/${{matrix.variant}}/digests
|
|
||||||
run: |
|
|
||||||
docker buildx imagetools create $(jq -cr '.target."docker-metadata-action".tags | map(select(startswith("ghcr.io/${{github.repository}}")) | "-t " + .) | join(" ")' ${{ runner.temp }}/${{matrix.variant}}/bake-meta.json) \
|
|
||||||
$(printf 'ghcr.io/${{github.repository}}@sha256:%s ' *)
|
|
||||||
docker buildx imagetools create $(jq -cr '.target."docker-metadata-action".tags | map(select(startswith("index.docker.io/${{github.repository}}")) | "-t " + .) | join(" ")' ${{ runner.temp }}/${{matrix.variant}}/bake-meta.json) \
|
|
||||||
$(printf 'index.docker.io/${{github.repository}}@sha256:%s ' *)
|
|
||||||
|
|
||||||
- name: Inspect ${{matrix.variant}} image
|
|
||||||
id: manifest-digest
|
|
||||||
run: |
|
|
||||||
docker buildx imagetools inspect --format '{{json .Manifest}}' ghcr.io/${{github.repository}}:$(jq -r '.target."docker-metadata-action".args.DOCKER_META_VERSION' ${{ runner.temp }}/${{matrix.variant}}/bake-meta.json) | jq -r '.digest' > GHCR_DIGEST_SHA
|
|
||||||
echo "GHCR_DIGEST_SHA=$(cat GHCR_DIGEST_SHA)" | tee -a "${GITHUB_ENV}"
|
|
||||||
docker buildx imagetools inspect --format '{{json .Manifest}}' index.docker.io/${{github.repository}}:$(jq -r '.target."docker-metadata-action".args.DOCKER_META_VERSION' ${{ runner.temp }}/${{matrix.variant}}/bake-meta.json) | jq -r '.digest' > DOCKERHUB_DIGEST_SHA
|
|
||||||
echo "DOCKERHUB_DIGEST_SHA=$(cat DOCKERHUB_DIGEST_SHA)" | tee -a "${GITHUB_ENV}"
|
|
||||||
cosign sign --yes $(jq --arg GHCR_DIGEST_SHA "$(cat GHCR_DIGEST_SHA)" -cr '.target."docker-metadata-action".tags | map(select(startswith("ghcr.io/${{github.repository}}")) | . + "@" + $GHCR_DIGEST_SHA) | join(" ")' ${{ runner.temp }}/${{matrix.variant}}/bake-meta.json)
|
|
||||||
cosign sign --yes $(jq --arg DOCKERHUB_DIGEST_SHA "$(cat DOCKERHUB_DIGEST_SHA)" -cr '.target."docker-metadata-action".tags | map(select(startswith("index.docker.io/${{github.repository}}")) | . + "@" + $DOCKERHUB_DIGEST_SHA) | join(" ")' ${{ runner.temp }}/${{matrix.variant}}/bake-meta.json)
|
|
||||||
|
|
||||||
- name: Attest GHCR
|
|
||||||
uses: actions/attest-build-provenance@v4
|
|
||||||
with:
|
|
||||||
subject-name: ghcr.io/${{github.repository}}
|
|
||||||
subject-digest: ${{ env.GHCR_DIGEST_SHA }}
|
|
||||||
push-to-registry: true
|
|
||||||
|
|
||||||
- name: Attest Dockerhub
|
|
||||||
uses: actions/attest-build-provenance@v4
|
|
||||||
with:
|
|
||||||
subject-name: index.docker.io/${{github.repository}}
|
|
||||||
subject-digest: ${{ env.DOCKERHUB_DIGEST_SHA }}
|
|
||||||
push-to-registry: true
|
|
||||||
|
|
||||||
linux:
|
|
||||||
permissions:
|
|
||||||
id-token: write
|
|
||||||
contents: write
|
|
||||||
attestations: write
|
|
||||||
packages: write
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
include:
|
|
||||||
- target: x86_64-unknown-linux-gnu
|
|
||||||
platform: linux/amd64
|
|
||||||
suffix: ""
|
|
||||||
build_env: ""
|
|
||||||
- target: x86_64-unknown-linux-musl
|
|
||||||
platform: linux/amd64
|
|
||||||
suffix: "-alpine"
|
|
||||||
build_env: ""
|
|
||||||
- target: aarch64-unknown-linux-gnu
|
|
||||||
platform: linux/arm64
|
|
||||||
suffix: ""
|
|
||||||
build_env: "JEMALLOC_SYS_WITH_LG_PAGE=16 "
|
|
||||||
- target: aarch64-unknown-linux-musl
|
|
||||||
platform: linux/arm64
|
|
||||||
suffix: "-alpine"
|
|
||||||
build_env: "JEMALLOC_SYS_WITH_LG_PAGE=16 "
|
|
||||||
- target: armv7-unknown-linux-gnueabihf
|
|
||||||
platform: linux/arm/v7
|
|
||||||
suffix: ""
|
|
||||||
build_env: "JEMALLOC_SYS_WITH_LG_PAGE=16 "
|
|
||||||
- target: armv7-unknown-linux-musleabihf
|
|
||||||
platform: linux/arm/v7
|
|
||||||
suffix: "-alpine"
|
|
||||||
build_env: "JEMALLOC_SYS_WITH_LG_PAGE=16 "
|
|
||||||
- target: arm-unknown-linux-gnueabihf
|
|
||||||
platform: linux/arm/v6
|
|
||||||
suffix: ""
|
|
||||||
build_env: ""
|
|
||||||
- target: arm-unknown-linux-musleabihf
|
|
||||||
platform: linux/arm/v6
|
|
||||||
suffix: "-alpine"
|
|
||||||
build_env: ""
|
|
||||||
name: Build / ${{matrix.target}}
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v7
|
|
||||||
|
|
||||||
- name: Free disk space (heavy ARM targets)
|
|
||||||
if: contains(matrix.target, 'arm') || contains(matrix.target, 'aarch64')
|
|
||||||
run: |
|
|
||||||
df -h /mnt /
|
|
||||||
sudo rm -rf /usr/share/dotnet /opt/ghc /usr/local/lib/android /usr/local/.ghcup /usr/local/share/powershell /usr/share/swift /opt/hostedtoolcache/CodeQL
|
|
||||||
sudo docker image prune --all --force || true
|
|
||||||
df -h /mnt /
|
|
||||||
|
|
||||||
- name: Add swap (heavy ARM targets)
|
|
||||||
if: contains(matrix.target, 'arm') || contains(matrix.target, 'aarch64')
|
|
||||||
run: |
|
|
||||||
mnt_avail=$(df --output=avail -k /mnt | tail -1)
|
|
||||||
if [ "$mnt_avail" -lt 18874368 ]; then
|
|
||||||
echo "Insufficient space on /mnt (${mnt_avail}K available), aborting swap setup"
|
|
||||||
exit 1
|
|
||||||
fi
|
|
||||||
sudo fallocate -l 16G /mnt/swapfile
|
|
||||||
sudo chmod 600 /mnt/swapfile
|
|
||||||
sudo mkswap /mnt/swapfile
|
|
||||||
sudo swapon /mnt/swapfile
|
|
||||||
sudo sysctl vm.swappiness=80
|
|
||||||
free -h
|
|
||||||
swapon --show
|
|
||||||
|
|
||||||
- name: Set up QEMU
|
|
||||||
uses: docker/setup-qemu-action@v4
|
|
||||||
with:
|
|
||||||
platforms: "arm64,arm"
|
|
||||||
|
|
||||||
- name: Set up Docker Buildx
|
|
||||||
uses: docker/setup-buildx-action@v4
|
|
||||||
with:
|
|
||||||
buildkitd-config-inline: |
|
|
||||||
[registry."docker.io"]
|
|
||||||
mirrors = ["https://mirror.gcr.io"]
|
|
||||||
driver-opts: |
|
|
||||||
network=host
|
|
||||||
|
|
||||||
- name: Log In to GitHub Container Registry
|
|
||||||
uses: docker/login-action@v4
|
|
||||||
with:
|
|
||||||
registry: ghcr.io
|
|
||||||
username: ${{github.repository_owner}}
|
|
||||||
password: ${{github.token}}
|
|
||||||
|
|
||||||
- name: Log In to DockerHub
|
|
||||||
uses: docker/login-action@v4
|
|
||||||
with:
|
|
||||||
username: ${{secrets.DOCKERHUB_USERNAME}}
|
|
||||||
password: ${{secrets.DOCKERHUB_TOKEN}}
|
|
||||||
|
|
||||||
- name: Calculate shasum of external deps
|
|
||||||
id: cal-dep-shasum
|
|
||||||
run: |
|
|
||||||
echo "checksum=$(yq -p toml -oy '.package[] | select((.source | contains("")) or (.checksum | contains("")))' Cargo.lock | sha256sum | awk '{print $1}')" >> "$GITHUB_OUTPUT"
|
|
||||||
|
|
||||||
- name: Cache apt
|
|
||||||
uses: actions/[email protected]
|
|
||||||
id: apt-cache
|
|
||||||
with:
|
|
||||||
path: |
|
|
||||||
var-cache-apt
|
|
||||||
var-lib-apt
|
|
||||||
key: apt-cache-${{ hashFiles('Dockerfile.build') }}
|
|
||||||
|
|
||||||
- name: Cache Cargo
|
|
||||||
uses: actions/[email protected]
|
|
||||||
id: cargo-cache
|
|
||||||
with:
|
|
||||||
path: |
|
|
||||||
usr-local-cargo-registry
|
|
||||||
usr-local-cargo-git
|
|
||||||
key: cargo-cache-${{ steps.cal-dep-shasum.outputs.checksum }}
|
|
||||||
|
|
||||||
- name: Inject cache into docker
|
|
||||||
uses: reproducible-containers/[email protected]
|
|
||||||
with:
|
|
||||||
cache-map: |
|
|
||||||
{
|
|
||||||
"var-cache-apt": "/var/cache/apt",
|
|
||||||
"var-lib-apt": "/var/lib/apt",
|
|
||||||
"usr-local-cargo-registry": "/usr/local/cargo/registry",
|
|
||||||
"usr-local-cargo-git": "/usr/local/cargo/git"
|
|
||||||
}
|
|
||||||
skip-extraction: ${{ steps.cargo-cache.outputs.cache-hit }} && ${{ steps.apt-cache.outputs.cache-hit }}
|
|
||||||
|
|
||||||
- name: Extract Metadata for Docker
|
|
||||||
uses: docker/metadata-action@v6
|
|
||||||
id: meta
|
|
||||||
with:
|
|
||||||
images: |
|
|
||||||
index.docker.io/${{github.repository}}
|
|
||||||
ghcr.io/${{github.repository}}
|
|
||||||
flavor: |
|
|
||||||
suffix=${{matrix.suffix}},onlatest=true
|
|
||||||
tags: |
|
|
||||||
type=ref,event=tag
|
|
||||||
type=ref,event=branch,prefix=branch-
|
|
||||||
type=edge,branch=main
|
|
||||||
type=semver,pattern=v{{major}}.{{minor}}
|
|
||||||
|
|
||||||
- name: Build Artifact
|
|
||||||
id: bake
|
|
||||||
uses: docker/bake-action@v7
|
|
||||||
env:
|
|
||||||
DOCKER_BUILD_RECORD_UPLOAD: false
|
|
||||||
TARGET: ${{matrix.target}}
|
|
||||||
GHCR_REPO: ghcr.io/${{github.repository}}
|
|
||||||
BUILD_ENV: ${{matrix.build_env}}
|
|
||||||
DOCKER_PLATFORM: ${{matrix.platform}}
|
|
||||||
SUFFIX: ${{matrix.suffix}}
|
|
||||||
with:
|
|
||||||
source: .
|
|
||||||
set: |
|
|
||||||
*.tags=
|
|
||||||
image.output=type=image,"name=ghcr.io/${{github.repository}},index.docker.io/${{github.repository}}",push-by-digest=true,name-canonical=true,push=true,compression=zstd,compression-level=9,force-compression=true,oci-mediatypes=true
|
|
||||||
files: |
|
|
||||||
docker-bake.hcl
|
|
||||||
${{ steps.meta.outputs.bake-file }}
|
|
||||||
targets: ${{(github.event_name == 'push' || inputs.Docker) && 'build,image' || 'build'}}
|
|
||||||
|
|
||||||
- name: Upload Artifacts
|
|
||||||
uses: actions/[email protected]
|
|
||||||
with:
|
|
||||||
name: artifact-${{matrix.target}}
|
|
||||||
path: |
|
|
||||||
artifact
|
|
||||||
!artifact/*.json
|
|
||||||
|
|
||||||
- name: Export digest & Rename meta bake definition file
|
|
||||||
if: github.event_name == 'push' || inputs.Docker
|
|
||||||
run: |
|
|
||||||
mv "${{ steps.meta.outputs.bake-file }}" "${{ runner.temp }}/bake-meta.json"
|
|
||||||
mkdir -p ${{ runner.temp }}/digests
|
|
||||||
digest="${{ fromJSON(steps.bake.outputs.metadata).image['containerimage.digest'] }}"
|
|
||||||
touch "${{ runner.temp }}/digests/${digest#sha256:}"
|
|
||||||
|
|
||||||
- name: Upload digest
|
|
||||||
if: github.event_name == 'push' || inputs.Docker
|
|
||||||
uses: actions/[email protected]
|
|
||||||
with:
|
|
||||||
name: digests-${{matrix.suffix == '' && 'gnu' || 'musl'}}-${{ matrix.target }}
|
|
||||||
path: ${{ runner.temp }}/digests/*
|
|
||||||
if-no-files-found: error
|
|
||||||
retention-days: 1
|
|
||||||
|
|
||||||
- name: Upload GNU meta bake definition
|
|
||||||
uses: actions/[email protected]
|
|
||||||
if: (github.event_name == 'push' || inputs.Docker) && endsWith(matrix.target,'gnu') && startsWith(matrix.target,'x86')
|
|
||||||
with:
|
|
||||||
name: bake-meta-gnu
|
|
||||||
path: ${{ runner.temp }}/bake-meta.json
|
|
||||||
if-no-files-found: error
|
|
||||||
retention-days: 1
|
|
||||||
|
|
||||||
- name: Upload musl meta bake definition
|
|
||||||
uses: actions/[email protected]
|
|
||||||
if: (github.event_name == 'push' || inputs.Docker) && endsWith(matrix.target,'musl') && startsWith(matrix.target,'x86')
|
|
||||||
with:
|
|
||||||
name: bake-meta-musl
|
|
||||||
path: ${{ runner.temp }}/bake-meta.json
|
|
||||||
if-no-files-found: error
|
|
||||||
retention-days: 1
|
|
||||||
|
|
||||||
windows:
|
|
||||||
name: Build / ${{matrix.target}}
|
|
||||||
runs-on: windows-latest
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
include:
|
|
||||||
# - target: aarch64-pc-windows-msvc
|
|
||||||
- target: x86_64-pc-windows-msvc
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v7
|
|
||||||
|
|
||||||
- name: Run sccache-cache
|
|
||||||
uses: mozilla-actions/[email protected]
|
|
||||||
with:
|
|
||||||
disable_annotations: true
|
|
||||||
|
|
||||||
- name: Build
|
|
||||||
run: |
|
|
||||||
rustup target add ${{matrix.target}}
|
|
||||||
cargo build --release --target ${{matrix.target}} -p stalwart --no-default-features --features "sqlite postgres mysql rocks s3 redis azure nats"
|
|
||||||
mkdir -p artifacts
|
|
||||||
mv ./target/${{matrix.target}}/release/stalwart.exe ./artifacts/stalwart.exe
|
|
||||||
|
|
||||||
- name: Upload Artifacts
|
|
||||||
uses: actions/[email protected]
|
|
||||||
with:
|
|
||||||
name: artifact-${{matrix.target}}
|
|
||||||
path: artifacts
|
|
||||||
|
|
||||||
macos:
|
|
||||||
name: Build / ${{matrix.target}}
|
|
||||||
runs-on: macos-latest
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
include:
|
|
||||||
- target: aarch64-apple-darwin
|
|
||||||
- target: x86_64-apple-darwin
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v7
|
|
||||||
|
|
||||||
- name: Run sccache-cache
|
|
||||||
uses: mozilla-actions/[email protected]
|
|
||||||
with:
|
|
||||||
disable_annotations: true
|
|
||||||
|
|
||||||
#- name: Build FoundationDB Edition
|
|
||||||
# env:
|
|
||||||
# GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
# run: |
|
|
||||||
# rustup target add ${{matrix.target}}
|
|
||||||
# # Pin FoundationDB 7.4.x (Apple publishes these as prereleases)
|
|
||||||
# curl --retry 5 -Lso foundationdb.pkg "$(gh api -X GET /repos/apple/foundationdb/releases --jq '[.[] | select(.tag_name | startswith("7.4."))] | sort_by(.tag_name | split(".") | map(tonumber)) | reverse | .[0].assets[] | select(.name | test("${{startsWith(matrix.target, 'x86') && 'x86_64' || 'arm64'}}" + ".pkg$")) | .browser_download_url')"
|
|
||||||
# echo "=== Package contents ==="
|
|
||||||
# pkgutil --payload-files foundationdb.pkg || true
|
|
||||||
# sudo installer -allowUntrusted -verbose -dumplog -pkg foundationdb.pkg -target /
|
|
||||||
# cargo build --release --target ${{matrix.target}} -p stalwart --no-default-features --features "foundationdb s3 redis nats"
|
|
||||||
# mkdir -p artifacts
|
|
||||||
# mv ./target/${{matrix.target}}/release/stalwart ./artifacts/stalwart-foundationdb
|
|
||||||
|
|
||||||
- name: Build
|
|
||||||
run: |
|
|
||||||
rustup target add ${{matrix.target}}
|
|
||||||
cargo build --release --target ${{matrix.target}} -p stalwart --no-default-features --features "sqlite postgres mysql rocks s3 redis azure nats"
|
|
||||||
mkdir -p artifacts
|
|
||||||
mv ./target/${{matrix.target}}/release/stalwart ./artifacts/stalwart
|
|
||||||
|
|
||||||
- name: Upload Artifacts
|
|
||||||
uses: actions/[email protected]
|
|
||||||
with:
|
|
||||||
name: artifact-${{matrix.target}}
|
|
||||||
path: artifacts
|
|
||||||
|
|
||||||
freebsd:
|
|
||||||
name: Build / ${{matrix.target}}
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
timeout-minutes: 360
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
include:
|
|
||||||
- target: x86_64-unknown-freebsd
|
|
||||||
arch: x86_64
|
|
||||||
# - target: aarch64-unknown-freebsd
|
|
||||||
# arch: aarch64
|
|
||||||
steps:
|
|
||||||
- name: Checkout
|
|
||||||
uses: actions/checkout@v7
|
|
||||||
|
|
||||||
- name: Build in FreeBSD VM
|
|
||||||
uses: vmactions/freebsd-vm@v1
|
|
||||||
with:
|
|
||||||
release: "15.1"
|
|
||||||
arch: ${{matrix.arch}}
|
|
||||||
usesh: true
|
|
||||||
mem: 14336
|
|
||||||
cpu: 4
|
|
||||||
sync: rsync
|
|
||||||
copyback: true
|
|
||||||
# gmake: required by jemalloc-sys on BSD hosts
|
|
||||||
# llvm: provides libclang for bindgen (librocksdb-sys)
|
|
||||||
# rust: libsqlite3-sys 0.38 uses cfg_select!, stabilized in Rust
|
|
||||||
# 1.95. The default 'quarterly' pkg repo still ships rust 1.94, so
|
|
||||||
# switch to the 'latest' repo (currently 1.96.1). rustup is not an
|
|
||||||
# option here: aarch64-unknown-freebsd has no rustup toolchains yet.
|
|
||||||
prepare: |
|
|
||||||
set -e
|
|
||||||
mkdir -p /usr/local/etc/pkg/repos
|
|
||||||
echo 'FreeBSD: { url: "pkg+https://pkg.freebsd.org/${ABI}/latest", mirror_type: "srv" }' > /usr/local/etc/pkg/repos/FreeBSD.conf
|
|
||||||
pkg update -f
|
|
||||||
env ASSUME_ALWAYS_YES=yes pkg bootstrap -f
|
|
||||||
pkg update -f
|
|
||||||
pkg install -y rust gmake llvm rocksdb
|
|
||||||
rustc --version
|
|
||||||
run: |
|
|
||||||
set -e
|
|
||||||
export CARGO_TARGET_DIR=/tmp/target
|
|
||||||
export CARGO_TERM_COLOR=always
|
|
||||||
export CARGO_NET_RETRY=10
|
|
||||||
cargo build --release -p stalwart --no-default-features --features "sqlite postgres mysql rocks s3 redis azure nats"
|
|
||||||
mkdir -p artifacts
|
|
||||||
cp /tmp/target/release/stalwart artifacts/stalwart
|
|
||||||
|
|
||||||
- name: Upload Artifacts
|
|
||||||
uses: actions/[email protected]
|
|
||||||
with:
|
|
||||||
name: artifact-${{matrix.target}}
|
|
||||||
path: artifacts
|
|
||||||
|
|
||||||
release:
|
|
||||||
name: Release
|
|
||||||
permissions:
|
|
||||||
id-token: write
|
|
||||||
contents: write
|
|
||||||
attestations: write
|
|
||||||
if: github.event_name == 'push' || inputs.Release
|
|
||||||
needs: [linux, windows, macos, freebsd]
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
steps:
|
|
||||||
# Must run before artifacts are downloaded — checkout cleans the workspace.
|
|
||||||
- name: Checkout (for CHANGELOG)
|
|
||||||
if: startsWith(github.ref, 'refs/tags/')
|
|
||||||
uses: actions/checkout@v7
|
|
||||||
|
|
||||||
- name: Download Artifacts
|
|
||||||
uses: actions/download-artifact@v8
|
|
||||||
with:
|
|
||||||
path: archive
|
|
||||||
pattern: artifact-*
|
|
||||||
|
|
||||||
- name: Compress
|
|
||||||
run: |
|
|
||||||
set -eux
|
|
||||||
BASE_DIR="$(pwd)/archive"
|
|
||||||
compress_files() {
|
|
||||||
local dir="$1"
|
|
||||||
local archive_dir_name="${dir#artifact-}"
|
|
||||||
cd "$dir"
|
|
||||||
# Process each file in the directory
|
|
||||||
for file in `ls`; do
|
|
||||||
filename="${file%.*}"
|
|
||||||
extension="${file##*.}"
|
|
||||||
if [ "$extension" = "exe" ]; then
|
|
||||||
7z a -tzip "${filename}-${archive_dir_name}.zip" "$file" > /dev/null
|
|
||||||
else
|
|
||||||
tar -czf "${filename}-${archive_dir_name}.tar.gz" "$file"
|
|
||||||
fi
|
|
||||||
done
|
|
||||||
cd $BASE_DIR
|
|
||||||
}
|
|
||||||
cd $BASE_DIR
|
|
||||||
for arch_dir in `ls`; do
|
|
||||||
dir_name=$(basename "$arch_dir")
|
|
||||||
compress_files "$dir_name"
|
|
||||||
done
|
|
||||||
|
|
||||||
- name: Attest binary
|
|
||||||
id: attest
|
|
||||||
uses: actions/attest-build-provenance@v4
|
|
||||||
with:
|
|
||||||
subject-path: |
|
|
||||||
archive/**/*.tar.gz
|
|
||||||
archive/**/*.zip
|
|
||||||
|
|
||||||
- name: Use cosign to sign existing artifacts
|
|
||||||
uses: sigstore/[email protected]
|
|
||||||
with:
|
|
||||||
inputs: |
|
|
||||||
archive/**/*.tar.gz
|
|
||||||
archive/**/*.zip
|
|
||||||
|
|
||||||
- name: Build release body
|
|
||||||
run: |
|
|
||||||
if [ "${{ startsWith(github.ref, 'refs/tags/') }}" = "true" ]; then
|
|
||||||
awk '/^## \[/{c++} c==1' CHANGELOG.md > release_body.md
|
|
||||||
echo "" >> release_body.md
|
|
||||||
else
|
|
||||||
: > release_body.md
|
|
||||||
fi
|
|
||||||
cat >> release_body.md <<EOF
|
|
||||||
<hr />
|
|
||||||
|
|
||||||
### Check binary attestation [here](${{ steps.attest.outputs.attestation-url }})
|
|
||||||
EOF
|
|
||||||
|
|
||||||
- name: Release
|
|
||||||
uses: softprops/action-gh-release@v3
|
|
||||||
with:
|
|
||||||
files: |
|
|
||||||
archive/**/*.tar.gz
|
|
||||||
archive/**/*.zip
|
|
||||||
archive/**/*.sigstore.json
|
|
||||||
prerelease: ${{!startsWith(github.ref, 'refs/tags/') || null}}
|
|
||||||
tag_name: ${{!startsWith(github.ref, 'refs/tags/') && 'nightly' || null}}
|
|
||||||
# Tag-push releases are created as drafts; the `publish` job un-drafts
|
|
||||||
# them only after all build jobs succeed, so watcher notifications
|
|
||||||
# don't fire on broken builds.
|
|
||||||
draft: ${{ startsWith(github.ref, 'refs/tags/') || null }}
|
|
||||||
body_path: release_body.md
|
|
||||||
|
|
||||||
publish:
|
|
||||||
name: Publish release
|
|
||||||
needs: [linux, windows, macos, freebsd, multiarch, release]
|
|
||||||
if: startsWith(github.ref, 'refs/tags/')
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
|
||||||
contents: write
|
|
||||||
steps:
|
|
||||||
- name: Un-draft release
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ github.token }}
|
|
||||||
run: gh release edit "${{ github.ref_name }}" --draft=false --latest --repo "${{ github.repository }}"
|
|
||||||
|
|
||||||
cleanup:
|
|
||||||
name: Cleanup failed release
|
|
||||||
needs: [linux, windows, macos, freebsd, multiarch, release]
|
|
||||||
if: failure() && startsWith(github.ref, 'refs/tags/') && github.run_attempt >= 3
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
permissions:
|
|
||||||
contents: write
|
|
||||||
steps:
|
|
||||||
- name: Delete draft release and tag
|
|
||||||
env:
|
|
||||||
GH_TOKEN: ${{ github.token }}
|
|
||||||
run: gh release delete "${{ github.ref_name }}" --yes --cleanup-tag --repo "${{ github.repository }}" || true
|
|
||||||
@@ -1,4 +0,0 @@
|
|||||||
# Funding platforms shown behind the repository's Sponsor button.
|
|
||||||
# https://docs.github.com/repositories/managing-your-repositorys-settings-and-features/customizing-your-repository/displaying-a-sponsor-button-in-your-repository
|
|
||||||
|
|
||||||
github: jcoffey-dev
|
|
||||||
@@ -1,43 +0,0 @@
|
|||||||
<!--
|
|
||||||
Thanks for contributing to INBUXA. CONTRIBUTING.md has the full guide; this
|
|
||||||
is the short version. Delete any section that does not apply.
|
|
||||||
-->
|
|
||||||
|
|
||||||
## Summary
|
|
||||||
|
|
||||||
<!-- What changes, and why. The why is the part that is hard to recover later. -->
|
|
||||||
|
|
||||||
## Related issues
|
|
||||||
|
|
||||||
<!-- e.g. Closes #123. Leave blank if there are none. -->
|
|
||||||
|
|
||||||
## Upstream files
|
|
||||||
|
|
||||||
<!--
|
|
||||||
Does this touch files that came from Stalwart? If so: is the change as small
|
|
||||||
as it can be, and is it marked with an `inbuxa:` comment saying which
|
|
||||||
requirement it serves? Every edit to an upstream file is a conflict waiting
|
|
||||||
at the next import, so it should be worth one.
|
|
||||||
-->
|
|
||||||
|
|
||||||
## Clean room
|
|
||||||
|
|
||||||
<!--
|
|
||||||
Only for changes to the rebuilt features in `crates/features`, or to the
|
|
||||||
hooks that serve them.
|
|
||||||
|
|
||||||
Confirm one:
|
|
||||||
- [ ] I have not read Stalwart's Enterprise-licensed source, and worked from
|
|
||||||
the specification in `docs/spec/features/`.
|
|
||||||
- [ ] I have read it. (Say so -- the change will be reviewed with that in
|
|
||||||
mind, or declined for the parts it touches. The project's claim of
|
|
||||||
independent creation is a record, and the record has to be true.)
|
|
||||||
-->
|
|
||||||
|
|
||||||
## Testing
|
|
||||||
|
|
||||||
<!--
|
|
||||||
What you ran. `cargo test -p tests` covers what needs nothing but a store;
|
|
||||||
say so if you ran any of the `#[ignore]`d suites from
|
|
||||||
docs/spec/container-tests.md, and which.
|
|
||||||
-->
|
|
||||||
+15
-38
@@ -1,42 +1,19 @@
|
|||||||
|
# To get started with Dependabot version updates, you'll need to specify which
|
||||||
|
# package ecosystems to update and where the package manifests are located.
|
||||||
|
# Please see the documentation for all configuration options:
|
||||||
|
# https://docs.github.com/code-security/dependabot/dependabot-version-updates/configuration-options-for-the-dependabot.yml-file
|
||||||
|
|
||||||
version: 2
|
version: 2
|
||||||
updates:
|
updates:
|
||||||
# Cargo. One entry: the workspace has a single lockfile at the root, and
|
- package-ecosystem: "cargo" # See documentation for possible values
|
||||||
# ~30 manifests that upstream bumps on every release -- pointing entries at
|
directory: "/" # Location of package manifests
|
||||||
# individual crates would find manifests with no lockfile beside them.
|
schedule:
|
||||||
#
|
interval: "weekly"
|
||||||
# Minor and patch arrive as one pull request a week. Majors are left out of
|
|
||||||
# the group on purpose: they are migrations rather than bumps, and each one
|
# Enable version updates for GitHub Actions
|
||||||
# deserves its own pull request and its own CI run.
|
- package-ecosystem: "github-actions"
|
||||||
- package-ecosystem: cargo
|
# Workflow files stored in the default location of `.github/workflows`
|
||||||
|
# You don't need to specify `/.github/workflows` for `directory`. You can use `directory: "/"`.
|
||||||
directory: "/"
|
directory: "/"
|
||||||
schedule:
|
schedule:
|
||||||
interval: weekly
|
interval: "weekly"
|
||||||
day: tuesday
|
|
||||||
time: "09:00"
|
|
||||||
timezone: Etc/UTC
|
|
||||||
open-pull-requests-limit: 5
|
|
||||||
groups:
|
|
||||||
minor-and-patch:
|
|
||||||
update-types:
|
|
||||||
- minor
|
|
||||||
- patch
|
|
||||||
- package-ecosystem: github-actions
|
|
||||||
directory: "/"
|
|
||||||
schedule:
|
|
||||||
interval: weekly
|
|
||||||
day: tuesday
|
|
||||||
time: "09:00"
|
|
||||||
timezone: Etc/UTC
|
|
||||||
groups:
|
|
||||||
actions:
|
|
||||||
patterns:
|
|
||||||
- "*"
|
|
||||||
# The Dockerfiles pin their base images, so this is what keeps a published
|
|
||||||
# image off a stale base between releases.
|
|
||||||
- package-ecosystem: docker
|
|
||||||
directory: "/"
|
|
||||||
schedule:
|
|
||||||
interval: weekly
|
|
||||||
day: tuesday
|
|
||||||
time: "09:00"
|
|
||||||
timezone: Etc/UTC
|
|
||||||
|
|||||||
+558
-42
@@ -1,51 +1,567 @@
|
|||||||
# What CI can check without a mail server's worth of infrastructure.
|
name: "CI"
|
||||||
#
|
|
||||||
# The build, and that every test target compiles. It deliberately does not
|
|
||||||
# *run* the test suites: the unit tests only build with the integration crate
|
|
||||||
# in the graph, because that is what switches on the `test_mode` features they
|
|
||||||
# rely on (docs/spec/SPEC.md 2.2b), and the integration suites need a `STORE`,
|
|
||||||
# fixed ports, and in most cases a container apiece (docs/spec/
|
|
||||||
# container-tests.md). Running them here would mean either a green tick that
|
|
||||||
# skipped everything, or a red one that means "the runner has no Redis".
|
|
||||||
#
|
|
||||||
# So this catches what it can honestly catch -- code that does not compile,
|
|
||||||
# including test code -- and the suites are run by hand, one at a time, as
|
|
||||||
# that page describes. If that changes, it changes because someone made the
|
|
||||||
# suites runnable unattended, not because CI started ignoring failures.
|
|
||||||
name: CI
|
|
||||||
on:
|
on:
|
||||||
|
workflow_dispatch:
|
||||||
|
inputs:
|
||||||
|
Docker:
|
||||||
|
required: false
|
||||||
|
default: false
|
||||||
|
type: boolean
|
||||||
|
Release:
|
||||||
|
required: false
|
||||||
|
default: false
|
||||||
|
type: boolean
|
||||||
push:
|
push:
|
||||||
branches: [main]
|
tags: ["v*.*.*"]
|
||||||
pull_request:
|
|
||||||
# Lets CI be run by hand against any ref, including one that predates a CI
|
env:
|
||||||
# change, without pushing an empty commit to move it.
|
SCCACHE_GHA_ENABLED: true
|
||||||
workflow_dispatch:
|
RUSTC_WRAPPER: sccache
|
||||||
|
CARGO_TERM_COLOR: always
|
||||||
|
CARGO_NET_RETRY: 10
|
||||||
|
CARGO_NET_GIT_FETCH_WITH_CLI: true
|
||||||
|
AWS_LC_SYS_PREBUILT_NASM: 1
|
||||||
|
|
||||||
# A second push to a branch cancels the run still going for the first: the
|
|
||||||
# older run's answer is about code nobody is looking at any more.
|
|
||||||
concurrency:
|
concurrency:
|
||||||
group: ci-${{ github.ref }}
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
cancel-in-progress: true
|
cancel-in-progress: true
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build:
|
multiarch:
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- variant: gnu
|
||||||
|
- variant: musl
|
||||||
|
name: Merge image / ${{matrix.variant}}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
id-token: write
|
||||||
|
contents: read
|
||||||
|
attestations: write
|
||||||
|
packages: write
|
||||||
|
needs: [linux]
|
||||||
|
if: github.event_name == 'push' || inputs.Docker
|
||||||
|
steps:
|
||||||
|
- name: Install Cosign
|
||||||
|
uses: sigstore/[email protected]
|
||||||
|
- name: Log In to GitHub Container Registry
|
||||||
|
uses: docker/login-action@v4
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
|
username: ${{github.repository_owner}}
|
||||||
|
password: ${{github.token}}
|
||||||
|
|
||||||
|
- name: Log In to DockerHub
|
||||||
|
uses: docker/login-action@v4
|
||||||
|
with:
|
||||||
|
username: ${{secrets.DOCKERHUB_USERNAME}}
|
||||||
|
password: ${{secrets.DOCKERHUB_TOKEN}}
|
||||||
|
|
||||||
|
- name: Download ${{matrix.variant}} meta bake definition
|
||||||
|
uses: actions/download-artifact@v8
|
||||||
|
with:
|
||||||
|
name: bake-meta-${{matrix.variant}}
|
||||||
|
path: ${{ runner.temp }}/${{matrix.variant}}
|
||||||
|
|
||||||
|
- name: Download ${{matrix.variant}} digests
|
||||||
|
uses: actions/download-artifact@v8
|
||||||
|
with:
|
||||||
|
path: ${{ runner.temp }}/${{matrix.variant}}/digests
|
||||||
|
pattern: digests-${{matrix.variant}}-*
|
||||||
|
merge-multiple: true
|
||||||
|
|
||||||
|
- name: Create ${{matrix.variant}} manifest list and push
|
||||||
|
working-directory: ${{ runner.temp }}/${{matrix.variant}}/digests
|
||||||
|
run: |
|
||||||
|
docker buildx imagetools create $(jq -cr '.target."docker-metadata-action".tags | map(select(startswith("ghcr.io/${{github.repository}}")) | "-t " + .) | join(" ")' ${{ runner.temp }}/${{matrix.variant}}/bake-meta.json) \
|
||||||
|
$(printf 'ghcr.io/${{github.repository}}@sha256:%s ' *)
|
||||||
|
docker buildx imagetools create $(jq -cr '.target."docker-metadata-action".tags | map(select(startswith("index.docker.io/${{github.repository}}")) | "-t " + .) | join(" ")' ${{ runner.temp }}/${{matrix.variant}}/bake-meta.json) \
|
||||||
|
$(printf 'index.docker.io/${{github.repository}}@sha256:%s ' *)
|
||||||
|
|
||||||
|
- name: Inspect ${{matrix.variant}} image
|
||||||
|
id: manifest-digest
|
||||||
|
run: |
|
||||||
|
docker buildx imagetools inspect --format '{{json .Manifest}}' ghcr.io/${{github.repository}}:$(jq -r '.target."docker-metadata-action".args.DOCKER_META_VERSION' ${{ runner.temp }}/${{matrix.variant}}/bake-meta.json) | jq -r '.digest' > GHCR_DIGEST_SHA
|
||||||
|
echo "GHCR_DIGEST_SHA=$(cat GHCR_DIGEST_SHA)" | tee -a "${GITHUB_ENV}"
|
||||||
|
docker buildx imagetools inspect --format '{{json .Manifest}}' index.docker.io/${{github.repository}}:$(jq -r '.target."docker-metadata-action".args.DOCKER_META_VERSION' ${{ runner.temp }}/${{matrix.variant}}/bake-meta.json) | jq -r '.digest' > DOCKERHUB_DIGEST_SHA
|
||||||
|
echo "DOCKERHUB_DIGEST_SHA=$(cat DOCKERHUB_DIGEST_SHA)" | tee -a "${GITHUB_ENV}"
|
||||||
|
cosign sign --yes $(jq --arg GHCR_DIGEST_SHA "$(cat GHCR_DIGEST_SHA)" -cr '.target."docker-metadata-action".tags | map(select(startswith("ghcr.io/${{github.repository}}")) | . + "@" + $GHCR_DIGEST_SHA) | join(" ")' ${{ runner.temp }}/${{matrix.variant}}/bake-meta.json)
|
||||||
|
cosign sign --yes $(jq --arg DOCKERHUB_DIGEST_SHA "$(cat DOCKERHUB_DIGEST_SHA)" -cr '.target."docker-metadata-action".tags | map(select(startswith("index.docker.io/${{github.repository}}")) | . + "@" + $DOCKERHUB_DIGEST_SHA) | join(" ")' ${{ runner.temp }}/${{matrix.variant}}/bake-meta.json)
|
||||||
|
|
||||||
|
- name: Attest GHCR
|
||||||
|
uses: actions/attest-build-provenance@v4
|
||||||
|
with:
|
||||||
|
subject-name: ghcr.io/${{github.repository}}
|
||||||
|
subject-digest: ${{ env.GHCR_DIGEST_SHA }}
|
||||||
|
push-to-registry: true
|
||||||
|
|
||||||
|
- name: Attest Dockerhub
|
||||||
|
uses: actions/attest-build-provenance@v4
|
||||||
|
with:
|
||||||
|
subject-name: index.docker.io/${{github.repository}}
|
||||||
|
subject-digest: ${{ env.DOCKERHUB_DIGEST_SHA }}
|
||||||
|
push-to-registry: true
|
||||||
|
|
||||||
|
linux:
|
||||||
|
permissions:
|
||||||
|
id-token: write
|
||||||
|
contents: write
|
||||||
|
attestations: write
|
||||||
|
packages: write
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- target: x86_64-unknown-linux-gnu
|
||||||
|
platform: linux/amd64
|
||||||
|
suffix: ""
|
||||||
|
build_env: ""
|
||||||
|
- target: x86_64-unknown-linux-musl
|
||||||
|
platform: linux/amd64
|
||||||
|
suffix: "-alpine"
|
||||||
|
build_env: ""
|
||||||
|
- target: aarch64-unknown-linux-gnu
|
||||||
|
platform: linux/arm64
|
||||||
|
suffix: ""
|
||||||
|
build_env: "JEMALLOC_SYS_WITH_LG_PAGE=16 "
|
||||||
|
- target: aarch64-unknown-linux-musl
|
||||||
|
platform: linux/arm64
|
||||||
|
suffix: "-alpine"
|
||||||
|
build_env: "JEMALLOC_SYS_WITH_LG_PAGE=16 "
|
||||||
|
- target: armv7-unknown-linux-gnueabihf
|
||||||
|
platform: linux/arm/v7
|
||||||
|
suffix: ""
|
||||||
|
build_env: "JEMALLOC_SYS_WITH_LG_PAGE=16 "
|
||||||
|
- target: armv7-unknown-linux-musleabihf
|
||||||
|
platform: linux/arm/v7
|
||||||
|
suffix: "-alpine"
|
||||||
|
build_env: "JEMALLOC_SYS_WITH_LG_PAGE=16 "
|
||||||
|
- target: arm-unknown-linux-gnueabihf
|
||||||
|
platform: linux/arm/v6
|
||||||
|
suffix: ""
|
||||||
|
build_env: ""
|
||||||
|
- target: arm-unknown-linux-musleabihf
|
||||||
|
platform: linux/arm/v6
|
||||||
|
suffix: "-alpine"
|
||||||
|
build_env: ""
|
||||||
|
name: Build / ${{matrix.target}}
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
# Every `uses:` here is pinned to a full commit SHA, with the release it
|
- name: Checkout
|
||||||
# belongs to in the trailing comment. A tag is a mutable pointer, so
|
uses: actions/checkout@v7
|
||||||
# trusting `@v7` is trusting every future version of that action,
|
|
||||||
# including one pushed by whoever compromises the account. Dependabot
|
- name: Free disk space (heavy ARM targets)
|
||||||
# updates both halves together -- do not "simplify" a pin back to a tag.
|
if: contains(matrix.target, 'arm') || contains(matrix.target, 'aarch64')
|
||||||
- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7.0.1
|
run: |
|
||||||
- uses: Swatinem/rust-cache@49a0bdc70d2e1b713ca9e2869b211fcce03d3c1c # v2.9.2
|
df -h /mnt /
|
||||||
- name: System dependencies
|
sudo rm -rf /usr/share/dotnet /opt/ghc /usr/local/lib/android /usr/local/.ghcup /usr/local/share/powershell /usr/share/swift /opt/hostedtoolcache/CodeQL
|
||||||
# foundationdb and the search backends are off by default, but the
|
sudo docker image prune --all --force || true
|
||||||
# default feature set still links against the system's C libraries.
|
df -h /mnt /
|
||||||
run: sudo apt-get update && sudo apt-get install -y --no-install-recommends clang
|
|
||||||
- name: Build the server
|
- name: Add swap (heavy ARM targets)
|
||||||
run: cargo build -p inbuxa --locked
|
if: contains(matrix.target, 'arm') || contains(matrix.target, 'aarch64')
|
||||||
- name: Compile every test target
|
run: |
|
||||||
# `--no-run` is the point: it builds the unit tests and the integration
|
mnt_avail=$(df --output=avail -k /mnt | tail -1)
|
||||||
# crate together, which is the combination that resolves the test
|
if [ "$mnt_avail" -lt 18874368 ]; then
|
||||||
# features, and stops short of running anything that wants a store.
|
echo "Insufficient space on /mnt (${mnt_avail}K available), aborting swap setup"
|
||||||
run: cargo test --workspace --locked --no-run
|
exit 1
|
||||||
|
fi
|
||||||
|
sudo fallocate -l 16G /mnt/swapfile
|
||||||
|
sudo chmod 600 /mnt/swapfile
|
||||||
|
sudo mkswap /mnt/swapfile
|
||||||
|
sudo swapon /mnt/swapfile
|
||||||
|
sudo sysctl vm.swappiness=80
|
||||||
|
free -h
|
||||||
|
swapon --show
|
||||||
|
|
||||||
|
- name: Set up QEMU
|
||||||
|
uses: docker/setup-qemu-action@v4
|
||||||
|
with:
|
||||||
|
platforms: "arm64,arm"
|
||||||
|
|
||||||
|
- name: Set up Docker Buildx
|
||||||
|
uses: docker/setup-buildx-action@v4
|
||||||
|
with:
|
||||||
|
buildkitd-config-inline: |
|
||||||
|
[registry."docker.io"]
|
||||||
|
mirrors = ["https://mirror.gcr.io"]
|
||||||
|
driver-opts: |
|
||||||
|
network=host
|
||||||
|
|
||||||
|
- name: Log In to GitHub Container Registry
|
||||||
|
uses: docker/login-action@v4
|
||||||
|
with:
|
||||||
|
registry: ghcr.io
|
||||||
|
username: ${{github.repository_owner}}
|
||||||
|
password: ${{github.token}}
|
||||||
|
|
||||||
|
- name: Log In to DockerHub
|
||||||
|
uses: docker/login-action@v4
|
||||||
|
with:
|
||||||
|
username: ${{secrets.DOCKERHUB_USERNAME}}
|
||||||
|
password: ${{secrets.DOCKERHUB_TOKEN}}
|
||||||
|
|
||||||
|
- name: Calculate shasum of external deps
|
||||||
|
id: cal-dep-shasum
|
||||||
|
run: |
|
||||||
|
echo "checksum=$(yq -p toml -oy '.package[] | select((.source | contains("")) or (.checksum | contains("")))' Cargo.lock | sha256sum | awk '{print $1}')" >> "$GITHUB_OUTPUT"
|
||||||
|
|
||||||
|
- name: Cache apt
|
||||||
|
uses: actions/[email protected]
|
||||||
|
id: apt-cache
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
var-cache-apt
|
||||||
|
var-lib-apt
|
||||||
|
key: apt-cache-${{ hashFiles('Dockerfile.build') }}
|
||||||
|
|
||||||
|
- name: Cache Cargo
|
||||||
|
uses: actions/[email protected]
|
||||||
|
id: cargo-cache
|
||||||
|
with:
|
||||||
|
path: |
|
||||||
|
usr-local-cargo-registry
|
||||||
|
usr-local-cargo-git
|
||||||
|
key: cargo-cache-${{ steps.cal-dep-shasum.outputs.checksum }}
|
||||||
|
|
||||||
|
- name: Inject cache into docker
|
||||||
|
uses: reproducible-containers/[email protected]
|
||||||
|
with:
|
||||||
|
cache-map: |
|
||||||
|
{
|
||||||
|
"var-cache-apt": "/var/cache/apt",
|
||||||
|
"var-lib-apt": "/var/lib/apt",
|
||||||
|
"usr-local-cargo-registry": "/usr/local/cargo/registry",
|
||||||
|
"usr-local-cargo-git": "/usr/local/cargo/git"
|
||||||
|
}
|
||||||
|
skip-extraction: ${{ steps.cargo-cache.outputs.cache-hit }} && ${{ steps.apt-cache.outputs.cache-hit }}
|
||||||
|
|
||||||
|
- name: Extract Metadata for Docker
|
||||||
|
uses: docker/metadata-action@v6
|
||||||
|
id: meta
|
||||||
|
with:
|
||||||
|
images: |
|
||||||
|
index.docker.io/${{github.repository}}
|
||||||
|
ghcr.io/${{github.repository}}
|
||||||
|
flavor: |
|
||||||
|
suffix=${{matrix.suffix}},onlatest=true
|
||||||
|
tags: |
|
||||||
|
type=ref,event=tag
|
||||||
|
type=ref,event=branch,prefix=branch-
|
||||||
|
type=edge,branch=main
|
||||||
|
type=semver,pattern=v{{major}}.{{minor}}
|
||||||
|
|
||||||
|
- name: Build Artifact
|
||||||
|
id: bake
|
||||||
|
uses: docker/bake-action@v7
|
||||||
|
env:
|
||||||
|
DOCKER_BUILD_RECORD_UPLOAD: false
|
||||||
|
TARGET: ${{matrix.target}}
|
||||||
|
GHCR_REPO: ghcr.io/${{github.repository}}
|
||||||
|
BUILD_ENV: ${{matrix.build_env}}
|
||||||
|
DOCKER_PLATFORM: ${{matrix.platform}}
|
||||||
|
SUFFIX: ${{matrix.suffix}}
|
||||||
|
with:
|
||||||
|
source: .
|
||||||
|
set: |
|
||||||
|
*.tags=
|
||||||
|
image.output=type=image,"name=ghcr.io/${{github.repository}},index.docker.io/${{github.repository}}",push-by-digest=true,name-canonical=true,push=true,compression=zstd,compression-level=9,force-compression=true,oci-mediatypes=true
|
||||||
|
files: |
|
||||||
|
docker-bake.hcl
|
||||||
|
${{ steps.meta.outputs.bake-file }}
|
||||||
|
targets: ${{(github.event_name == 'push' || inputs.Docker) && 'build,image' || 'build'}}
|
||||||
|
|
||||||
|
- name: Upload Artifacts
|
||||||
|
uses: actions/[email protected]
|
||||||
|
with:
|
||||||
|
name: artifact-${{matrix.target}}
|
||||||
|
path: |
|
||||||
|
artifact
|
||||||
|
!artifact/*.json
|
||||||
|
|
||||||
|
- name: Export digest & Rename meta bake definition file
|
||||||
|
if: github.event_name == 'push' || inputs.Docker
|
||||||
|
run: |
|
||||||
|
mv "${{ steps.meta.outputs.bake-file }}" "${{ runner.temp }}/bake-meta.json"
|
||||||
|
mkdir -p ${{ runner.temp }}/digests
|
||||||
|
digest="${{ fromJSON(steps.bake.outputs.metadata).image['containerimage.digest'] }}"
|
||||||
|
touch "${{ runner.temp }}/digests/${digest#sha256:}"
|
||||||
|
|
||||||
|
- name: Upload digest
|
||||||
|
if: github.event_name == 'push' || inputs.Docker
|
||||||
|
uses: actions/[email protected]
|
||||||
|
with:
|
||||||
|
name: digests-${{matrix.suffix == '' && 'gnu' || 'musl'}}-${{ matrix.target }}
|
||||||
|
path: ${{ runner.temp }}/digests/*
|
||||||
|
if-no-files-found: error
|
||||||
|
retention-days: 1
|
||||||
|
|
||||||
|
- name: Upload GNU meta bake definition
|
||||||
|
uses: actions/[email protected]
|
||||||
|
if: (github.event_name == 'push' || inputs.Docker) && endsWith(matrix.target,'gnu') && startsWith(matrix.target,'x86')
|
||||||
|
with:
|
||||||
|
name: bake-meta-gnu
|
||||||
|
path: ${{ runner.temp }}/bake-meta.json
|
||||||
|
if-no-files-found: error
|
||||||
|
retention-days: 1
|
||||||
|
|
||||||
|
- name: Upload musl meta bake definition
|
||||||
|
uses: actions/[email protected]
|
||||||
|
if: (github.event_name == 'push' || inputs.Docker) && endsWith(matrix.target,'musl') && startsWith(matrix.target,'x86')
|
||||||
|
with:
|
||||||
|
name: bake-meta-musl
|
||||||
|
path: ${{ runner.temp }}/bake-meta.json
|
||||||
|
if-no-files-found: error
|
||||||
|
retention-days: 1
|
||||||
|
|
||||||
|
windows:
|
||||||
|
name: Build / ${{matrix.target}}
|
||||||
|
runs-on: windows-latest
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
# - target: aarch64-pc-windows-msvc
|
||||||
|
- target: x86_64-pc-windows-msvc
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v7
|
||||||
|
|
||||||
|
- name: Run sccache-cache
|
||||||
|
uses: mozilla-actions/[email protected]
|
||||||
|
with:
|
||||||
|
disable_annotations: true
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
run: |
|
||||||
|
rustup target add ${{matrix.target}}
|
||||||
|
cargo build --release --target ${{matrix.target}} -p stalwart --no-default-features --features "sqlite postgres mysql rocks s3 redis azure nats"
|
||||||
|
mkdir -p artifacts
|
||||||
|
mv ./target/${{matrix.target}}/release/stalwart.exe ./artifacts/stalwart.exe
|
||||||
|
|
||||||
|
- name: Upload Artifacts
|
||||||
|
uses: actions/[email protected]
|
||||||
|
with:
|
||||||
|
name: artifact-${{matrix.target}}
|
||||||
|
path: artifacts
|
||||||
|
|
||||||
|
macos:
|
||||||
|
name: Build / ${{matrix.target}}
|
||||||
|
runs-on: macos-latest
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- target: aarch64-apple-darwin
|
||||||
|
- target: x86_64-apple-darwin
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v7
|
||||||
|
|
||||||
|
- name: Run sccache-cache
|
||||||
|
uses: mozilla-actions/[email protected]
|
||||||
|
with:
|
||||||
|
disable_annotations: true
|
||||||
|
|
||||||
|
#- name: Build FoundationDB Edition
|
||||||
|
# env:
|
||||||
|
# GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
# run: |
|
||||||
|
# rustup target add ${{matrix.target}}
|
||||||
|
# # Pin FoundationDB 7.4.x (Apple publishes these as prereleases)
|
||||||
|
# curl --retry 5 -Lso foundationdb.pkg "$(gh api -X GET /repos/apple/foundationdb/releases --jq '[.[] | select(.tag_name | startswith("7.4."))] | sort_by(.tag_name | split(".") | map(tonumber)) | reverse | .[0].assets[] | select(.name | test("${{startsWith(matrix.target, 'x86') && 'x86_64' || 'arm64'}}" + ".pkg$")) | .browser_download_url')"
|
||||||
|
# echo "=== Package contents ==="
|
||||||
|
# pkgutil --payload-files foundationdb.pkg || true
|
||||||
|
# sudo installer -allowUntrusted -verbose -dumplog -pkg foundationdb.pkg -target /
|
||||||
|
# cargo build --release --target ${{matrix.target}} -p stalwart --no-default-features --features "foundationdb s3 redis nats"
|
||||||
|
# mkdir -p artifacts
|
||||||
|
# mv ./target/${{matrix.target}}/release/stalwart ./artifacts/stalwart-foundationdb
|
||||||
|
|
||||||
|
- name: Build
|
||||||
|
run: |
|
||||||
|
rustup target add ${{matrix.target}}
|
||||||
|
cargo build --release --target ${{matrix.target}} -p stalwart --no-default-features --features "sqlite postgres mysql rocks s3 redis azure nats"
|
||||||
|
mkdir -p artifacts
|
||||||
|
mv ./target/${{matrix.target}}/release/stalwart ./artifacts/stalwart
|
||||||
|
|
||||||
|
- name: Upload Artifacts
|
||||||
|
uses: actions/[email protected]
|
||||||
|
with:
|
||||||
|
name: artifact-${{matrix.target}}
|
||||||
|
path: artifacts
|
||||||
|
|
||||||
|
freebsd:
|
||||||
|
name: Build / ${{matrix.target}}
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
timeout-minutes: 360
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
include:
|
||||||
|
- target: x86_64-unknown-freebsd
|
||||||
|
arch: x86_64
|
||||||
|
# - target: aarch64-unknown-freebsd
|
||||||
|
# arch: aarch64
|
||||||
|
steps:
|
||||||
|
- name: Checkout
|
||||||
|
uses: actions/checkout@v7
|
||||||
|
|
||||||
|
- name: Build in FreeBSD VM
|
||||||
|
uses: vmactions/freebsd-vm@v1
|
||||||
|
with:
|
||||||
|
release: "15.1"
|
||||||
|
arch: ${{matrix.arch}}
|
||||||
|
usesh: true
|
||||||
|
mem: 14336
|
||||||
|
cpu: 4
|
||||||
|
sync: rsync
|
||||||
|
copyback: true
|
||||||
|
# gmake: required by jemalloc-sys on BSD hosts
|
||||||
|
# llvm: provides libclang for bindgen (librocksdb-sys)
|
||||||
|
# rust: libsqlite3-sys 0.38 uses cfg_select!, stabilized in Rust
|
||||||
|
# 1.95. The default 'quarterly' pkg repo still ships rust 1.94, so
|
||||||
|
# switch to the 'latest' repo (currently 1.96.1). rustup is not an
|
||||||
|
# option here: aarch64-unknown-freebsd has no rustup toolchains yet.
|
||||||
|
prepare: |
|
||||||
|
set -e
|
||||||
|
mkdir -p /usr/local/etc/pkg/repos
|
||||||
|
echo 'FreeBSD: { url: "pkg+https://pkg.freebsd.org/${ABI}/latest", mirror_type: "srv" }' > /usr/local/etc/pkg/repos/FreeBSD.conf
|
||||||
|
pkg update -f
|
||||||
|
env ASSUME_ALWAYS_YES=yes pkg bootstrap -f
|
||||||
|
pkg update -f
|
||||||
|
pkg install -y rust gmake llvm rocksdb
|
||||||
|
rustc --version
|
||||||
|
run: |
|
||||||
|
set -e
|
||||||
|
export CARGO_TARGET_DIR=/tmp/target
|
||||||
|
export CARGO_TERM_COLOR=always
|
||||||
|
export CARGO_NET_RETRY=10
|
||||||
|
cargo build --release -p stalwart --no-default-features --features "sqlite postgres mysql rocks s3 redis azure nats"
|
||||||
|
mkdir -p artifacts
|
||||||
|
cp /tmp/target/release/stalwart artifacts/stalwart
|
||||||
|
|
||||||
|
- name: Upload Artifacts
|
||||||
|
uses: actions/[email protected]
|
||||||
|
with:
|
||||||
|
name: artifact-${{matrix.target}}
|
||||||
|
path: artifacts
|
||||||
|
|
||||||
|
release:
|
||||||
|
name: Release
|
||||||
|
permissions:
|
||||||
|
id-token: write
|
||||||
|
contents: write
|
||||||
|
attestations: write
|
||||||
|
if: github.event_name == 'push' || inputs.Release
|
||||||
|
needs: [linux, windows, macos, freebsd]
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
steps:
|
||||||
|
# Must run before artifacts are downloaded — checkout cleans the workspace.
|
||||||
|
- name: Checkout (for CHANGELOG)
|
||||||
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
|
uses: actions/checkout@v7
|
||||||
|
|
||||||
|
- name: Download Artifacts
|
||||||
|
uses: actions/download-artifact@v8
|
||||||
|
with:
|
||||||
|
path: archive
|
||||||
|
pattern: artifact-*
|
||||||
|
|
||||||
|
- name: Compress
|
||||||
|
run: |
|
||||||
|
set -eux
|
||||||
|
BASE_DIR="$(pwd)/archive"
|
||||||
|
compress_files() {
|
||||||
|
local dir="$1"
|
||||||
|
local archive_dir_name="${dir#artifact-}"
|
||||||
|
cd "$dir"
|
||||||
|
# Process each file in the directory
|
||||||
|
for file in `ls`; do
|
||||||
|
filename="${file%.*}"
|
||||||
|
extension="${file##*.}"
|
||||||
|
if [ "$extension" = "exe" ]; then
|
||||||
|
7z a -tzip "${filename}-${archive_dir_name}.zip" "$file" > /dev/null
|
||||||
|
else
|
||||||
|
tar -czf "${filename}-${archive_dir_name}.tar.gz" "$file"
|
||||||
|
fi
|
||||||
|
done
|
||||||
|
cd $BASE_DIR
|
||||||
|
}
|
||||||
|
cd $BASE_DIR
|
||||||
|
for arch_dir in `ls`; do
|
||||||
|
dir_name=$(basename "$arch_dir")
|
||||||
|
compress_files "$dir_name"
|
||||||
|
done
|
||||||
|
|
||||||
|
- name: Attest binary
|
||||||
|
id: attest
|
||||||
|
uses: actions/attest-build-provenance@v4
|
||||||
|
with:
|
||||||
|
subject-path: |
|
||||||
|
archive/**/*.tar.gz
|
||||||
|
archive/**/*.zip
|
||||||
|
|
||||||
|
- name: Use cosign to sign existing artifacts
|
||||||
|
uses: sigstore/[email protected]
|
||||||
|
with:
|
||||||
|
inputs: |
|
||||||
|
archive/**/*.tar.gz
|
||||||
|
archive/**/*.zip
|
||||||
|
|
||||||
|
- name: Build release body
|
||||||
|
run: |
|
||||||
|
if [ "${{ startsWith(github.ref, 'refs/tags/') }}" = "true" ]; then
|
||||||
|
awk '/^## \[/{c++} c==1' CHANGELOG.md > release_body.md
|
||||||
|
echo "" >> release_body.md
|
||||||
|
else
|
||||||
|
: > release_body.md
|
||||||
|
fi
|
||||||
|
cat >> release_body.md <<EOF
|
||||||
|
<hr />
|
||||||
|
|
||||||
|
### Check binary attestation [here](${{ steps.attest.outputs.attestation-url }})
|
||||||
|
EOF
|
||||||
|
|
||||||
|
- name: Release
|
||||||
|
uses: softprops/action-gh-release@v3
|
||||||
|
with:
|
||||||
|
files: |
|
||||||
|
archive/**/*.tar.gz
|
||||||
|
archive/**/*.zip
|
||||||
|
archive/**/*.sigstore.json
|
||||||
|
prerelease: ${{!startsWith(github.ref, 'refs/tags/') || null}}
|
||||||
|
tag_name: ${{!startsWith(github.ref, 'refs/tags/') && 'nightly' || null}}
|
||||||
|
# Tag-push releases are created as drafts; the `publish` job un-drafts
|
||||||
|
# them only after all build jobs succeed, so watcher notifications
|
||||||
|
# don't fire on broken builds.
|
||||||
|
draft: ${{ startsWith(github.ref, 'refs/tags/') || null }}
|
||||||
|
body_path: release_body.md
|
||||||
|
|
||||||
|
publish:
|
||||||
|
name: Publish release
|
||||||
|
needs: [linux, windows, macos, freebsd, multiarch, release]
|
||||||
|
if: startsWith(github.ref, 'refs/tags/')
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
steps:
|
||||||
|
- name: Un-draft release
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
run: gh release edit "${{ github.ref_name }}" --draft=false --latest --repo "${{ github.repository }}"
|
||||||
|
|
||||||
|
cleanup:
|
||||||
|
name: Cleanup failed release
|
||||||
|
needs: [linux, windows, macos, freebsd, multiarch, release]
|
||||||
|
if: failure() && startsWith(github.ref, 'refs/tags/') && github.run_attempt >= 3
|
||||||
|
runs-on: ubuntu-latest
|
||||||
|
permissions:
|
||||||
|
contents: write
|
||||||
|
steps:
|
||||||
|
- name: Delete draft release and tag
|
||||||
|
env:
|
||||||
|
GH_TOKEN: ${{ github.token }}
|
||||||
|
run: gh release delete "${{ github.ref_name }}" --yes --cleanup-tag --repo "${{ github.repository }}" || true
|
||||||
|
|||||||
@@ -1,7 +1,4 @@
|
|||||||
/target
|
/target
|
||||||
# Release binaries built by hand: ~100 MB each, and a public repository is
|
|
||||||
# the wrong place for them.
|
|
||||||
/artifact
|
|
||||||
*.failed
|
*.failed
|
||||||
*_failed
|
*_failed
|
||||||
run.sh
|
run.sh
|
||||||
@@ -10,9 +7,3 @@ run.sh
|
|||||||
!.gitattributes
|
!.gitattributes
|
||||||
!.github
|
!.github
|
||||||
CLAUDE.md
|
CLAUDE.md
|
||||||
|
|
||||||
# The cutover rehearsal writes its fixture and state here.
|
|
||||||
tools/fork/cutover-rehearsal/__pycache__/
|
|
||||||
tools/fork/cutover-rehearsal/before.json
|
|
||||||
tools/fork/cutover-rehearsal/phase2_notes.json
|
|
||||||
tools/fork/__pycache__/
|
|
||||||
|
|||||||
@@ -2,6 +2,39 @@
|
|||||||
|
|
||||||
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).
|
All notable changes to this project will be documented in this file. This project adheres to [Semantic Versioning](http://semver.org/).
|
||||||
|
|
||||||
|
## [0.16.23] - 2026-09-21
|
||||||
|
|
||||||
|
If you are upgrading from v0.16.x, replace the binary (or run `docker pull`). If you are upgrading from v0.15.x and below, please read the [upgrading documentation](https://github.com/stalwartlabs/stalwart/blob/main/UPGRADING/v0_16.md) for more information on how to upgrade from previous versions.
|
||||||
|
|
||||||
|
## Added
|
||||||
|
- Expressions: `bit_and` function.
|
||||||
|
|
||||||
|
## Changed
|
||||||
|
|
||||||
|
## Fixed
|
||||||
|
- MTA:
|
||||||
|
- A mailing list whose recipients include another mailing list is accepted at `RCPT TO` and then rejected at local delivery with `550 5.5.0 Mailbox not found`.
|
||||||
|
- DMARC aggregate reports carry two `spf` elements per record and the `version` element of a DMARC aggregate report is written as `1` instead of `1.0`.
|
||||||
|
- DSNs generated for an alias rewrite or a list expansion emit a doubled `addr-type` in `Original-Recipient` (`rfc822;rfc822;[email protected]`).
|
||||||
|
- DSNs that cannot be written to the store are discarded, the recipients are flagged as notified and the original message is removed from the queue, losing both the bounce and the message.
|
||||||
|
- POP3:
|
||||||
|
- `TOP msg n` counts the `n` lines from the first byte of the message instead of from the first byte of the body.
|
||||||
|
- A message whose very first line begins with `.` is not byte-stuffed.
|
||||||
|
- Spam filter: Moving or copying a message from one account into another creates no training sample, so the classifier never learns from it.
|
||||||
|
- Sieve: `envelope "orcpt"` yields the bare address for an `ORCPT` supplied over SMTP. It now carries the `addr-type` prefix in every case, as required by RFC 6009.
|
||||||
|
- ACME: The `_acme-challenge` TXT records published for a DNS-01 authorization are never removed.
|
||||||
|
- DNS: The DNSSEC resolver queries a single nameserver at a time, working around a `hickory-resolver` race that cancels the TCP retry when two nameservers return a truncated response in parallel.
|
||||||
|
- Troubleshoot tool:
|
||||||
|
- MX records are resolved through the DNSSEC-validating resolver, matching the resolver used by the delivery path.
|
||||||
|
- A TLSA lookup that fails or returns bogus records stops the delivery attempt for that host, instead of continuing without DANE.
|
||||||
|
- OIDC: Bearer tokens that carry no `email`, `preferred_username` or `upn` claim are always authenticated against the default directory.
|
||||||
|
- Meilisearch: A confirmation timeout is treated as a failed write even when `failOnTimeout` is disabled, so an index whose batches take longer than `pollInterval` x `maxRetries` never completes an indexing task and resubmits the same batch indefinitely.
|
||||||
|
- WebUI: A failed update no longer takes an `Application` offline.
|
||||||
|
- FoundationDB: The cached read version is invalidated when any broadcast is received from another node.
|
||||||
|
- Redis:
|
||||||
|
- On a cluster, the rate limiter and the blob upload quota issue `INCR` and `EXPIRE` as a `MULTI`/`EXEC` transaction, whose `MOVED` redirects collapse into a single `EXECABORT` that never refreshes the slot map.
|
||||||
|
- A connection that fails because it is addressing the wrong server is returned to the pool and reused, since the recycle check only issues `PING`.
|
||||||
|
|
||||||
## [0.16.22] - 2026-09-13
|
## [0.16.22] - 2026-09-13
|
||||||
|
|
||||||
If you are upgrading from v0.16.x, replace the binary (or run `docker pull`). If you are upgrading from v0.15.x and below, please read the [upgrading documentation](https://github.com/stalwartlabs/stalwart/blob/main/UPGRADING/v0_16.md) for more information on how to upgrade from previous versions.
|
If you are upgrading from v0.16.x, replace the binary (or run `docker pull`). If you are upgrading from v0.15.x and below, please read the [upgrading documentation](https://github.com/stalwartlabs/stalwart/blob/main/UPGRADING/v0_16.md) for more information on how to upgrade from previous versions.
|
||||||
|
|||||||
@@ -1,128 +0,0 @@
|
|||||||
# Contributor Covenant Code of Conduct
|
|
||||||
|
|
||||||
## Our Pledge
|
|
||||||
|
|
||||||
We as members, contributors, and leaders pledge to make participation in our
|
|
||||||
community a harassment-free experience for everyone, regardless of age, body
|
|
||||||
size, visible or invisible disability, ethnicity, sex characteristics, gender
|
|
||||||
identity and expression, level of experience, education, socio-economic status,
|
|
||||||
nationality, personal appearance, race, religion, or sexual identity
|
|
||||||
and orientation.
|
|
||||||
|
|
||||||
We pledge to act and interact in ways that contribute to an open, welcoming,
|
|
||||||
diverse, inclusive, and healthy community.
|
|
||||||
|
|
||||||
## Our Standards
|
|
||||||
|
|
||||||
Examples of behavior that contributes to a positive environment for our
|
|
||||||
community include:
|
|
||||||
|
|
||||||
* Demonstrating empathy and kindness toward other people
|
|
||||||
* Being respectful of differing opinions, viewpoints, and experiences
|
|
||||||
* Giving and gracefully accepting constructive feedback
|
|
||||||
* Accepting responsibility and apologizing to those affected by our mistakes,
|
|
||||||
and learning from the experience
|
|
||||||
* Focusing on what is best not just for us as individuals, but for the
|
|
||||||
overall community
|
|
||||||
|
|
||||||
Examples of unacceptable behavior include:
|
|
||||||
|
|
||||||
* The use of sexualized language or imagery, and sexual attention or
|
|
||||||
advances of any kind
|
|
||||||
* Trolling, insulting or derogatory comments, and personal or political attacks
|
|
||||||
* Public or private harassment
|
|
||||||
* Publishing others' private information, such as a physical or email
|
|
||||||
address, without their explicit permission
|
|
||||||
* Other conduct which could reasonably be considered inappropriate in a
|
|
||||||
professional setting
|
|
||||||
|
|
||||||
## Enforcement Responsibilities
|
|
||||||
|
|
||||||
Community leaders are responsible for clarifying and enforcing our standards of
|
|
||||||
acceptable behavior and will take appropriate and fair corrective action in
|
|
||||||
response to any behavior that they deem inappropriate, threatening, offensive,
|
|
||||||
or harmful.
|
|
||||||
|
|
||||||
Community leaders have the right and responsibility to remove, edit, or reject
|
|
||||||
comments, commits, code, wiki edits, issues, and other contributions that are
|
|
||||||
not aligned to this Code of Conduct, and will communicate reasons for moderation
|
|
||||||
decisions when appropriate.
|
|
||||||
|
|
||||||
## Scope
|
|
||||||
|
|
||||||
This Code of Conduct applies within all community spaces, and also applies when
|
|
||||||
an individual is officially representing the community in public spaces.
|
|
||||||
Examples of representing our community include using an official e-mail address,
|
|
||||||
posting via an official social media account, or acting as an appointed
|
|
||||||
representative at an online or offline event.
|
|
||||||
|
|
||||||
## Enforcement
|
|
||||||
|
|
||||||
Instances of abusive, harassing, or otherwise unacceptable behavior may be
|
|
||||||
reported to the community leaders responsible for enforcement at
|
|
||||||
**johnellisATlinuxDOTcom**.
|
|
||||||
All complaints will be reviewed and investigated promptly and fairly.
|
|
||||||
|
|
||||||
All community leaders are obligated to respect the privacy and security of the
|
|
||||||
reporter of any incident.
|
|
||||||
|
|
||||||
## Enforcement Guidelines
|
|
||||||
|
|
||||||
Community leaders will follow these Community Impact Guidelines in determining
|
|
||||||
the consequences for any action they deem in violation of this Code of Conduct:
|
|
||||||
|
|
||||||
### 1. Correction
|
|
||||||
|
|
||||||
**Community Impact**: Use of inappropriate language or other behavior deemed
|
|
||||||
unprofessional or unwelcome in the community.
|
|
||||||
|
|
||||||
**Consequence**: A private, written warning from community leaders, providing
|
|
||||||
clarity around the nature of the violation and an explanation of why the
|
|
||||||
behavior was inappropriate. A public apology may be requested.
|
|
||||||
|
|
||||||
### 2. Warning
|
|
||||||
|
|
||||||
**Community Impact**: A violation through a single incident or series
|
|
||||||
of actions.
|
|
||||||
|
|
||||||
**Consequence**: A warning with consequences for continued behavior. No
|
|
||||||
interaction with the people involved, including unsolicited interaction with
|
|
||||||
those enforcing the Code of Conduct, for a specified period of time. This
|
|
||||||
includes avoiding interactions in community spaces as well as external channels
|
|
||||||
like social media. Violating these terms may lead to a temporary or
|
|
||||||
permanent ban.
|
|
||||||
|
|
||||||
### 3. Temporary Ban
|
|
||||||
|
|
||||||
**Community Impact**: A serious violation of community standards, including
|
|
||||||
sustained inappropriate behavior.
|
|
||||||
|
|
||||||
**Consequence**: A temporary ban from any sort of interaction or public
|
|
||||||
communication with the community for a specified period of time. No public or
|
|
||||||
private interaction with the people involved, including unsolicited interaction
|
|
||||||
with those enforcing the Code of Conduct, is allowed during this period.
|
|
||||||
Violating these terms may lead to a permanent ban.
|
|
||||||
|
|
||||||
### 4. Permanent Ban
|
|
||||||
|
|
||||||
**Community Impact**: Demonstrating a pattern of violation of community
|
|
||||||
standards, including sustained inappropriate behavior, harassment of an
|
|
||||||
individual, or aggression toward or disparagement of classes of individuals.
|
|
||||||
|
|
||||||
**Consequence**: A permanent ban from any sort of public interaction within
|
|
||||||
the community.
|
|
||||||
|
|
||||||
## Attribution
|
|
||||||
|
|
||||||
This Code of Conduct is adapted from the [Contributor Covenant][homepage],
|
|
||||||
version 2.0, available at
|
|
||||||
https://www.contributor-covenant.org/version/2/0/code_of_conduct.html.
|
|
||||||
|
|
||||||
Community Impact Guidelines were inspired by [Mozilla's code of conduct
|
|
||||||
enforcement ladder](https://github.com/mozilla/diversity).
|
|
||||||
|
|
||||||
[homepage]: https://www.contributor-covenant.org
|
|
||||||
|
|
||||||
For answers to common questions about this code of conduct, see the FAQ at
|
|
||||||
https://www.contributor-covenant.org/faq. Translations are available at
|
|
||||||
https://www.contributor-covenant.org/translations.
|
|
||||||
+43
-47
@@ -1,65 +1,61 @@
|
|||||||
# Contributing
|
# Contributing
|
||||||
|
|
||||||
Patches, bug reports and questions are welcome.
|
Thank you for your interest in contributing to Stalwart. We appreciate the support and enthusiasm of the open-source community. To keep the project maintainable and the review process sustainable, contributions are subject to the policies described below. Please read them in full before opening a pull request.
|
||||||
|
|
||||||
## Before a pull request
|
## Vouched Contributors Only
|
||||||
|
|
||||||
**Open an issue first for anything substantial.** A feature or a refactor is
|
Due to the high volume of low-quality, AI-generated submissions, pull requests are limited to a list of vouched contributors. Pull requests opened by anyone who is not on this list are closed automatically.
|
||||||
worth agreeing on before it is written, because this is a fork that tracks
|
|
||||||
upstream: a change that moves code around costs a conflict on every import,
|
|
||||||
and it should be worth that.
|
|
||||||
|
|
||||||
Small fixes — a bug, a typo, a test — need no ceremony. Send them.
|
To be added as a vouched contributor, post a message at [support.stalw.art](https://support.stalw.art) explaining the code changes you would like to submit, and include a link to the proposed change (a branch, diff, or draft). Once a maintainer has reviewed your request and vouched for you, you will be able to open pull requests directly.
|
||||||
|
|
||||||
## What this repository is
|
This policy lets us focus limited review capacity on contributions from people who have taken the time to understand the codebase and discuss their changes first.
|
||||||
|
|
||||||
INBUXA is a fork of Stalwart, taken under the AGPL-3.0-only half of its dual
|
## What Contributions Are Accepted
|
||||||
licence, with nine features rebuilt independently. Two things follow:
|
|
||||||
|
|
||||||
- **The clean room is real.** The rebuilt features in `crates/features` were
|
At this stage of the project we accept a narrow set of contributions:
|
||||||
written from specifications in `docs/spec/features/`, by people who had not
|
|
||||||
read Stalwart's Enterprise source. If you have read it, say so in the pull
|
|
||||||
request and it will be reviewed with that in mind, or declined for the parts
|
|
||||||
it touches. Nothing about this is personal: the project's defence of
|
|
||||||
independent creation is a record, and the record has to be true.
|
|
||||||
- **Upstream files stay recognisable.** Changes to files that came from
|
|
||||||
upstream are kept small and marked with an `inbuxa:` comment saying which
|
|
||||||
requirement they serve, so the next import merges cleanly and a reader can
|
|
||||||
tell fork from base. New work belongs in the fork's own crates where it can.
|
|
||||||
|
|
||||||
## Licence and provenance
|
- **Bug fixes.** Corrections to existing, incorrect behavior are welcome. Please include steps to reproduce the bug and describe the fix.
|
||||||
|
- **Translations.** Additions and corrections to existing translations are welcome.
|
||||||
|
|
||||||
Contributions are under AGPL-3.0-only. Keep upstream's copyright headers where
|
New features are generally **not** accepted, unless they involve only a few lines of code. Larger features fall outside the scope of what we can review and integrate while the architecture is still evolving.
|
||||||
they are; if you change a file that came from upstream, leave its "Modified by
|
|
||||||
Coffey Labs" line in place. New files carry:
|
|
||||||
|
|
||||||
```
|
If you would like to see a new feature, please request it at [support.stalw.art](https://support.stalw.art) under the **Feature Ideas** category rather than opening a pull request. This lets the community discuss and prioritize ideas before any code is written.
|
||||||
/*
|
|
||||||
* SPDX-FileCopyrightText: 2026 Coffey Labs
|
|
||||||
*
|
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only
|
|
||||||
*/
|
|
||||||
```
|
|
||||||
|
|
||||||
If you bring in code from another project, it stays under its own licence and
|
## No AI-Generated Code
|
||||||
its notice goes in `THIRD-PARTY.md`. `tools/fork/strip.py` reports any file
|
|
||||||
that is missing from there on every import.
|
|
||||||
|
|
||||||
## Running the tests
|
AI-generated code is not accepted in this project.
|
||||||
|
|
||||||
`cargo test -p tests` runs what needs nothing but a store on disk. The rest
|
Even the most advanced models write inefficient Rust code. Beyond raw performance, AI creates technical debt by generating large amounts of code that not even the authors who submitted it can fully understand or maintain. Reviewing and untangling such contributions costs the maintainers far more time than it saves.
|
||||||
need containers, a particular backend, or a copy of real data, and are
|
|
||||||
`#[ignore]`d:
|
|
||||||
|
|
||||||
- `docs/spec/container-tests.md` — the suites that need containers, with the
|
Using AI as a fancy autocomplete is perfectly fine. What matters is that every line generated by a model is read, understood, and reviewed by a human before it is submitted. You are responsible for every line in your pull request, regardless of how it was produced. If you cannot explain why a change is written the way it is, it is not ready to be submitted.
|
||||||
`STORE` each one wants and what a plain regression leaves failing.
|
|
||||||
- `docs/spec/compat-tests.md` — the compatibility set, which needs a copy of a
|
|
||||||
real server's data.
|
|
||||||
|
|
||||||
Run one suite at a time. They bind fixed ports, and the timing checks flake if
|
## Pull Request Process
|
||||||
two run at once.
|
|
||||||
|
|
||||||
## Commit messages
|
Once you are a vouched contributor:
|
||||||
|
|
||||||
Say what changed and why, in prose, wrapped at 72 characters or so. The why is
|
1. Keep each pull request small and focused on a single logical change.
|
||||||
the part that is hard to recover later. No tool trailers.
|
2. Match the style and conventions of the surrounding code.
|
||||||
|
3. Make sure the project builds and the test suite passes before opening the pull request.
|
||||||
|
4. In the pull request description, explain what the change does and why, and link to the [support.stalw.art](https://support.stalw.art) discussion where the change was vouched.
|
||||||
|
|
||||||
|
## Code of Conduct
|
||||||
|
|
||||||
|
We as members, contributors, and leaders pledge to make participation in our community a harassment-free experience for everyone, regardless of age, body size, visible or invisible disability, ethnicity, sex characteristics, gender identity and expression, level of experience, education, socio-economic status, nationality, personal appearance, race, religion, or sexual identity and orientation. We pledge to act and interact in ways that contribute to an open, welcoming, diverse, inclusive, and healthy community.
|
||||||
|
|
||||||
|
You can read the full Code of Conduct [here](https://github.com/stalwartlabs/.github/blob/main/CODE_OF_CONDUCT.md).
|
||||||
|
|
||||||
|
## Licensing
|
||||||
|
|
||||||
|
This project is licensed under the Affero General Public License (AGPL) version 3.0. By contributing to this project, you agree that your contributions will be licensed under the AGPL-3.0 license.
|
||||||
|
|
||||||
|
## Fiduciary Contributor License Agreement
|
||||||
|
|
||||||
|
Before making any contributions, all contributors are required to sign the Fiduciary Contributor License Agreement (FLA). The FLA is a legal agreement that assigns the copyright of contributions to a designated fiduciary, who manages these rights on behalf of the project. This arrangement ensures that the software remains free and open, even as contributors come and go.
|
||||||
|
|
||||||
|
Key points of the FLA:
|
||||||
|
|
||||||
|
- Ensures the software remains free and open source
|
||||||
|
- Protects the project from potential copyright issues
|
||||||
|
- Includes a reversion clause: if the fiduciary violates Free Software principles, rights revert to the original contributors
|
||||||
|
|
||||||
|
For more details about the FLA, please refer to the [FLA FAQ](https://fsfe.org/activities/fla/fla.en.html).
|
||||||
|
|||||||
Generated
+190
-228
File diff suppressed because it is too large
Load Diff
@@ -29,7 +29,6 @@ members = [
|
|||||||
"crates/common",
|
"crates/common",
|
||||||
"crates/trc",
|
"crates/trc",
|
||||||
"crates/migration",
|
"crates/migration",
|
||||||
"crates/features",
|
|
||||||
"tests",
|
"tests",
|
||||||
]
|
]
|
||||||
|
|
||||||
|
|||||||
+14
-14
@@ -21,7 +21,7 @@ RUN rustup target add "$(cat /target.txt)"
|
|||||||
COPY --from=planner /recipe.json /recipe.json
|
COPY --from=planner /recipe.json /recipe.json
|
||||||
RUN RUSTFLAGS="$(cat /flags.txt)" cargo chef cook --target "$(cat /target.txt)" --release --no-default-features --features "sqlite postgres mysql rocks s3 redis azure nats" --recipe-path /recipe.json
|
RUN RUSTFLAGS="$(cat /flags.txt)" cargo chef cook --target "$(cat /target.txt)" --release --no-default-features --features "sqlite postgres mysql rocks s3 redis azure nats" --recipe-path /recipe.json
|
||||||
COPY . .
|
COPY . .
|
||||||
RUN RUSTFLAGS="$(cat /flags.txt)" cargo build --target "$(cat /target.txt)" --release -p inbuxa --no-default-features --features "sqlite postgres mysql rocks s3 redis azure nats"
|
RUN RUSTFLAGS="$(cat /flags.txt)" cargo build --target "$(cat /target.txt)" --release -p stalwart --no-default-features --features "sqlite postgres mysql rocks s3 redis azure nats"
|
||||||
RUN mv "/build/target/$(cat /target.txt)/release" "/output"
|
RUN mv "/build/target/$(cat /target.txt)/release" "/output"
|
||||||
|
|
||||||
FROM docker.io/debian:trixie-slim
|
FROM docker.io/debian:trixie-slim
|
||||||
@@ -29,18 +29,18 @@ RUN export DEBIAN_FRONTEND=noninteractive && \
|
|||||||
apt-get update && \
|
apt-get update && \
|
||||||
apt-get install -yq --no-install-recommends ca-certificates curl libcap2-bin && \
|
apt-get install -yq --no-install-recommends ca-certificates curl libcap2-bin && \
|
||||||
rm -rf /var/lib/apt/lists/* && \
|
rm -rf /var/lib/apt/lists/* && \
|
||||||
groupadd -r -g 2000 inbuxa && \
|
groupadd -r -g 2000 stalwart && \
|
||||||
useradd -r -u 2000 -g 2000 -s /usr/sbin/nologin -M inbuxa && \
|
useradd -r -u 2000 -g 2000 -s /usr/sbin/nologin -M stalwart && \
|
||||||
mkdir -p /etc/inbuxa /var/lib/inbuxa && \
|
mkdir -p /etc/stalwart /var/lib/stalwart && \
|
||||||
chown inbuxa:inbuxa /etc/inbuxa /var/lib/inbuxa
|
chown stalwart:stalwart /etc/stalwart /var/lib/stalwart
|
||||||
COPY --from=builder --chmod=0755 /output/inbuxa /usr/local/bin/inbuxa
|
COPY --from=builder --chmod=0755 /output/stalwart /usr/local/bin/stalwart
|
||||||
RUN setcap 'cap_net_bind_service=+ep' /usr/local/bin/inbuxa
|
RUN setcap 'cap_net_bind_service=+ep' /usr/local/bin/stalwart
|
||||||
USER inbuxa
|
USER stalwart
|
||||||
WORKDIR /var/lib/inbuxa
|
WORKDIR /var/lib/stalwart
|
||||||
VOLUME ["/etc/inbuxa", "/var/lib/inbuxa"]
|
VOLUME ["/etc/stalwart", "/var/lib/stalwart"]
|
||||||
EXPOSE 443 25 110 587 465 143 993 995 4190 8080
|
EXPOSE 443 25 110 587 465 143 993 995 4190 8080
|
||||||
ENV INBUXA_HEALTHCHECK_URL=https://127.0.0.1:443/healthz/live
|
ENV STALWART_HEALTHCHECK_URL=https://127.0.0.1:443/healthz/live
|
||||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
|
||||||
CMD curl -fsSk -H "X-Forwarded-For: 127.0.0.1" "$INBUXA_HEALTHCHECK_URL" || curl -fsS -H "X-Forwarded-For: 127.0.0.1" http://127.0.0.1:8080/healthz/live || exit 1
|
CMD curl -fsSk -H "X-Forwarded-For: 127.0.0.1" "$STALWART_HEALTHCHECK_URL" || curl -fsS -H "X-Forwarded-For: 127.0.0.1" http://127.0.0.1:8080/healthz/live || exit 1
|
||||||
ENTRYPOINT ["/usr/local/bin/inbuxa"]
|
ENTRYPOINT ["/usr/local/bin/stalwart"]
|
||||||
CMD ["--config", "/etc/inbuxa/config.json"]
|
CMD ["--config", "/etc/stalwart/config.json"]
|
||||||
|
|||||||
+32
-32
@@ -108,7 +108,7 @@ RUN \
|
|||||||
--mount=type=cache,target=/usr/local/cargo/git \
|
--mount=type=cache,target=/usr/local/cargo/git \
|
||||||
source /env-cargo && \
|
source /env-cargo && \
|
||||||
if [ ! -z "${FDB_ARCH}" ]; then \
|
if [ ! -z "${FDB_ARCH}" ]; then \
|
||||||
RUSTFLAGS="-L /usr/lib" cargo chef cook --recipe-path recipe.json --zigbuild --release --target ${TARGET} -p inbuxa --no-default-features --features "foundationdb s3 redis nats"; \
|
RUSTFLAGS="-L /usr/lib" cargo chef cook --recipe-path recipe.json --zigbuild --release --target ${TARGET} -p stalwart --no-default-features --features "foundationdb s3 redis nats"; \
|
||||||
fi
|
fi
|
||||||
RUN \
|
RUN \
|
||||||
--mount=type=secret,id=ACTIONS_RESULTS_URL,env=ACTIONS_RESULTS_URL \
|
--mount=type=secret,id=ACTIONS_RESULTS_URL,env=ACTIONS_RESULTS_URL \
|
||||||
@@ -116,7 +116,7 @@ RUN \
|
|||||||
--mount=type=cache,target=/usr/local/cargo/registry \
|
--mount=type=cache,target=/usr/local/cargo/registry \
|
||||||
--mount=type=cache,target=/usr/local/cargo/git \
|
--mount=type=cache,target=/usr/local/cargo/git \
|
||||||
source /env-cargo && \
|
source /env-cargo && \
|
||||||
cargo chef cook --recipe-path recipe.json --zigbuild --release --target ${TARGET} -p inbuxa --no-default-features --features "sqlite postgres mysql rocks s3 redis azure nats"
|
cargo chef cook --recipe-path recipe.json --zigbuild --release --target ${TARGET} -p stalwart --no-default-features --features "sqlite postgres mysql rocks s3 redis azure nats"
|
||||||
# Copy the source code
|
# Copy the source code
|
||||||
COPY . .
|
COPY . .
|
||||||
ENV RUSTC_WRAPPER="sccache" \
|
ENV RUSTC_WRAPPER="sccache" \
|
||||||
@@ -129,8 +129,8 @@ RUN \
|
|||||||
--mount=type=cache,target=/usr/local/cargo/git \
|
--mount=type=cache,target=/usr/local/cargo/git \
|
||||||
source /env-cargo && \
|
source /env-cargo && \
|
||||||
if [ ! -z "${FDB_ARCH}" ]; then \
|
if [ ! -z "${FDB_ARCH}" ]; then \
|
||||||
RUSTFLAGS="-L /usr/lib" cargo zigbuild --release --target ${TARGET} -p inbuxa --no-default-features --features "foundationdb s3 redis nats" && \
|
RUSTFLAGS="-L /usr/lib" cargo zigbuild --release --target ${TARGET} -p stalwart --no-default-features --features "foundationdb s3 redis nats" && \
|
||||||
mv /app/target/${TARGET}/release/inbuxa /app/artifact/inbuxa-foundationdb; \
|
mv /app/target/${TARGET}/release/stalwart /app/artifact/stalwart-foundationdb; \
|
||||||
fi
|
fi
|
||||||
# Build generic version
|
# Build generic version
|
||||||
RUN \
|
RUN \
|
||||||
@@ -139,8 +139,8 @@ RUN \
|
|||||||
--mount=type=cache,target=/usr/local/cargo/registry \
|
--mount=type=cache,target=/usr/local/cargo/registry \
|
||||||
--mount=type=cache,target=/usr/local/cargo/git \
|
--mount=type=cache,target=/usr/local/cargo/git \
|
||||||
source /env-cargo && \
|
source /env-cargo && \
|
||||||
cargo zigbuild --release --target ${TARGET} -p inbuxa --no-default-features --features "sqlite postgres mysql rocks s3 redis azure nats" && \
|
cargo zigbuild --release --target ${TARGET} -p stalwart --no-default-features --features "sqlite postgres mysql rocks s3 redis azure nats" && \
|
||||||
mv /app/target/${TARGET}/release/inbuxa /app/artifact/inbuxa
|
mv /app/target/${TARGET}/release/stalwart /app/artifact/stalwart
|
||||||
|
|
||||||
# *****************
|
# *****************
|
||||||
# Binary stage
|
# Binary stage
|
||||||
@@ -156,21 +156,21 @@ RUN export DEBIAN_FRONTEND=noninteractive && \
|
|||||||
apt-get update && \
|
apt-get update && \
|
||||||
apt-get install -yq --no-install-recommends ca-certificates curl tzdata libcap2-bin && \
|
apt-get install -yq --no-install-recommends ca-certificates curl tzdata libcap2-bin && \
|
||||||
rm -rf /var/lib/apt/lists/* && \
|
rm -rf /var/lib/apt/lists/* && \
|
||||||
groupadd -r -g 2000 inbuxa && \
|
groupadd -r -g 2000 stalwart && \
|
||||||
useradd -r -u 2000 -g 2000 -s /usr/sbin/nologin -M inbuxa && \
|
useradd -r -u 2000 -g 2000 -s /usr/sbin/nologin -M stalwart && \
|
||||||
mkdir -p /etc/inbuxa /var/lib/inbuxa && \
|
mkdir -p /etc/stalwart /var/lib/stalwart && \
|
||||||
chown inbuxa:inbuxa /etc/inbuxa /var/lib/inbuxa
|
chown stalwart:stalwart /etc/stalwart /var/lib/stalwart
|
||||||
COPY --from=builder --chmod=0755 /app/artifact/inbuxa /usr/local/bin/inbuxa
|
COPY --from=builder --chmod=0755 /app/artifact/stalwart /usr/local/bin/stalwart
|
||||||
RUN setcap 'cap_net_bind_service=+ep' /usr/local/bin/inbuxa
|
RUN setcap 'cap_net_bind_service=+ep' /usr/local/bin/stalwart
|
||||||
USER inbuxa
|
USER stalwart
|
||||||
WORKDIR /var/lib/inbuxa
|
WORKDIR /var/lib/stalwart
|
||||||
VOLUME ["/etc/inbuxa", "/var/lib/inbuxa"]
|
VOLUME ["/etc/stalwart", "/var/lib/stalwart"]
|
||||||
EXPOSE 443 25 110 587 465 143 993 995 4190 8080
|
EXPOSE 443 25 110 587 465 143 993 995 4190 8080
|
||||||
ENV INBUXA_HEALTHCHECK_URL=https://127.0.0.1:443/healthz/live
|
ENV STALWART_HEALTHCHECK_URL=https://127.0.0.1:443/healthz/live
|
||||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
|
||||||
CMD curl -fsSk -H "X-Forwarded-For: 127.0.0.1" "$INBUXA_HEALTHCHECK_URL" || curl -fsS -H "X-Forwarded-For: 127.0.0.1" http://127.0.0.1:8080/healthz/live || exit 1
|
CMD curl -fsSk -H "X-Forwarded-For: 127.0.0.1" "$STALWART_HEALTHCHECK_URL" || curl -fsS -H "X-Forwarded-For: 127.0.0.1" http://127.0.0.1:8080/healthz/live || exit 1
|
||||||
ENTRYPOINT ["/usr/local/bin/inbuxa"]
|
ENTRYPOINT ["/usr/local/bin/stalwart"]
|
||||||
CMD ["--config", "/etc/inbuxa/config.json"]
|
CMD ["--config", "/etc/stalwart/config.json"]
|
||||||
|
|
||||||
# *****************
|
# *****************
|
||||||
# Runtime image for musl targets
|
# Runtime image for musl targets
|
||||||
@@ -178,18 +178,18 @@ CMD ["--config", "/etc/inbuxa/config.json"]
|
|||||||
FROM --platform=$TARGETPLATFORM alpine AS musl
|
FROM --platform=$TARGETPLATFORM alpine AS musl
|
||||||
RUN apk add --update --no-cache ca-certificates curl tzdata libcap && \
|
RUN apk add --update --no-cache ca-certificates curl tzdata libcap && \
|
||||||
rm -rf /var/cache/apk/* && \
|
rm -rf /var/cache/apk/* && \
|
||||||
addgroup -S -g 2000 inbuxa && \
|
addgroup -S -g 2000 stalwart && \
|
||||||
adduser -S -D -H -u 2000 -G inbuxa -s /sbin/nologin inbuxa && \
|
adduser -S -D -H -u 2000 -G stalwart -s /sbin/nologin stalwart && \
|
||||||
mkdir -p /etc/inbuxa /var/lib/inbuxa && \
|
mkdir -p /etc/stalwart /var/lib/stalwart && \
|
||||||
chown inbuxa:inbuxa /etc/inbuxa /var/lib/inbuxa
|
chown stalwart:stalwart /etc/stalwart /var/lib/stalwart
|
||||||
COPY --from=builder --chmod=0755 /app/artifact/inbuxa /usr/local/bin/inbuxa
|
COPY --from=builder --chmod=0755 /app/artifact/stalwart /usr/local/bin/stalwart
|
||||||
RUN setcap 'cap_net_bind_service=+ep' /usr/local/bin/inbuxa
|
RUN setcap 'cap_net_bind_service=+ep' /usr/local/bin/stalwart
|
||||||
USER inbuxa
|
USER stalwart
|
||||||
WORKDIR /var/lib/inbuxa
|
WORKDIR /var/lib/stalwart
|
||||||
VOLUME ["/etc/inbuxa", "/var/lib/inbuxa"]
|
VOLUME ["/etc/stalwart", "/var/lib/stalwart"]
|
||||||
EXPOSE 443 25 110 587 465 143 993 995 4190 8080
|
EXPOSE 443 25 110 587 465 143 993 995 4190 8080
|
||||||
ENV INBUXA_HEALTHCHECK_URL=https://127.0.0.1:443/healthz/live
|
ENV STALWART_HEALTHCHECK_URL=https://127.0.0.1:443/healthz/live
|
||||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
|
||||||
CMD curl -fsSk -H "X-Forwarded-For: 127.0.0.1" "$INBUXA_HEALTHCHECK_URL" || curl -fsS -H "X-Forwarded-For: 127.0.0.1" http://127.0.0.1:8080/healthz/live || exit 1
|
CMD curl -fsSk -H "X-Forwarded-For: 127.0.0.1" "$STALWART_HEALTHCHECK_URL" || curl -fsS -H "X-Forwarded-For: 127.0.0.1" http://127.0.0.1:8080/healthz/live || exit 1
|
||||||
ENTRYPOINT ["/usr/local/bin/inbuxa"]
|
ENTRYPOINT ["/usr/local/bin/stalwart"]
|
||||||
CMD ["--config", "/etc/inbuxa/config.json"]
|
CMD ["--config", "/etc/stalwart/config.json"]
|
||||||
|
|||||||
+14
-14
@@ -53,28 +53,28 @@ COPY Cargo.lock .
|
|||||||
COPY crates/ crates/
|
COPY crates/ crates/
|
||||||
COPY resources/ resources/
|
COPY resources/ resources/
|
||||||
COPY tests/ tests/
|
COPY tests/ tests/
|
||||||
RUN cargo build -p inbuxa --no-default-features --features "foundationdb s3 redis azure nats" --release
|
RUN cargo build -p stalwart --no-default-features --features "foundationdb s3 redis azure nats" --release
|
||||||
|
|
||||||
FROM debian:trixie-slim AS runtime
|
FROM debian:trixie-slim AS runtime
|
||||||
|
|
||||||
COPY --from=builder --chmod=0755 /app/target/release/inbuxa /usr/local/bin/inbuxa
|
COPY --from=builder --chmod=0755 /app/target/release/stalwart /usr/local/bin/stalwart
|
||||||
COPY --from=builder /usr/lib/libfdb_c.so /usr/lib/libfdb_c.so
|
COPY --from=builder /usr/lib/libfdb_c.so /usr/lib/libfdb_c.so
|
||||||
RUN export DEBIAN_FRONTEND=noninteractive && \
|
RUN export DEBIAN_FRONTEND=noninteractive && \
|
||||||
apt-get update && \
|
apt-get update && \
|
||||||
apt-get install -yq --no-install-recommends ca-certificates curl libcap2-bin && \
|
apt-get install -yq --no-install-recommends ca-certificates curl libcap2-bin && \
|
||||||
rm -rf /var/lib/apt/lists/* && \
|
rm -rf /var/lib/apt/lists/* && \
|
||||||
groupadd -r -g 2000 inbuxa && \
|
groupadd -r -g 2000 stalwart && \
|
||||||
useradd -r -u 2000 -g 2000 -s /usr/sbin/nologin -M inbuxa && \
|
useradd -r -u 2000 -g 2000 -s /usr/sbin/nologin -M stalwart && \
|
||||||
mkdir -p /etc/inbuxa /var/lib/inbuxa && \
|
mkdir -p /etc/stalwart /var/lib/stalwart && \
|
||||||
chown inbuxa:inbuxa /etc/inbuxa /var/lib/inbuxa && \
|
chown stalwart:stalwart /etc/stalwart /var/lib/stalwart && \
|
||||||
setcap 'cap_net_bind_service=+ep' /usr/local/bin/inbuxa
|
setcap 'cap_net_bind_service=+ep' /usr/local/bin/stalwart
|
||||||
|
|
||||||
USER inbuxa
|
USER stalwart
|
||||||
WORKDIR /var/lib/inbuxa
|
WORKDIR /var/lib/stalwart
|
||||||
VOLUME ["/etc/inbuxa", "/var/lib/inbuxa"]
|
VOLUME ["/etc/stalwart", "/var/lib/stalwart"]
|
||||||
EXPOSE 443 25 110 587 465 143 993 995 4190 8080
|
EXPOSE 443 25 110 587 465 143 993 995 4190 8080
|
||||||
ENV INBUXA_HEALTHCHECK_URL=https://127.0.0.1:443/healthz/live
|
ENV STALWART_HEALTHCHECK_URL=https://127.0.0.1:443/healthz/live
|
||||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
|
HEALTHCHECK --interval=30s --timeout=5s --start-period=30s --retries=3 \
|
||||||
CMD curl -fsSk -H "X-Forwarded-For: 127.0.0.1" "$INBUXA_HEALTHCHECK_URL" || curl -fsS -H "X-Forwarded-For: 127.0.0.1" http://127.0.0.1:8080/healthz/live || exit 1
|
CMD curl -fsSk -H "X-Forwarded-For: 127.0.0.1" "$STALWART_HEALTHCHECK_URL" || curl -fsS -H "X-Forwarded-For: 127.0.0.1" http://127.0.0.1:8080/healthz/live || exit 1
|
||||||
ENTRYPOINT ["/usr/local/bin/inbuxa"]
|
ENTRYPOINT ["/usr/local/bin/stalwart"]
|
||||||
CMD ["--config", "/etc/inbuxa/config.json"]
|
CMD ["--config", "/etc/stalwart/config.json"]
|
||||||
|
|||||||
@@ -1,70 +1,186 @@
|
|||||||
<p align="center">
|
<p align="center">
|
||||||
<img src="./img/brand/inbuxa-lockup-light.svg" alt="inbuxa" height="140">
|
<a href="https://stalw.art">
|
||||||
|
<img src="./img/logo-red.svg" height="150">
|
||||||
|
</a>
|
||||||
</p>
|
</p>
|
||||||
|
|
||||||
<h3 align="center">
|
<h3 align="center">
|
||||||
A complete mail and collaboration server, every feature included, under the AGPL
|
Secure, scalable mail & collaboration server with comprehensive protocol support 🛡️ <br/>(IMAP, JMAP, SMTP, CalDAV, CardDAV, WebDAV)
|
||||||
</h3>
|
</h3>
|
||||||
|
|
||||||
---
|
<br>
|
||||||
|
|
||||||
**INBUXA** is a mail and collaboration server: JMAP, IMAP, POP3, SMTP,
|
<p align="center">
|
||||||
CalDAV, CardDAV and WebDAV, in one Rust binary, with ihasmail as its web front
|
<a href="https://github.com/stalwartlabs/stalwart/actions/workflows/ci.yml"><img src="https://img.shields.io/github/actions/workflow/status/stalwartlabs/stalwart/ci.yml?style=flat-square" alt="continuous integration"></a>
|
||||||
end. It is a fork of [Stalwart](https://github.com/stalwartlabs/stalwart).
|
|
||||||
Project site: [inbuxa.org](https://inbuxa.org). Documentation: [docs.inbuxa.org](https://docs.inbuxa.org).
|
<a href="https://www.gnu.org/licenses/agpl-3.0"><img src="https://img.shields.io/badge/License-AGPL_v3-blue.svg?label=license&style=flat-square" alt="License: AGPL v3"></a>
|
||||||
|
|
||||||
|
<a href="https://stalw.art/docs/install/get-started"><img src="https://img.shields.io/badge/read_the-docs-red?style=flat-square" alt="Documentation"></a>
|
||||||
|
|
||||||
|
<a href="https://github.com/stalwartlabs/stalwart/releases"><img src="https://img.shields.io/github/downloads/stalwartlabs/stalwart/total?style=flat-square" alt="downloads"></a
|
||||||
|
</p>
|
||||||
|
<p align="center">
|
||||||
|
<a href="https://mastodon.social/@stalwartlabs"><img src="https://img.shields.io/mastodon/follow/109929667531941122?style=flat-square&logo=mastodon&color=%236364ff&label=Mastodon" alt="Mastodon"></a>
|
||||||
|
|
||||||
|
<a href="https://twitter.com/stalwartlabs"><img src="https://img.shields.io/twitter/follow/stalwartlabs?style=flat-square&logo=x&label=Twitter" alt="Twitter"></a>
|
||||||
|
<a href="https://discord.gg/vhqRgdhguq"><img src="https://img.shields.io/discord/923615863037390889?label=Discord&logo=discord&style=flat-square" alt="Discord"></a>
|
||||||
|
|
||||||
|
<a href="https://www.reddit.com/r/stalwartlabs/"><img src="https://img.shields.io/reddit/subreddit-subscribers/stalwartlabs?label=%2Fr%2Fstalwartlabs&logo=reddit&style=flat-square" alt="Reddit"></a>
|
||||||
|
</p>
|
||||||
|
|
||||||
Stalwart ships some features only in a paid Enterprise Edition: multi-tenancy,
|
## Features
|
||||||
masked email, undelete and others. INBUXA ships everything to everybody under
|
|
||||||
the AGPL-3.0, rebuilding those features independently and without using any
|
|
||||||
of Stalwart's Enterprise code.
|
|
||||||
|
|
||||||
## What's different from Stalwart
|
**Stalwart** is an open-source mail & collaboration server with JMAP, IMAP4, POP3, SMTP, CalDAV, CardDAV and WebDAV support and a wide range of modern features. It is written in Rust and designed to be secure, fast, robust and scalable.
|
||||||
|
|
||||||
- **Every feature, one edition.** No license key, no edition checks, no
|
Key features:
|
||||||
upsell. See `docs/spec/SPEC.md` §4 for the features being rebuilt, and
|
|
||||||
`docs/spec/features/` for each one's specification.
|
|
||||||
- **Webmail and administration by ihasmail,** as a separate service that can
|
|
||||||
run beside the server or elsewhere. Stalwart's own web interface is removed,
|
|
||||||
so there's no web front end on the mail host.
|
|
||||||
- **Clean-room rebuilds.** Enterprise-only code is stripped from every
|
|
||||||
upstream release before it's imported. The rebuilt features are written
|
|
||||||
from specifications that use only public sources (`docs/spec/SPEC.md` §3).
|
|
||||||
|
|
||||||
## How the fork is kept
|
- **Email** server with complete protocol support:
|
||||||
|
- JMAP:
|
||||||
|
* [JMAP for Mail](https://datatracker.ietf.org/doc/html/rfc8621) server.
|
||||||
|
* [JMAP for Sieve Scripts](https://www.ietf.org/archive/id/draft-ietf-jmap-sieve-22.html).
|
||||||
|
* [WebSocket](https://datatracker.ietf.org/doc/html/rfc8887), [Blob Management](https://www.rfc-editor.org/rfc/rfc9404.html) and [Quotas](https://www.rfc-editor.org/rfc/rfc9425.html) extensions.
|
||||||
|
- IMAP:
|
||||||
|
* [IMAP4rev2](https://datatracker.ietf.org/doc/html/rfc9051) and [IMAP4rev1](https://datatracker.ietf.org/doc/html/rfc3501) server.
|
||||||
|
* [ManageSieve](https://datatracker.ietf.org/doc/html/rfc5804) server.
|
||||||
|
* Numerous [extensions](https://stalw.art/docs/development/rfcs#imap4-and-extensions) supported.
|
||||||
|
- POP3:
|
||||||
|
- [POP3](https://datatracker.ietf.org/doc/html/rfc1939) server.
|
||||||
|
- [STLS](https://datatracker.ietf.org/doc/html/rfc2595) and [SASL](https://datatracker.ietf.org/doc/html/rfc5034) support as well as other [extensions](https://datatracker.ietf.org/doc/html/rfc2449).
|
||||||
|
- SMTP:
|
||||||
|
* SMTP server with built-in [DMARC](https://datatracker.ietf.org/doc/html/rfc7489), [DKIMv2](https://datatracker.ietf.org/doc/draft-ietf-dkim-dkim2-spec/), [DKIMv1](https://datatracker.ietf.org/doc/html/rfc6376), [SPF](https://datatracker.ietf.org/doc/html/rfc7208) and [ARC](https://datatracker.ietf.org/doc/html/rfc8617) support for message authentication.
|
||||||
|
* Strong transport security through [DANE](https://datatracker.ietf.org/doc/html/rfc6698), [MTA-STS](https://datatracker.ietf.org/doc/html/rfc8461) and [SMTP TLS](https://datatracker.ietf.org/doc/html/rfc8460) reporting.
|
||||||
|
* Automated DKIM key rotation and management.
|
||||||
|
* Inbound throttling and filtering with granular configuration rules, sieve scripting, MTA hooks and milter integration.
|
||||||
|
* Distributed virtual queues with delayed delivery, priority delivery, quotas, routing rules and throttling support.
|
||||||
|
* Envelope rewriting and message modification.
|
||||||
|
- **Collaboration** server:
|
||||||
|
- Calendaring and scheduling:
|
||||||
|
- [CalDAV](https://datatracker.ietf.org/doc/html/rfc4791) and [CalDAV Scheduling](https://datatracker.ietf.org/doc/html/rfc6638) support.
|
||||||
|
- [JMAP for Calendars](https://datatracker.ietf.org/doc/html/draft-ietf-jmap-calendars-24) support.
|
||||||
|
- Contact management:
|
||||||
|
- [CardDAV](https://datatracker.ietf.org/doc/html/rfc6352) support.
|
||||||
|
- [JMAP for Contacts](https://datatracker.ietf.org/doc/html/rfc9610) support.
|
||||||
|
- File storage:
|
||||||
|
- [WebDAV](https://datatracker.ietf.org/doc/html/rfc4918) support.
|
||||||
|
- [JMAP for File Storage](https://datatracker.ietf.org/doc/html/draft-ietf-jmap-filenode-03) support.
|
||||||
|
- Sharing with fine-grained access controls:
|
||||||
|
- [WebDAV ACL](https://datatracker.ietf.org/doc/html/rfc3744) support.
|
||||||
|
- [JMAP Sharing](https://datatracker.ietf.org/doc/html/rfc9670) support.
|
||||||
|
- **Spam** and **Phishing** built-in filter:
|
||||||
|
- Comprehensive set of filtering **rules** on par with popular solutions.
|
||||||
|
- LLM-driven spam filtering and message analysis.
|
||||||
|
- Statistical **spam classifier** with collaborative filtering, automatic training capabilities and address book integration.
|
||||||
|
- DNS Blocklists (**DNSBLs**) checking of IP addresses, domains, and hashes.
|
||||||
|
- Collaborative digest-based spam filtering with **Pyzor**.
|
||||||
|
- **Phishing** protection against homographic URL attacks, sender spoofing and other techniques.
|
||||||
|
- Trusted **reply** tracking to recognize and prioritize genuine e-mail replies.
|
||||||
|
- Sender **reputation** monitoring by IP address, ASN, domain and email address.
|
||||||
|
- **Greylisting** to temporarily defer unknown senders.
|
||||||
|
- **Spam traps** to set up decoy email addresses that catch and analyze spam.
|
||||||
|
- **Flexible**:
|
||||||
|
- Pluggable storage backends with **RocksDB**, **FoundationDB**, **PostgreSQL**, **mySQL**, **SQLite**, **S3-Compatible**, **Azure** and **Redis** support.
|
||||||
|
- Full-text search available in 17 languages using the built-in search engine or via **Meilisearch**, **ElasticSearch**, **OpenSearch**, **PostgreSQL** or **mySQL** backends.
|
||||||
|
- Sieve scripting language with support for all [registered extensions](https://www.iana.org/assignments/sieve-extensions/sieve-extensions.xhtml).
|
||||||
|
- Email aliases, mailing lists, subaddressing and catch-all addresses support.
|
||||||
|
- Automated DNS management.
|
||||||
|
- Automatic account configuration and discovery with [PACC](https://datatracker.ietf.org/doc/draft-ietf-mailmaint-pacc/), [autoconfig](https://datatracker.ietf.org/doc/draft-ietf-mailmaint-autoconfig/) and [autodiscover](https://learn.microsoft.com/en-us/exchange/architecture/client-access/autodiscover?view=exchserver-2019).
|
||||||
|
- Multi-tenancy support with domain and tenant isolation.
|
||||||
|
- Disk quotas per user and tenant.
|
||||||
|
- **Secure and robust**:
|
||||||
|
- Encryption at rest with **S/MIME** or **OpenPGP**.
|
||||||
|
- Automatic TLS certificate provisioning with [ACME](https://datatracker.ietf.org/doc/html/rfc8555) using `TLS-ALPN-01`, `DNS-01`, `DNS-PERSIST-01` or `HTTP-01` challenges.
|
||||||
|
- Automated blocking of IP addresses that attack, abuse or scan the server for exploits.
|
||||||
|
- Rate limiting.
|
||||||
|
- Security audited (read the [report](https://stalw.art/blog/security-audit)).
|
||||||
|
- Memory safe (thanks to Rust).
|
||||||
|
- **Scalable and fault-tolerant**:
|
||||||
|
- Designed to handle growth seamlessly, from small setups to large-scale deployments of thousands of nodes.
|
||||||
|
- Built with **fault tolerance** and **high availability** in mind, recovers from hardware or software failures with minimal operational impact.
|
||||||
|
- Peer-to-peer cluster coordination or with **Kafka**, **Redpanda**, **NATS** or **Redis**.
|
||||||
|
- **Kubernetes**, **Apache Mesos** and **Docker Swarm** support for automated scaling and container orchestration.
|
||||||
|
- Read replicas, sharded blob storage and in-memory data stores for high performance and low latency.
|
||||||
|
- **Authentication and Authorization**:
|
||||||
|
- **OpenID Connect** authentication.
|
||||||
|
- OAuth 2.0 authorization with [authorization code](https://www.rfc-editor.org/rfc/rfc8628) and [device authorization](https://www.rfc-editor.org/rfc/rfc8628) flows.
|
||||||
|
- **LDAP**, **OIDC**, **SQL** or built-in authentication backend support.
|
||||||
|
- System for Cross-domain Identity Management ([SCIM](https://www.rfc-editor.org/info/rfc7643/)) v2 for automated provisioning.
|
||||||
|
- Two-factor authentication with Time-based One-Time Passwords (`2FA-TOTP`)
|
||||||
|
- Application passwords (App Passwords).
|
||||||
|
- Roles and permissions.
|
||||||
|
- Access Control Lists (ACLs).
|
||||||
|
- **Observability**:
|
||||||
|
- Logging and tracing with **OpenTelemetry**, journald, log files and console support.
|
||||||
|
- Metrics with **OpenTelemetry** and **Prometheus** integration.
|
||||||
|
- Webhooks for event-driven automation.
|
||||||
|
- Alerts with email and webhook notifications.
|
||||||
|
- Live tracing and metrics.
|
||||||
|
- **Web-based administration**:
|
||||||
|
- Dashboard with real-time statistics and monitoring.
|
||||||
|
- Account, domain, group and mailing list management.
|
||||||
|
- SMTP queue management for messages and outbound DMARC and TLS reports.
|
||||||
|
- Report visualization interface for received DMARC, TLS-RPT and Failure (ARF) reports.
|
||||||
|
- Configuration of every aspect of the mail server.
|
||||||
|
- Log viewer with search and filtering capabilities.
|
||||||
|
- Self-service portal for password reset and encryption-at-rest key management.
|
||||||
|
|
||||||
Upstream releases arrive as stripped snapshots, never with upstream's git
|
## Screenshots
|
||||||
history, which contains Enterprise code. `tools/fork/strip.py` builds each
|
|
||||||
snapshot on top of upstream's own `ossify.py`, then verifies it independently.
|
|
||||||
The report for every import is in `docs/fork/strip-reports/`. See
|
|
||||||
`docs/spec/SPEC.md` §2.
|
|
||||||
|
|
||||||
## Building
|
<img src="./img/demo.gif">
|
||||||
|
|
||||||
```bash
|
## Presentation
|
||||||
cargo build --release -p inbuxa # the binary is target/release/inbuxa
|
|
||||||
docker build -t inbuxa . # or the container image
|
|
||||||
```
|
|
||||||
|
|
||||||
Settings are read from `INBUXA_*` environment variables. An existing Stalwart
|
**Want a deeper dive?** Need to explain to your boss why Stalwart is the perfect fit? Whether you're evaluating options, making a case to your team, or simply curious about how it all works under the hood, these slides walk you through the key features, architecture, and benefits of Stalwart. Browse the [slides](https://stalw.art/slides) to see what makes it stand out.
|
||||||
install's `STALWART_*` variables still work, with a warning to rename them.
|
|
||||||
New installs keep their data in `/var/lib/inbuxa` and logs in
|
|
||||||
`/var/log/inbuxa`. Existing installs keep the paths their configuration
|
|
||||||
already names, so none of their data moves.
|
|
||||||
|
|
||||||
## License and credits
|
## Get Started
|
||||||
|
|
||||||
INBUXA is free software under the [GNU Affero General Public License,
|
Install Stalwart on your server by following the instructions for your platform:
|
||||||
version 3](./LICENSES/AGPL-3.0-only.txt).
|
|
||||||
|
|
||||||
It is a fork of Stalwart, copyright © Stalwart Labs LLC, **modified by
|
- [Linux / MacOS / FreeBSD](https://stalw.art/docs/install/platform/linux)
|
||||||
Coffey Labs in 2026**. Upstream's copyright notices are kept on every file
|
- [Windows](https://stalw.art/docs/install/platform/windows)
|
||||||
they cover, and every upstream file this fork changed says so in its header,
|
- [Docker](https://stalw.art/docs/install/platform/docker)
|
||||||
under the notice it came with. Stalwart's files are dual-licensed
|
|
||||||
AGPL-3.0-only or Stalwart's Enterprise License, and INBUXA takes them under
|
|
||||||
the AGPL-3.0 only. A few of those files also carry code from other projects
|
|
||||||
under MIT or BSD licenses, which stays under those licenses;
|
|
||||||
[THIRD-PARTY.md](./THIRD-PARTY.md) lists it with its notices. "Stalwart" is
|
|
||||||
Stalwart Labs' name. INBUXA isn't affiliated with or endorsed by Stalwart
|
|
||||||
Labs.
|
|
||||||
|
|
||||||
The INBUXA mark reuses ihasmail's cat-and-envelope artwork.
|
All documentation is available at [stalw.art/docs](https://stalw.art/docs/install/get-started).
|
||||||
|
|
||||||
|
## Support
|
||||||
|
|
||||||
|
If you are having problems running Stalwart, found a bug, or just have a question, please head to the [Stalwart Support Portal](https://support.stalw.art) at [support.stalw.art](https://support.stalw.art).
|
||||||
|
Additionally, you may purchase an [Enterprise License](https://stalw.art/enterprise) to obtain priority support from Stalwart Labs LLC, including response-time commitments and a private Priority Support area on the portal.
|
||||||
|
|
||||||
|
## Contributing
|
||||||
|
|
||||||
|
We welcome contributions, but to keep the project maintainable there are a few things to know before opening a pull request. Because of the high volume of low-quality, AI-generated submissions, pull requests are limited to a list of vouched contributors; to be added, post at [support.stalw.art](https://support.stalw.art) describing the change you would like to submit, together with a link to the proposed change. At this stage only bug fixes and translations are accepted, and new features are not, unless they involve just a few lines of code.
|
||||||
|
For the full guidelines, please read [CONTRIBUTING.md](CONTRIBUTING.md).
|
||||||
|
|
||||||
|
## Roadmap
|
||||||
|
|
||||||
|
Stalwart has reached an exciting point in its journey, it’s now **feature complete**. All the core functionality and open standard email and collaboration protocols that we set out to support are in place. In other words, Stalwart already does everything you’d expect from a modern, standards-compliant mail and collaboration platform.
|
||||||
|
|
||||||
|
The next major milestone is all about refinement: finalizing the database schema and focusing on performance optimizations to ensure everything runs as efficiently and reliably as possible. Once that’s done, we’ll be ready to roll out version **1.0**.
|
||||||
|
|
||||||
|
Of course, development doesn’t stop there. The community has contributed hundreds of great ideas for improvements and new features, everything from subtle usability tweaks to entirely new integrations. You can see the full list of proposals over on our [GitHub issues](https://github.com/stalwartlabs/stalwart/issues?q=is%3Aissue+is%3Aopen+sort%3Areactions-%2B1-desc+label%3Aenhancement). If there’s something you’d like to see prioritized, just give it a thumbs up as we plan to implement enhancements based on the community’s votes.
|
||||||
|
|
||||||
|
## Sponsorship
|
||||||
|
|
||||||
|
Your support is crucial in helping us continue to improve the project, add new features, and maintain the highest level of quality. By [becoming a sponsor](https://opencollective.com/stalwart), you help fund the development and future of Stalwart. As a thank-you, sponsors who contribute $5 per month or more will automatically receive a [Enterprise edition](https://stalw.art/enterprise/) license. And, sponsors who contribute $30 per month or more, also have access to [Premium Support](https://stalw.art/support) from Stalwart Labs.
|
||||||
|
|
||||||
|
## Funding
|
||||||
|
|
||||||
|
Part of the development of this project was funded through:
|
||||||
|
|
||||||
|
- [NGI0 Entrust Fund](https://nlnet.nl/entrust), a fund established by [NLnet](https://nlnet.nl/) with financial support from the European Commission's [Next Generation Internet](https://ngi.eu/) programme, under the aegis of DG Communications Networks, Content and Technology under grant agreement No 101069594.
|
||||||
|
- [NGI Zero Core](https://nlnet.nl/NGI0/), a fund established by [NLnet](https://nlnet.nl/) with financial support from the European Commission's programme, under the aegis of DG Communications Networks, Content and Technology under grant agreement No 101092990.
|
||||||
|
|
||||||
|
If you find the project useful you can help by [becoming a sponsor](https://opencollective.com/stalwart). Thank you!
|
||||||
|
|
||||||
|
## License
|
||||||
|
|
||||||
|
This project is dual-licensed under the **GNU Affero General Public License v3.0** (AGPL-3.0; as published by the Free Software Foundation) and the **Stalwart Enterprise License v2 (SELv2)**:
|
||||||
|
|
||||||
|
- The [GNU Affero General Public License v3.0](./LICENSES/AGPL-3.0-only.txt) is a free software license that ensures your freedom to use, modify, and distribute the software, with the condition that any modified versions of the software must also be distributed under the same license.
|
||||||
|
- The [Stalwart Enterprise License v2 (SELv2)](./LICENSES/LicenseRef-SEL.txt) is a proprietary license designed for commercial use. It offers additional features and greater flexibility for businesses that do not wish to comply with the AGPL-3.0 license requirements.
|
||||||
|
|
||||||
|
Each file in this project contains a license notice at the top, indicating the applicable license(s). The license notice follows the [REUSE guidelines](https://reuse.software/) to ensure clarity and consistency. The full text of each license is available in the [LICENSES](./LICENSES/) directory.
|
||||||
|
|
||||||
|
## Copyright
|
||||||
|
|
||||||
|
Copyright (C) 2020, Stalwart Labs LLC
|
||||||
|
|||||||
+139
-27
@@ -1,42 +1,154 @@
|
|||||||
# Security policy
|
# Security Policy for Stalwart
|
||||||
|
|
||||||
## Supported versions
|
## Supported Versions
|
||||||
|
|
||||||
INBUXA is developed on `main`, and security fixes are applied there and in
|
We provide security updates for the following versions of Stalwart:
|
||||||
the latest release. Older tags are not backported.
|
|
||||||
|
|
||||||
| Version | Supported |
|
| Version | Supported | End of Support |
|
||||||
| --- | --- |
|
| ------- | ------------------ | -------------- |
|
||||||
| `main` and the latest release | :white_check_mark: |
|
| 0.16.x | :white_check_mark: | TBD |
|
||||||
| Older releases | :x: |
|
| 0.15.x | :white_check_mark: | 2026-12-01 |
|
||||||
|
| < 0.14 | :x: | Ended |
|
||||||
|
|
||||||
## Reporting a vulnerability
|
**Note**: We typically support the current major version and one previous major version. Users are strongly encouraged to upgrade to the latest version for the best security posture.
|
||||||
|
|
||||||
**Please don't open a public issue for a security problem.** An issue is
|
## Reporting a Vulnerability
|
||||||
visible to everyone, including whoever would use it, before there is a fix.
|
|
||||||
|
|
||||||
Report it privately by email to:
|
We take the security of Stalwart very seriously. If you believe you've found a security vulnerability, we encourage you to inform us responsibly through coordinated disclosure.
|
||||||
|
|
||||||
**johnellisATlinuxDOTcom**
|
### How to Report
|
||||||
|
|
||||||
Include as much as you can of:
|
**Do not report security vulnerabilities through public GitHub issues, discussions, or social media.**
|
||||||
|
|
||||||
- what the vulnerability is, and what it lets someone do;
|
Instead, please use one of these secure channels:
|
||||||
- how to reproduce it, or a proof of concept;
|
|
||||||
- the version or commit affected;
|
|
||||||
- anything about the deployment that matters — backend, front ends, whether
|
|
||||||
it needs an authenticated account.
|
|
||||||
|
|
||||||
You'll get an acknowledgement within a few days. If a report turns out to
|
1. **Email** (preferred): Send details to `[email protected]`
|
||||||
affect upstream Stalwart rather than this fork's own code, it will be passed
|
2. **GitHub Security Advisories**: Use the "Report a vulnerability" button in the Security tab
|
||||||
to Stalwart Labs with credit to you, and you'll be told that has happened.
|
3. **Backup contact**: If no response within 48 hours, email `[email protected]`
|
||||||
|
|
||||||
|
### What to Include
|
||||||
|
|
||||||
|
To help us understand and address the issue quickly, please include:
|
||||||
|
|
||||||
|
**Required Information:**
|
||||||
|
- Brief description of the vulnerability type
|
||||||
|
- Affected version(s) and components
|
||||||
|
- Steps to reproduce the issue
|
||||||
|
- Impact assessment (what could an attacker achieve?)
|
||||||
|
|
||||||
|
**Helpful Additional Details:**
|
||||||
|
- Full paths of affected source files
|
||||||
|
- Specific commit/branch where the issue exists
|
||||||
|
- Required configuration to reproduce
|
||||||
|
- Proof-of-concept code (if available)
|
||||||
|
- Suggested mitigation or fix (if you have ideas)
|
||||||
|
|
||||||
|
### Our Response Process
|
||||||
|
|
||||||
|
**Timeline Commitments:**
|
||||||
|
- **Initial acknowledgment**: Within 24 hours
|
||||||
|
- **Detailed response**: Within 72 hours
|
||||||
|
- **Status updates**: Every 7 days until resolved
|
||||||
|
- **Resolution target**: 90 days for most issues
|
||||||
|
|
||||||
|
**What We'll Do:**
|
||||||
|
1. Acknowledge your report and assign a tracking ID
|
||||||
|
2. Assess the vulnerability and determine severity
|
||||||
|
3. Develop and test a fix
|
||||||
|
4. Coordinate disclosure timeline with you
|
||||||
|
5. Release security update and publish advisory
|
||||||
|
6. Credit you in our security advisory (if desired)
|
||||||
|
|
||||||
|
## Disclosure Policy
|
||||||
|
|
||||||
|
We follow responsible disclosure principles:
|
||||||
|
|
||||||
|
- **Coordinated disclosure**: We'll work with you to determine appropriate disclosure timing
|
||||||
|
- **Typical timeline**: 90 days from report to public disclosure
|
||||||
|
- **Early disclosure**: May occur if issue is being actively exploited
|
||||||
|
- **Delayed disclosure**: May be necessary for complex issues requiring significant changes
|
||||||
|
|
||||||
## Scope
|
## Scope
|
||||||
|
|
||||||
This repository is the mail server. The web front ends have their own:
|
This security policy applies to:
|
||||||
|
|
||||||
- [inbuxa-admin](https://github.com/inbuxa/inbuxa-admin)
|
**In Scope:**
|
||||||
- [ihasmail-inbuxa](https://github.com/inbuxa/ihasmail-inbuxa)
|
- Stalwart (all supported versions)
|
||||||
|
- Official Docker images
|
||||||
|
- Documentation that could lead to insecure configurations
|
||||||
|
- Dependencies with security implications
|
||||||
|
|
||||||
|
**Out of Scope:**
|
||||||
|
- Third-party integrations or plugins
|
||||||
|
- Issues requiring physical access to the server
|
||||||
|
- Social engineering attacks
|
||||||
|
- Attacks requiring compromised credentials (unless the vulnerability enables credential compromise)
|
||||||
|
- Theoretical vulnerabilities without practical exploitation
|
||||||
|
|
||||||
|
## Security Measures
|
||||||
|
|
||||||
|
**Our Commitments:**
|
||||||
|
- Regular security audits of dependencies using `cargo audit`
|
||||||
|
- Automated security scanning in CI/CD pipeline
|
||||||
|
- Following Rust security best practices
|
||||||
|
- Prompt security updates for critical dependencies
|
||||||
|
- Security-focused code review process
|
||||||
|
|
||||||
|
**User Responsibilities:**
|
||||||
|
- Keep Stalwart updated to supported versions
|
||||||
|
- Follow security configuration guidelines
|
||||||
|
- Implement proper network security (firewalls, TLS, etc.)
|
||||||
|
- Regular security monitoring and logging
|
||||||
|
- Secure credential management
|
||||||
|
|
||||||
|
## Legal Safe Harbor
|
||||||
|
|
||||||
|
We support security research conducted in good faith. If you follow these guidelines:
|
||||||
|
|
||||||
|
**We will NOT:**
|
||||||
|
- Initiate legal action against you
|
||||||
|
- Contact law enforcement about your research
|
||||||
|
- Suspend or terminate your access to Stalwart services
|
||||||
|
|
||||||
|
**You must:**
|
||||||
|
- Only test against your own Stalwart installations
|
||||||
|
- Not access, modify, or delete user data
|
||||||
|
- Not perform testing that could degrade service availability
|
||||||
|
- Not publicly disclose the issue before coordinated disclosure
|
||||||
|
- Act in good faith and not for malicious purposes
|
||||||
|
|
||||||
|
## Recognition
|
||||||
|
|
||||||
|
We believe in recognizing security researchers who help keep Stalwart secure:
|
||||||
|
|
||||||
|
- **Security Advisory Credits**: We'll credit you in our GitHub Security Advisories (unless you prefer to remain anonymous)
|
||||||
|
- **Hall of Fame**: Significant contributors may be listed in our security acknowledgments
|
||||||
|
- **Swag**: We may send Stalwart merchandise for notable contributions
|
||||||
|
|
||||||
|
## Security Updates
|
||||||
|
|
||||||
|
**Stay Informed:**
|
||||||
|
- Subscribe to our [GitHub releases](https://github.com/stalwartlabs/stalwart/releases) for security updates
|
||||||
|
- Join our community channels for security announcements
|
||||||
|
- Enable GitHub notifications for security advisories
|
||||||
|
|
||||||
|
**Update Process:**
|
||||||
|
- Security updates are published as patch releases (e.g., 0.12.1 → 0.12.2)
|
||||||
|
- Critical vulnerabilities may receive out-of-band releases
|
||||||
|
- Docker images are updated simultaneously with releases
|
||||||
|
- Security advisories are published through GitHub Security Advisories
|
||||||
|
|
||||||
|
## Contact Information
|
||||||
|
|
||||||
|
- **Security reports**: security@stalw.art
|
||||||
|
- **General inquiries**: hello@stalw.art
|
||||||
|
- **PGP Key**: Available upon request for sensitive communications
|
||||||
|
|
||||||
|
## Additional Resources
|
||||||
|
|
||||||
|
- [Stalwart Security Incident Response Process](SECURITY_PROCESS.md)
|
||||||
|
- [Security Configuration Guide](https://stalw.art/docs/install/security)
|
||||||
|
- [Rust Security Advisory Database](https://rustsec.org/)
|
||||||
|
|
||||||
|
*This security policy is effective as of June 20, 2025 and may be updated periodically. Check back regularly for updates.*
|
||||||
|
|
||||||
Upstream's own security documents are kept in `.github-upstream/` for
|
|
||||||
reference. They describe Stalwart Labs' process, not this project's.
|
|
||||||
|
|||||||
@@ -1,92 +0,0 @@
|
|||||||
# Third-party code
|
|
||||||
|
|
||||||
INBUXA is a fork of Stalwart. Stalwart is original work by Stalwart Labs LLC,
|
|
||||||
not a fork of anything, but a few of its files carry code, adapted or ported,
|
|
||||||
from other projects under permissive licenses. Those parts stay under their own
|
|
||||||
licenses, not the AGPL, and their notices are reproduced here as the licenses
|
|
||||||
require. Where a project offers MIT or Apache-2.0, INBUXA takes it under MIT.
|
|
||||||
|
|
||||||
`tools/fork/strip.py` lists every such file on each upstream import and names
|
|
||||||
any this page doesn't cover yet (docs/spec/SPEC.md §2.2). The fork's own code,
|
|
||||||
and Rust crates pulled in as dependencies, aren't listed here: dependencies
|
|
||||||
carry their own license files.
|
|
||||||
|
|
||||||
## Under the MIT license
|
|
||||||
|
|
||||||
| Where | From | Notice |
|
|
||||||
|---|---|---|
|
|
||||||
| `crates/common/src/scripts/functions/text.rs` | [levenshtein-rs](https://github.com/wooorm/levenshtein-rs) | Copyright (c) 2016 Titus Wormer <tituswormer@gmail.com> |
|
|
||||||
| `crates/common/src/telemetry/tracers/journald.rs` | the journald snippet | Copyright (c) 2018 Benjamin Saunders <ben.e.saunders@gmail.com> |
|
|
||||||
| `crates/jmap/src/registry/mapping/log.rs` | [rev_lines](https://github.com/mikeycgto/rev_lines) | Copyright (c) 2017 Michael Coyne <mjc@hey.com> |
|
|
||||||
| `crates/imap-proto/src/utf7.rs` | [MailKit](https://github.com/jstedfast/MailKit), by Jeffrey Stedfast | Copyright (C) 2013-2026 .NET Foundation and Contributors |
|
|
||||||
| `crates/nlp/src/tokenizers/japanese.rs` | [rust-tinysegmenter](https://github.com/woxtu/rust-tinysegmenter) | Copyright (c) 2015 woxtu |
|
|
||||||
| `crates/store/src/backend/postgres/tls.rs` | [tokio-postgres-rustls](https://github.com/jbg/tokio-postgres-rustls) | Copyright (c) 2019 Jasper Hugo |
|
|
||||||
| `crates/common/src/network/acme/directory.rs`, `crates/common/src/network/acme/jose.rs`, `crates/common/src/network/acme/order.rs` | [rustls-acme](https://github.com/FlorianUekermann/rustls-acme) (MIT or Apache-2.0) | Copyright (c) Florian Uekermann |
|
|
||||||
| `crates/types/src/id.rs` | [crockford](https://github.com/archer884/crockford) (MIT or Apache-2.0) | Copyright (c) 2017 J/A <archer884@gmail.com> |
|
|
||||||
| `crates/nlp/src/tokenizers/types.rs` | test cases from [linkify](https://github.com/robinst/linkify) (MIT or Apache-2.0) | Copyright (c) 2017 Robin Stocker |
|
|
||||||
|
|
||||||
Each notice above applies with this permission notice:
|
|
||||||
|
|
||||||
> Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
||||||
> of this software and associated documentation files (the "Software"), to deal
|
|
||||||
> in the Software without restriction, including without limitation the rights
|
|
||||||
> to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
||||||
> copies of the Software, and to permit persons to whom the Software is
|
|
||||||
> furnished to do so, subject to the following conditions:
|
|
||||||
>
|
|
||||||
> The above copyright notice and this permission notice shall be included in
|
|
||||||
> all copies or substantial portions of the Software.
|
|
||||||
>
|
|
||||||
> THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
||||||
> IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
||||||
> FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
||||||
> AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
||||||
> LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
||||||
> OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
||||||
> SOFTWARE.
|
|
||||||
|
|
||||||
## Under the BSD 3-Clause license
|
|
||||||
|
|
||||||
| Where | From | Notice |
|
|
||||||
|---|---|---|
|
|
||||||
| `crates/jmap-proto/src/types/date.rs`, `crates/registry/src/types/datetime.rs` | [upb](https://github.com/protocolbuffers/upb/blob/22182e6e/upb/json_decode.c), the date parsing marked in each file | Copyright (c) 2009-2011, Google Inc. All rights reserved. |
|
|
||||||
|
|
||||||
```text
|
|
||||||
Copyright (c) 2009-2011, Google Inc.
|
|
||||||
All rights reserved.
|
|
||||||
|
|
||||||
Redistribution and use in source and binary forms, with or without
|
|
||||||
modification, are permitted provided that the following conditions are met:
|
|
||||||
|
|
||||||
* Redistributions of source code must retain the above copyright
|
|
||||||
notice, this list of conditions and the following disclaimer.
|
|
||||||
* Redistributions in binary form must reproduce the above copyright
|
|
||||||
notice, this list of conditions and the following disclaimer in the
|
|
||||||
documentation and/or other materials provided with the distribution.
|
|
||||||
* Neither the name of Google Inc. nor the names of any other
|
|
||||||
contributors may be used to endorse or promote products
|
|
||||||
derived from this software without specific prior written permission.
|
|
||||||
|
|
||||||
THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY EXPRESS OR IMPLIED
|
|
||||||
WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
|
|
||||||
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
|
|
||||||
EVENT SHALL GOOGLE INC. BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
|
|
||||||
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
|
|
||||||
PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR
|
|
||||||
BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER
|
|
||||||
IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
|
|
||||||
ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
|
|
||||||
POSSIBILITY OF SUCH DAMAGE.
|
|
||||||
```
|
|
||||||
|
|
||||||
## Credited algorithms
|
|
||||||
|
|
||||||
These files implement published algorithms and credit their source. No code
|
|
||||||
is copied, so there's no notice to carry. They're listed so the strip report
|
|
||||||
doesn't flag them as new.
|
|
||||||
|
|
||||||
- `crates/jmap-proto/src/types/date.rs`, `crates/registry/src/types/datetime.rs`:
|
|
||||||
`civil_from_days`, from Howard Hinnant's
|
|
||||||
[date algorithms](http://howardhinnant.github.io/date_algorithms.html)
|
|
||||||
- `crates/utils/src/glob.rs`: Russ Cox's
|
|
||||||
[glob matching](https://research.swtch.com/glob)
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "common"
|
name = "common"
|
||||||
version = "0.16.22"
|
version = "0.16.23"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
build = "build.rs"
|
build = "build.rs"
|
||||||
|
|
||||||
@@ -13,7 +13,6 @@ directory = { path = "../directory" }
|
|||||||
coordinator = { path = "../coordinator" }
|
coordinator = { path = "../coordinator" }
|
||||||
types = { path = "../types" }
|
types = { path = "../types" }
|
||||||
registry = { path = "../registry" }
|
registry = { path = "../registry" }
|
||||||
inbuxa-features = { path = "../features" }
|
|
||||||
jmap_proto = { path = "../jmap-proto" }
|
jmap_proto = { path = "../jmap-proto" }
|
||||||
sieve-rs = { version = "0.7", features = ["rkyv", "serde"] }
|
sieve-rs = { version = "0.7", features = ["rkyv", "serde"] }
|
||||||
mail-parser = { version = "0.11", features = ["full_encoding"] }
|
mail-parser = { version = "0.11", features = ["full_encoding"] }
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use super::AccessToken;
|
use super::AccessToken;
|
||||||
@@ -798,14 +796,6 @@ impl AccessToken {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl AccessTokenInner {
|
impl AccessTokenInner {
|
||||||
/// inbuxa: SCIM-27: the account's own effective permission, from its
|
|
||||||
/// roles, its own settings and its tenant, before a credential narrows it
|
|
||||||
pub fn account_has_permission(&self, permission: Permission) -> bool {
|
|
||||||
self.scopes
|
|
||||||
.first()
|
|
||||||
.is_some_and(|scope| scope.permissions.get(permission as usize))
|
|
||||||
}
|
|
||||||
|
|
||||||
pub fn from_id(account_id: u32) -> Self {
|
pub fn from_id(account_id: u32) -> Self {
|
||||||
Self {
|
Self {
|
||||||
account_id,
|
account_id,
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -11,7 +9,7 @@ use crate::{
|
|||||||
auth::{
|
auth::{
|
||||||
AccessToken, AuthRequest, DomainCache,
|
AccessToken, AuthRequest, DomainCache,
|
||||||
credential::{ApiKey, AppPassword},
|
credential::{ApiKey, AppPassword},
|
||||||
oauth::GrantType,
|
oauth::{GrantType, token::TOKEN_HEADER},
|
||||||
},
|
},
|
||||||
};
|
};
|
||||||
use base64::{Engine, engine::general_purpose};
|
use base64::{Engine, engine::general_purpose};
|
||||||
@@ -23,7 +21,8 @@ use registry::schema::{
|
|||||||
enums::Permission,
|
enums::Permission,
|
||||||
structs::{self, Credential},
|
structs::{self, Credential},
|
||||||
};
|
};
|
||||||
use std::{net::IpAddr, sync::Arc};
|
use serde::Deserialize;
|
||||||
|
use std::{borrow::Cow, net::IpAddr, sync::Arc};
|
||||||
use store::write::now;
|
use store::write::now;
|
||||||
use trc::AddContext;
|
use trc::AddContext;
|
||||||
|
|
||||||
@@ -186,7 +185,7 @@ impl Server {
|
|||||||
};
|
};
|
||||||
|
|
||||||
is_alias_login = directory_account.email != auth_as_address;
|
is_alias_login = directory_account.email != auth_as_address;
|
||||||
self.build_directory_token(directory, directory_account, req.remote_ip)
|
self.build_directory_token(directory_account, req.remote_ip)
|
||||||
.await
|
.await
|
||||||
} else if let Some(account_id) =
|
} else if let Some(account_id) =
|
||||||
self.account_id_from_parts(auth_as_local, domain.id).await?
|
self.account_id_from_parts(auth_as_local, domain.id).await?
|
||||||
@@ -321,19 +320,12 @@ impl Server {
|
|||||||
// Obtain external directory, if any. When no username is supplied
|
// Obtain external directory, if any. When no username is supplied
|
||||||
// (e.g. HTTP bearer auth), peek at the JWT claims to find the
|
// (e.g. HTTP bearer auth), peek at the JWT claims to find the
|
||||||
// user's domain so per-domain OIDC directories are reachable.
|
// user's domain so per-domain OIDC directories are reachable.
|
||||||
let directory = if let Some(username) = username.as_deref().map(UsernameParts::new)
|
let directory = match username.as_deref().map(UsernameParts::new) {
|
||||||
{
|
Some(username) => match username.auth_as().domain() {
|
||||||
if let Some(domain_name) = username.auth_as().domain() {
|
Some(domain_name) => self.get_directory_for_domain(domain_name).await?,
|
||||||
self.get_directory_for_domain(domain_name).await?
|
None => self.get_directory_for_token(token).await?,
|
||||||
} else if let Some(domain_name) = extract_jwt_domain(token) {
|
},
|
||||||
self.get_directory_for_domain(&domain_name).await?
|
None => self.get_directory_for_token(token).await?,
|
||||||
} else {
|
|
||||||
self.get_default_directory()
|
|
||||||
}
|
|
||||||
} else if let Some(domain_name) = extract_jwt_domain(token) {
|
|
||||||
self.get_directory_for_domain(&domain_name).await?
|
|
||||||
} else {
|
|
||||||
self.get_default_directory()
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Try external directory authentication first if supported, then fallback to internal OAuth.
|
// Try external directory authentication first if supported, then fallback to internal OAuth.
|
||||||
@@ -343,38 +335,7 @@ impl Server {
|
|||||||
{
|
{
|
||||||
match directory.authenticate(&req.credentials).await {
|
match directory.authenticate(&req.credentials).await {
|
||||||
Ok(result) => {
|
Ok(result) => {
|
||||||
// inbuxa: DIR-7: the token must be the named user's, or
|
return self.build_directory_token(result, req.remote_ip).await;
|
||||||
// the named address an alias it may sign in with
|
|
||||||
let named = username
|
|
||||||
.as_deref()
|
|
||||||
.map(|name| UsernameParts::new(name).auth_as().address().to_lowercase());
|
|
||||||
let is_alias = match &named {
|
|
||||||
Some(named) if !named.eq_ignore_ascii_case(&result.email) => {
|
|
||||||
if !result
|
|
||||||
.email_aliases
|
|
||||||
.iter()
|
|
||||||
.any(|alias| alias.eq_ignore_ascii_case(named))
|
|
||||||
{
|
|
||||||
return Err(trc::AuthEvent::Failed
|
|
||||||
.into_err()
|
|
||||||
.ctx(trc::Key::AccountName, named.clone())
|
|
||||||
.details(result.email.clone())
|
|
||||||
.reason("The token belongs to a different user"));
|
|
||||||
}
|
|
||||||
true
|
|
||||||
}
|
|
||||||
_ => false,
|
|
||||||
};
|
|
||||||
let token = self
|
|
||||||
.build_directory_token(directory, result, req.remote_ip)
|
|
||||||
.await?;
|
|
||||||
if is_alias && !token.has_permission(Permission::AuthenticateWithAlias) {
|
|
||||||
return Err(trc::AuthEvent::Failed
|
|
||||||
.into_err()
|
|
||||||
.ctx(trc::Key::AccountId, token.account_id())
|
|
||||||
.reason("Authenticated using an email alias but account does not have AuthenticateAlias permission"));
|
|
||||||
}
|
|
||||||
return Ok(token);
|
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
external_error = Some(err);
|
external_error = Some(err);
|
||||||
@@ -415,8 +376,6 @@ impl Server {
|
|||||||
&& let Some(directory) = self.get_directory_for_cached_domain(&domain_cache)
|
&& let Some(directory) = self.get_directory_for_cached_domain(&domain_cache)
|
||||||
&& let Recipient::Account(account) = directory.recipient(address).await?
|
&& let Recipient::Account(account) = directory.recipient(address).await?
|
||||||
{
|
{
|
||||||
// inbuxa: DIR-6
|
|
||||||
self.assert_directory_serves(directory, &account.email).await?;
|
|
||||||
return Ok(Some(Box::pin(self.synchronize_account(account)).await?.id));
|
return Ok(Some(Box::pin(self.synchronize_account(account)).await?.id));
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -538,109 +497,95 @@ impl Server {
|
|||||||
|
|
||||||
async fn build_directory_token(
|
async fn build_directory_token(
|
||||||
&self,
|
&self,
|
||||||
directory: &Arc<Directory>,
|
|
||||||
account: directory::Account,
|
account: directory::Account,
|
||||||
remote_ip: IpAddr,
|
remote_ip: IpAddr,
|
||||||
) -> trc::Result<AccessToken> {
|
) -> trc::Result<AccessToken> {
|
||||||
// inbuxa: DIR-6
|
|
||||||
self.assert_directory_serves(directory, &account.email).await?;
|
|
||||||
let account = Box::pin(self.synchronize_account(account)).await?;
|
let account = Box::pin(self.synchronize_account(account)).await?;
|
||||||
self.access_token_from_account(account.id, account.account)
|
self.access_token_from_account(account.id, account.account)
|
||||||
.await
|
.await
|
||||||
.and_then(|token| AccessToken::new(token, remote_ip))
|
.and_then(|token| AccessToken::new(token, remote_ip))
|
||||||
}
|
}
|
||||||
|
|
||||||
/// inbuxa: DIR-1, DIR-5: the directory a domain signs in against: its
|
|
||||||
/// own, else the server default, else the internal one (`None`). An
|
|
||||||
/// unknown domain gets the server default.
|
|
||||||
pub async fn get_directory_for_domain(
|
pub async fn get_directory_for_domain(
|
||||||
&self,
|
&self,
|
||||||
domain_name: &str,
|
domain_name: &str,
|
||||||
) -> trc::Result<Option<&Arc<Directory>>> {
|
) -> trc::Result<Option<&Arc<Directory>>> {
|
||||||
Ok(match self.domain(domain_name).await? {
|
|
||||||
Some(domain) => self.get_directory_for_cached_domain(&domain),
|
Ok(self.get_default_directory())
|
||||||
None => self.get_default_directory(),
|
|
||||||
})
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// inbuxa: DIR-1, DIR-5: as above, for a domain already read. A
|
async fn get_directory_for_token(&self, token: &str) -> trc::Result<Option<&Arc<Directory>>> {
|
||||||
/// `directoryId` naming no directory the server built is unavailable,
|
let Some(payload) = JwtClaims::decode_payload(token) else {
|
||||||
/// never the internal directory.
|
return Ok(self.get_default_directory());
|
||||||
pub fn get_directory_for_cached_domain(&self, domain: &DomainCache) -> Option<&Arc<Directory>> {
|
|
||||||
match domain.id_directory {
|
|
||||||
Some(directory_id) => Some(
|
|
||||||
self.core
|
|
||||||
.storage
|
|
||||||
.directories
|
|
||||||
.get(&directory_id)
|
|
||||||
.unwrap_or_else(|| {
|
|
||||||
trc::event!(
|
|
||||||
Auth(trc::AuthEvent::Warning),
|
|
||||||
Domain = domain.name().to_string(),
|
|
||||||
Id = directory_id,
|
|
||||||
Reason = "The domain's directory doesn't exist; sign-in fails",
|
|
||||||
);
|
|
||||||
unavailable_directory()
|
|
||||||
}),
|
|
||||||
),
|
|
||||||
None => self.get_default_directory(),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// inbuxa: DIR-6: a directory speaks only for the domains it serves.
|
|
||||||
pub async fn assert_directory_serves(
|
|
||||||
&self,
|
|
||||||
directory: &Arc<Directory>,
|
|
||||||
address: &str,
|
|
||||||
) -> trc::Result<()> {
|
|
||||||
let serves = match address.rsplit_once('@') {
|
|
||||||
Some((_, domain)) => self
|
|
||||||
.get_directory_for_domain(domain)
|
|
||||||
.await?
|
|
||||||
.is_some_and(|effective| Arc::ptr_eq(effective, directory)),
|
|
||||||
None => false,
|
|
||||||
};
|
};
|
||||||
if serves {
|
let Some(claims) = JwtClaims::parse(&payload) else {
|
||||||
Ok(())
|
return Ok(self.get_default_directory());
|
||||||
} else {
|
};
|
||||||
Err(trc::AuthEvent::Failed
|
|
||||||
.into_err()
|
match (claims.domain(), claims.iss.as_deref()) {
|
||||||
.ctx(trc::Key::AccountName, address.to_string())
|
(Some(domain_name), _) => self.get_directory_for_domain(domain_name).await,
|
||||||
.reason("The directory returned an account on a domain it doesn't serve"))
|
(None, Some(issuer)) => Ok(self
|
||||||
|
.get_directory_for_issuer(issuer)
|
||||||
|
.or_else(|| self.get_default_directory())),
|
||||||
|
(None, None) => Ok(self.get_default_directory()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn get_directory_for_issuer(&self, issuer: &str) -> Option<&Arc<Directory>> {
|
||||||
|
|
||||||
|
None
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn get_directory_for_cached_domain(&self, domain: &DomainCache) -> Option<&Arc<Directory>> {
|
||||||
|
|
||||||
|
self.get_default_directory()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// inbuxa: DIR-5: what a dangling `directoryId` resolves to.
|
#[derive(Deserialize)]
|
||||||
pub fn unavailable_directory() -> &'static Arc<Directory> {
|
struct JwtClaims<'x> {
|
||||||
static UNAVAILABLE: std::sync::OnceLock<Arc<Directory>> = std::sync::OnceLock::new();
|
#[serde(borrow, default)]
|
||||||
UNAVAILABLE.get_or_init(|| {
|
iss: Option<Cow<'x, str>>,
|
||||||
Arc::new(Directory::Unavailable(directory::UnavailableDirectory::new(
|
#[serde(borrow, default)]
|
||||||
registry::schema::enums::DirectoryType::Ldap,
|
email: Option<Cow<'x, str>>,
|
||||||
"The directory named by the domain doesn't exist",
|
#[serde(borrow, default)]
|
||||||
)))
|
preferred_username: Option<Cow<'x, str>>,
|
||||||
})
|
#[serde(borrow, default)]
|
||||||
|
upn: Option<Cow<'x, str>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
fn extract_jwt_domain(token: &str) -> Option<String> {
|
impl<'x> JwtClaims<'x> {
|
||||||
let mut parts = token.split('.');
|
fn decode_payload(token: &str) -> Option<Vec<u8>> {
|
||||||
let _header = parts.next()?;
|
if token.starts_with(TOKEN_HEADER) {
|
||||||
let payload = parts.next()?;
|
return None;
|
||||||
let _signature = parts.next()?;
|
|
||||||
if parts.next().is_some() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
let payload_bytes = general_purpose::URL_SAFE_NO_PAD.decode(payload).ok()?;
|
|
||||||
let claims: serde_json::Value = serde_json::from_slice(&payload_bytes).ok()?;
|
|
||||||
for claim in ["email", "preferred_username", "upn"] {
|
|
||||||
if let Some(val) = claims.get(claim).and_then(|v| v.as_str())
|
|
||||||
&& let Some((_, domain)) = val.rsplit_once('@')
|
|
||||||
&& !domain.is_empty()
|
|
||||||
{
|
|
||||||
return Some(domain.to_ascii_lowercase());
|
|
||||||
}
|
}
|
||||||
|
|
||||||
|
let mut parts = token.split('.');
|
||||||
|
let _header = parts.next()?;
|
||||||
|
let payload = parts.next()?;
|
||||||
|
let _signature = parts.next()?;
|
||||||
|
if parts.next().is_some() {
|
||||||
|
return None;
|
||||||
|
}
|
||||||
|
|
||||||
|
general_purpose::URL_SAFE_NO_PAD.decode(payload).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn parse(payload: &'x [u8]) -> Option<Self> {
|
||||||
|
serde_json::from_slice(payload).ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn domain(&self) -> Option<&str> {
|
||||||
|
[&self.email, &self.preferred_username, &self.upn]
|
||||||
|
.into_iter()
|
||||||
|
.flatten()
|
||||||
|
.find_map(|claim| {
|
||||||
|
claim
|
||||||
|
.rsplit_once('@')
|
||||||
|
.map(|(_, domain)| domain)
|
||||||
|
.filter(|domain| !domain.is_empty())
|
||||||
|
})
|
||||||
}
|
}
|
||||||
None
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl UsernameParts {
|
impl UsernameParts {
|
||||||
@@ -738,3 +683,76 @@ impl AuthRequest {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
fn jwt(payload: &str) -> String {
|
||||||
|
format!(
|
||||||
|
"eyJhbGciOiJSUzI1NiJ9.{}.c2lnbmF0dXJl",
|
||||||
|
general_purpose::URL_SAFE_NO_PAD.encode(payload)
|
||||||
|
)
|
||||||
|
}
|
||||||
|
|
||||||
|
fn hints(token: &str) -> Option<(Option<String>, Option<String>)> {
|
||||||
|
let payload = JwtClaims::decode_payload(token)?;
|
||||||
|
let claims = JwtClaims::parse(&payload)?;
|
||||||
|
|
||||||
|
Some((
|
||||||
|
claims.domain().map(str::to_string),
|
||||||
|
claims.iss.as_deref().map(str::to_string),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn jwt_claims_are_extracted() {
|
||||||
|
for (payload, domain, issuer) in [
|
||||||
|
(
|
||||||
|
r#"{"iss":"https://idp.example.org","email":"[email protected]"}"#,
|
||||||
|
Some("Example.ORG"),
|
||||||
|
Some("https://idp.example.org"),
|
||||||
|
),
|
||||||
|
(
|
||||||
|
r#"{"preferred_username":"[email protected]","upn":"[email protected]"}"#,
|
||||||
|
Some("example.net"),
|
||||||
|
None,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
r#"{"email":"broken@","upn":"[email protected]"}"#,
|
||||||
|
Some("example.com"),
|
||||||
|
None,
|
||||||
|
),
|
||||||
|
(
|
||||||
|
r#"{"iss":"https://idp.example.org","sub":"5db2d1b6","aud":["a","b"],"scope":"openid"}"#,
|
||||||
|
None,
|
||||||
|
Some("https://idp.example.org"),
|
||||||
|
),
|
||||||
|
(r#"{"sub":"5db2d1b6"}"#, None, None),
|
||||||
|
(r#"{"email":"[email protected]"}"#, Some("example.net"), None),
|
||||||
|
] {
|
||||||
|
assert_eq!(
|
||||||
|
hints(&jwt(payload)),
|
||||||
|
Some((domain.map(str::to_string), issuer.map(str::to_string))),
|
||||||
|
"Unexpected claims for {payload}"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn non_jwt_tokens_are_ignored() {
|
||||||
|
for token in [
|
||||||
|
"sw1.eyJhbGciOiJSUzI1NiJ9.eyJpc3MiOiJodHRwczovL2lkcC5leGFtcGxlLm9yZyJ9",
|
||||||
|
"sw1.eyJhbGciOiJSUzI1NiJ9",
|
||||||
|
"opaque-token",
|
||||||
|
"one.two",
|
||||||
|
"one.two.three.four",
|
||||||
|
"",
|
||||||
|
] {
|
||||||
|
assert!(
|
||||||
|
JwtClaims::decode_payload(token).is_none(),
|
||||||
|
"Token {token:?} was parsed as a JWT"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -71,8 +69,7 @@ pub struct DomainCache {
|
|||||||
|
|
||||||
pub const DOMAIN_FLAG_RELAY: u8 = 1;
|
pub const DOMAIN_FLAG_RELAY: u8 = 1;
|
||||||
pub const DOMAIN_FLAG_SUB_ADDRESSING: u8 = 1 << 1;
|
pub const DOMAIN_FLAG_SUB_ADDRESSING: u8 = 1 << 1;
|
||||||
// inbuxa: SCIM-15, SCIM-58
|
|
||||||
pub const DOMAIN_FLAG_SCIM: u8 = 1 << 2;
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, Default)]
|
#[derive(Debug, Clone, Default)]
|
||||||
pub struct AccountCache {
|
pub struct AccountCache {
|
||||||
@@ -332,8 +329,4 @@ impl DomainCache {
|
|||||||
self.names.first().map(|s| s.as_ref()).unwrap_or_default()
|
self.names.first().map(|s| s.as_ref()).unwrap_or_default()
|
||||||
}
|
}
|
||||||
|
|
||||||
// inbuxa: SCIM-15, SCIM-58
|
|
||||||
pub fn allows_scim(&self) -> bool {
|
|
||||||
self.flags & DOMAIN_FLAG_SCIM != 0
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ pub const FAILED_TO_DECODE_TOKEN: &str = concat!(
|
|||||||
"the Authentication object."
|
"the Authentication object."
|
||||||
);
|
);
|
||||||
|
|
||||||
const TOKEN_HEADER: &str = "sw1.";
|
pub(crate) const TOKEN_HEADER: &str = "sw1.";
|
||||||
const TOKEN_KEY_CONTEXT: &str = "stalwart-oauth-token-sw1";
|
const TOKEN_KEY_CONTEXT: &str = "stalwart-oauth-token-sw1";
|
||||||
const OAUTH_EPOCH: u64 = 946684800; // Jan 1, 2000
|
const OAUTH_EPOCH: u64 = 946684800; // Jan 1, 2000
|
||||||
|
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -66,48 +64,10 @@ impl Server {
|
|||||||
.caused_by(trc::location!())?
|
.caused_by(trc::location!())?
|
||||||
}
|
}
|
||||||
|
|
||||||
// inbuxa: MT-13, MT-14, MT-15: cut down to what the tenant allows
|
|
||||||
if let Some(tenant_id) = tenant_id {
|
|
||||||
self.apply_tenant_ceiling(&mut permissions, tenant_id)
|
|
||||||
.await
|
|
||||||
.caused_by(trc::location!())?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(permissions)
|
Ok(permissions)
|
||||||
}
|
}
|
||||||
|
|
||||||
/// inbuxa: MT-13. The tenant's roles give the base; its own permission
|
|
||||||
/// lists adjust it (`inbuxa_features::tenancy::ceiling`).
|
|
||||||
async fn apply_tenant_ceiling(
|
|
||||||
&self,
|
|
||||||
permissions: &mut PermissionsGroup,
|
|
||||||
tenant_id: u32,
|
|
||||||
) -> trc::Result<()> {
|
|
||||||
use inbuxa_features::tenancy::ceiling::{Policy, ceiling};
|
|
||||||
|
|
||||||
let tenant = self.tenant(tenant_id).await?;
|
|
||||||
let base = self
|
|
||||||
.add_role_permissions(PermissionsGroup::default(), tenant.id_roles.iter().copied())
|
|
||||||
.await?
|
|
||||||
.finalize();
|
|
||||||
let policy = match tenant.permissions.as_deref() {
|
|
||||||
None => Policy::Inherit,
|
|
||||||
Some(list) if list.merge => Policy::Merge {
|
|
||||||
enabled: &list.enabled,
|
|
||||||
disabled: &list.disabled,
|
|
||||||
},
|
|
||||||
Some(list) => Policy::Replace {
|
|
||||||
enabled: &list.enabled,
|
|
||||||
disabled: &list.disabled,
|
|
||||||
},
|
|
||||||
};
|
|
||||||
ceiling(base, policy).apply(&mut permissions.enabled, &mut permissions.disabled);
|
|
||||||
// inbuxa: MT-1, MT-15: impersonation would reach beyond the tenant
|
|
||||||
permissions.disabled.set(Permission::Impersonate as usize);
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub async fn can_set_permissions(
|
pub async fn can_set_permissions(
|
||||||
&self,
|
&self,
|
||||||
access_token: &AccessToken,
|
access_token: &AccessToken,
|
||||||
@@ -264,11 +224,6 @@ impl Default for DefaultPermissions {
|
|||||||
default.superuser.push(permission);
|
default.superuser.push(permission);
|
||||||
default.tenant.push(permission);
|
default.tenant.push(permission);
|
||||||
}
|
}
|
||||||
// inbuxa: MT-12: a tenant administrator reads its own tenant
|
|
||||||
Permission::SysTenantGet | Permission::SysTenantQuery => {
|
|
||||||
default.superuser.push(permission);
|
|
||||||
default.tenant.push(permission);
|
|
||||||
}
|
|
||||||
permission => {
|
permission => {
|
||||||
let name = permission.as_str();
|
let name = permission.as_str();
|
||||||
if name.starts_with("jmap")
|
if name.starts_with("jmap")
|
||||||
|
|||||||
Vendored
-100
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::{Server, auth::DomainCache, cache::invalidate::CacheInvalidationBuilder};
|
use crate::{Server, auth::DomainCache, cache::invalidate::CacheInvalidationBuilder};
|
||||||
@@ -53,14 +51,6 @@ impl Server {
|
|||||||
.ctx(trc::Key::AccountId, account_id)
|
.ctx(trc::Key::AccountId, account_id)
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
// inbuxa: SCIM-58: SCIM is authoritative; sign-in changes nothing
|
|
||||||
if domain.allows_scim() {
|
|
||||||
return Ok(AccountWithId {
|
|
||||||
id: account_id,
|
|
||||||
account: Account::from(current_account),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut updated_account = Account::from(current_account.clone())
|
let mut updated_account = Account::from(current_account.clone())
|
||||||
.into_user()
|
.into_user()
|
||||||
.ok_or_else(|| {
|
.ok_or_else(|| {
|
||||||
@@ -89,7 +79,6 @@ impl Server {
|
|||||||
for alias in account.email_aliases {
|
for alias in account.email_aliases {
|
||||||
if let Some((local, alias_domain)) = self.validate_alias(&alias).await?
|
if let Some((local, alias_domain)) = self.validate_alias(&alias).await?
|
||||||
&& alias_domain.id_tenant == domain.id_tenant
|
&& alias_domain.id_tenant == domain.id_tenant
|
||||||
&& self.same_directory(&domain, &alias).await?
|
|
||||||
&& self
|
&& self
|
||||||
.rcpt_id_from_parts(local, alias_domain.id)
|
.rcpt_id_from_parts(local, alias_domain.id)
|
||||||
.await?
|
.await?
|
||||||
@@ -107,12 +96,6 @@ impl Server {
|
|||||||
if let Some(groups) = account.groups {
|
if let Some(groups) = account.groups {
|
||||||
let mut member_group_ids = Vec::with_capacity(groups.len());
|
let mut member_group_ids = Vec::with_capacity(groups.len());
|
||||||
for email in groups {
|
for email in groups {
|
||||||
// inbuxa: SCIM-58: no group comes from a claim on a SCIM domain
|
|
||||||
if self.is_scim_address(&email).await?
|
|
||||||
|| !self.same_directory(&domain, &email).await?
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
member_group_ids.push(
|
member_group_ids.push(
|
||||||
self.synchronize_group(directory::Group {
|
self.synchronize_group(directory::Group {
|
||||||
email,
|
email,
|
||||||
@@ -172,19 +155,11 @@ impl Server {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
// inbuxa: SCIM-58: accounts on this domain come from SCIM only
|
|
||||||
if domain.allows_scim() {
|
|
||||||
return Err(trc::AuthEvent::Failed
|
|
||||||
.into_err()
|
|
||||||
.details("The account isn't provisioned: its domain is managed by SCIM")
|
|
||||||
.ctx(trc::Key::AccountName, account.email));
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut aliases = Vec::with_capacity(account.email_aliases.len());
|
let mut aliases = Vec::with_capacity(account.email_aliases.len());
|
||||||
for alias in account.email_aliases {
|
for alias in account.email_aliases {
|
||||||
if let Some((local, alias_domain)) = self.validate_alias(&alias).await?
|
if let Some((local, alias_domain)) = self.validate_alias(&alias).await?
|
||||||
&& alias_domain.id_tenant == domain.id_tenant
|
&& alias_domain.id_tenant == domain.id_tenant
|
||||||
&& self.same_directory(&domain, &alias).await?
|
|
||||||
&& self
|
&& self
|
||||||
.rcpt_id_from_parts(local, alias_domain.id)
|
.rcpt_id_from_parts(local, alias_domain.id)
|
||||||
.await?
|
.await?
|
||||||
@@ -200,12 +175,6 @@ impl Server {
|
|||||||
}
|
}
|
||||||
let mut member_group_ids = Vec::new();
|
let mut member_group_ids = Vec::new();
|
||||||
for email in account.groups.unwrap_or_default() {
|
for email in account.groups.unwrap_or_default() {
|
||||||
// inbuxa: SCIM-58: no group comes from a claim on a SCIM domain
|
|
||||||
if self.is_scim_address(&email).await?
|
|
||||||
|| !self.same_directory(&domain, &email).await?
|
|
||||||
{
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
member_group_ids.push(
|
member_group_ids.push(
|
||||||
self.synchronize_group(directory::Group {
|
self.synchronize_group(directory::Group {
|
||||||
email,
|
email,
|
||||||
@@ -236,8 +205,6 @@ impl Server {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
|
|
||||||
// inbuxa: DIR-15
|
|
||||||
self.check_tenant_limits(&account).await?;
|
|
||||||
match self
|
match self
|
||||||
.registry()
|
.registry()
|
||||||
.write(RegistryWrite::insert(&account))
|
.write(RegistryWrite::insert(&account))
|
||||||
@@ -288,11 +255,6 @@ impl Server {
|
|||||||
.ctx(trc::Key::AccountId, account_id)
|
.ctx(trc::Key::AccountId, account_id)
|
||||||
})?;
|
})?;
|
||||||
|
|
||||||
// inbuxa: SCIM-58: SCIM is authoritative; sign-in changes nothing
|
|
||||||
if domain.allows_scim() {
|
|
||||||
return Ok(account_id);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut updated_account = Account::from(current_account.clone())
|
let mut updated_account = Account::from(current_account.clone())
|
||||||
.into_group()
|
.into_group()
|
||||||
.ok_or_else(|| {
|
.ok_or_else(|| {
|
||||||
@@ -313,7 +275,6 @@ impl Server {
|
|||||||
for alias in group.email_aliases {
|
for alias in group.email_aliases {
|
||||||
if let Some((local, alias_domain)) = self.validate_alias(&alias).await?
|
if let Some((local, alias_domain)) = self.validate_alias(&alias).await?
|
||||||
&& alias_domain.id_tenant == domain.id_tenant
|
&& alias_domain.id_tenant == domain.id_tenant
|
||||||
&& self.same_directory(&domain, &alias).await?
|
|
||||||
&& self
|
&& self
|
||||||
.rcpt_id_from_parts(local, alias_domain.id)
|
.rcpt_id_from_parts(local, alias_domain.id)
|
||||||
.await?
|
.await?
|
||||||
@@ -361,19 +322,11 @@ impl Server {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
None => {
|
None => {
|
||||||
// inbuxa: SCIM-58: groups on this domain come from SCIM only
|
|
||||||
if domain.allows_scim() {
|
|
||||||
return Err(trc::AuthEvent::Error
|
|
||||||
.into_err()
|
|
||||||
.details("The group isn't provisioned: its domain is managed by SCIM")
|
|
||||||
.ctx(trc::Key::AccountName, group.email));
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut aliases = Vec::with_capacity(group.email_aliases.len());
|
let mut aliases = Vec::with_capacity(group.email_aliases.len());
|
||||||
for alias in group.email_aliases {
|
for alias in group.email_aliases {
|
||||||
if let Some((local, alias_domain)) = self.validate_alias(&alias).await?
|
if let Some((local, alias_domain)) = self.validate_alias(&alias).await?
|
||||||
&& alias_domain.id_tenant == domain.id_tenant
|
&& alias_domain.id_tenant == domain.id_tenant
|
||||||
&& self.same_directory(&domain, &alias).await?
|
|
||||||
&& self
|
&& self
|
||||||
.rcpt_id_from_parts(local, alias_domain.id)
|
.rcpt_id_from_parts(local, alias_domain.id)
|
||||||
.await?
|
.await?
|
||||||
@@ -400,8 +353,6 @@ impl Server {
|
|||||||
}));
|
}));
|
||||||
|
|
||||||
|
|
||||||
// inbuxa: DIR-15
|
|
||||||
self.check_tenant_limits(&account).await?;
|
|
||||||
match self
|
match self
|
||||||
.registry()
|
.registry()
|
||||||
.write(RegistryWrite::insert(&account))
|
.write(RegistryWrite::insert(&account))
|
||||||
@@ -427,57 +378,6 @@ impl Server {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// inbuxa: DIR-6: whether an address is on a domain served by the same
|
|
||||||
/// directory as `domain`; a warning when it isn't.
|
|
||||||
async fn same_directory(&self, domain: &DomainCache, address: &str) -> trc::Result<bool> {
|
|
||||||
let Some((_, other)) = address.rsplit_once('@') else {
|
|
||||||
return Ok(true);
|
|
||||||
};
|
|
||||||
let Some(other) = self.domain(other).await? else {
|
|
||||||
return Ok(true);
|
|
||||||
};
|
|
||||||
let same = match (
|
|
||||||
self.get_directory_for_cached_domain(domain),
|
|
||||||
self.get_directory_for_cached_domain(&other),
|
|
||||||
) {
|
|
||||||
(None, None) => true,
|
|
||||||
(Some(a), Some(b)) => Arc::ptr_eq(a, b),
|
|
||||||
_ => false,
|
|
||||||
};
|
|
||||||
if !same {
|
|
||||||
trc::event!(
|
|
||||||
Auth(trc::AuthEvent::Warning),
|
|
||||||
AccountName = address.to_string(),
|
|
||||||
Domain = other.name().to_string(),
|
|
||||||
Reason = "Dropped: the address is on a domain served by another directory",
|
|
||||||
);
|
|
||||||
}
|
|
||||||
Ok(same)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// inbuxa: DIR-15, MT-3, MT-17: an object created from a directory
|
|
||||||
/// passes the same tenant checks as one created over JMAP.
|
|
||||||
async fn check_tenant_limits(&self, object: &Object) -> trc::Result<()> {
|
|
||||||
match inbuxa_features::tenancy::writes::check(self.registry(), None, None, object).await? {
|
|
||||||
Ok(_) => Ok(()),
|
|
||||||
Err(err) => Err(trc::AuthEvent::Failed
|
|
||||||
.into_err()
|
|
||||||
.details(err.description().unwrap_or("A tenant limit is reached").to_string())
|
|
||||||
.reason("The directory's account can't be created")),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// inbuxa: SCIM-58: whether an address is on a domain SCIM manages.
|
|
||||||
async fn is_scim_address(&self, address: &str) -> trc::Result<bool> {
|
|
||||||
Ok(match address.rsplit_once('@') {
|
|
||||||
Some((_, domain)) => self
|
|
||||||
.domain(domain)
|
|
||||||
.await?
|
|
||||||
.is_some_and(|domain| domain.allows_scim()),
|
|
||||||
None => false,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn validate_address<'x>(
|
async fn validate_address<'x>(
|
||||||
&self,
|
&self,
|
||||||
email: &'x str,
|
email: &'x str,
|
||||||
|
|||||||
+1
-31
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -19,6 +17,7 @@ use registry::{
|
|||||||
},
|
},
|
||||||
types::id::ObjectId,
|
types::id::ObjectId,
|
||||||
};
|
};
|
||||||
|
use store::{registry::RegistryQuery, roaring::RoaringBitmap};
|
||||||
use types::id::Id;
|
use types::id::Id;
|
||||||
|
|
||||||
#[derive(Debug, Default)]
|
#[derive(Debug, Default)]
|
||||||
@@ -121,10 +120,6 @@ impl CacheInvalidationBuilder {
|
|||||||
|| (current.sub_addressing != new.sub_addressing)
|
|| (current.sub_addressing != new.sub_addressing)
|
||||||
|| (current.allow_relaying != new.allow_relaying)
|
|| (current.allow_relaying != new.allow_relaying)
|
||||||
|| (current.is_enabled != new.is_enabled)
|
|| (current.is_enabled != new.is_enabled)
|
||||||
// inbuxa: SCIM-60, the flag is cached as DOMAIN_FLAG_SCIM,
|
|
||||||
// so turning SCIM's authority on or off has to take effect
|
|
||||||
// without a restart
|
|
||||||
|| (current.allow_scim_provisioning != new.allow_scim_provisioning)
|
|
||||||
{
|
{
|
||||||
self.invalidate(CacheInvalidation::Domain(id));
|
self.invalidate(CacheInvalidation::Domain(id));
|
||||||
}
|
}
|
||||||
@@ -286,15 +281,6 @@ impl Server {
|
|||||||
.registry()
|
.registry()
|
||||||
.linked_objects(ObjectId::new(ObjectType::Role, role_id.into()))
|
.linked_objects(ObjectId::new(ObjectType::Role, role_id.into()))
|
||||||
.await?;
|
.await?;
|
||||||
// inbuxa: MT-16: a role a tenant holds sets its ceiling
|
|
||||||
for tenant_id in inbuxa_features::tenancy::members::tenants_using_role(
|
|
||||||
self.registry(),
|
|
||||||
&linked_objects,
|
|
||||||
)
|
|
||||||
.await?
|
|
||||||
{
|
|
||||||
changes.insert(CacheInvalidation::Tenant(tenant_id));
|
|
||||||
}
|
|
||||||
for linked_object in linked_objects {
|
for linked_object in linked_objects {
|
||||||
match linked_object.object() {
|
match linked_object.object() {
|
||||||
ObjectType::Account => {
|
ObjectType::Account => {
|
||||||
@@ -312,22 +298,6 @@ impl Server {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// inbuxa: MT-16: a tenant's change reaches its people on their next request
|
|
||||||
let tenant_ids = changes
|
|
||||||
.iter()
|
|
||||||
.filter_map(|change| match change {
|
|
||||||
CacheInvalidation::Tenant(tenant_id) => Some(*tenant_id),
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
for tenant_id in tenant_ids {
|
|
||||||
for account_id in
|
|
||||||
inbuxa_features::tenancy::members::accounts(self.registry(), tenant_id).await?
|
|
||||||
{
|
|
||||||
changes.insert(CacheInvalidation::AccessToken(account_id));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let changes = changes.into_iter().collect::<Vec<_>>();
|
let changes = changes.into_iter().collect::<Vec<_>>();
|
||||||
self.invalidate_local_caches(&changes).await;
|
self.invalidate_local_caches(&changes).await;
|
||||||
self.cluster_broadcast(BroadcastEvent::CacheInvalidate(changes))
|
self.cluster_broadcast(BroadcastEvent::CacheInvalidate(changes))
|
||||||
|
|||||||
+3
-32
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -30,7 +28,7 @@ use registry::{
|
|||||||
enums::{DkimRotationStage, Locale, StorageQuota, TenantStorageQuota},
|
enums::{DkimRotationStage, Locale, StorageQuota, TenantStorageQuota},
|
||||||
prelude::{ObjectType, Property},
|
prelude::{ObjectType, Property},
|
||||||
structs::{
|
structs::{
|
||||||
Account, DkimSignature, Domain, EncryptionAtRest, MailingList,
|
Account, DkimSignature, Domain, EncryptionAtRest, MailingList, MaskedEmail,
|
||||||
Permissions, PublicKey, Role, SubAddressing, Tenant,
|
Permissions, PublicKey, Role, SubAddressing, Tenant,
|
||||||
},
|
},
|
||||||
},
|
},
|
||||||
@@ -40,7 +38,7 @@ use std::{borrow::Cow, sync::Arc};
|
|||||||
use store::{
|
use store::{
|
||||||
U64_LEN,
|
U64_LEN,
|
||||||
registry::{RegistryQuery, bootstrap::Bootstrap},
|
registry::{RegistryQuery, bootstrap::Bootstrap},
|
||||||
write::key::KeySerializer,
|
write::{key::KeySerializer, now},
|
||||||
};
|
};
|
||||||
use trc::{AddContext, StoreEvent};
|
use trc::{AddContext, StoreEvent};
|
||||||
use types::id::Id;
|
use types::id::Id;
|
||||||
@@ -160,11 +158,7 @@ impl Server {
|
|||||||
if domain.allow_relaying {
|
if domain.allow_relaying {
|
||||||
flags |= DOMAIN_FLAG_RELAY;
|
flags |= DOMAIN_FLAG_RELAY;
|
||||||
}
|
}
|
||||||
// inbuxa: SCIM-15, SCIM-58: the domain is open to SCIM, and SCIM is
|
|
||||||
// authoritative for its accounts
|
|
||||||
if domain.allow_scim_provisioning {
|
|
||||||
flags |= crate::auth::DOMAIN_FLAG_SCIM;
|
|
||||||
}
|
|
||||||
|
|
||||||
let sub_addressing_custom = match domain.sub_addressing {
|
let sub_addressing_custom = match domain.sub_addressing {
|
||||||
SubAddressing::Enabled => {
|
SubAddressing::Enabled => {
|
||||||
@@ -299,29 +293,6 @@ impl Server {
|
|||||||
|
|
||||||
Ok(Some(result))
|
Ok(Some(result))
|
||||||
} else {
|
} else {
|
||||||
// inbuxa: ME-4, ME-6: a live masked address reaches its
|
|
||||||
// owner; a refused one isn't cached, as it can come back
|
|
||||||
if let Some(domain) = self.domain_by_id(domain_id).await?
|
|
||||||
&& let Some(name) = domain.names.first()
|
|
||||||
{
|
|
||||||
use inbuxa_features::masked_email::ops::{Lookup, lookup};
|
|
||||||
match lookup(
|
|
||||||
&self.core.storage.data,
|
|
||||||
self.registry(),
|
|
||||||
&format!("{local_part}@{name}"),
|
|
||||||
)
|
|
||||||
.await?
|
|
||||||
{
|
|
||||||
Lookup::Accepts(mask) => {
|
|
||||||
return Ok(Some(EmailCache::Account(
|
|
||||||
mask.object.account_id.document_id(),
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
Lookup::Refuses => return Ok(None),
|
|
||||||
Lookup::Unknown => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Cache negative result
|
// Cache negative result
|
||||||
emails_negative.insert(
|
emails_negative.insert(
|
||||||
EmailAddress::new(local_part, domain_id),
|
EmailAddress::new(local_part, domain_id),
|
||||||
|
|||||||
Vendored
+2
-3
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -132,7 +130,8 @@ impl Server {
|
|||||||
|
|
||||||
// Update tracers
|
// Update tracers
|
||||||
|
|
||||||
tracers.update();
|
#[cfg(not(feature = "enterprise"))]
|
||||||
|
tracers.update(false);
|
||||||
|
|
||||||
// Reload queue settings
|
// Reload queue settings
|
||||||
self.inner
|
self.inner
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use calcard::vcard::VCardVersion;
|
use calcard::vcard::VCardVersion;
|
||||||
@@ -102,17 +100,6 @@ impl GroupwareConfig {
|
|||||||
let dr = bp.setting_infallible::<DataRetention>().await;
|
let dr = bp.setting_infallible::<DataRetention>().await;
|
||||||
let system = bp.setting_infallible::<SystemSettings>().await;
|
let system = bp.setting_infallible::<SystemSettings>().await;
|
||||||
|
|
||||||
// inbuxa: BT-19: a stored template that doesn't parse is reported at
|
|
||||||
// start and on each reload; the built-in is used meanwhile
|
|
||||||
inbuxa_features::branding::templates::warn_unusable::<CalendarTemplateVariable>(
|
|
||||||
"CalendarAlarm.template",
|
|
||||||
alarm.template.as_deref(),
|
|
||||||
);
|
|
||||||
inbuxa_features::branding::templates::warn_unusable::<CalendarTemplateVariable>(
|
|
||||||
"CalendarScheduling.emailTemplate",
|
|
||||||
sched.email_template.as_deref(),
|
|
||||||
);
|
|
||||||
|
|
||||||
GroupwareConfig {
|
GroupwareConfig {
|
||||||
max_request_size: dav.request_max_size as usize,
|
max_request_size: dav.request_max_size as usize,
|
||||||
dead_property_size: dav.dead_property_max_size.map(|v| v as usize),
|
dead_property_size: dav.dead_property_max_size.map(|v| v as usize),
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -92,7 +90,7 @@ impl Scripting {
|
|||||||
.with_protected_headers(untrusted.protected_headers)
|
.with_protected_headers(untrusted.protected_headers)
|
||||||
.with_vacation_default_subject(untrusted.default_subject)
|
.with_vacation_default_subject(untrusted.default_subject)
|
||||||
.with_vacation_subject_prefix(untrusted.default_subject_prefix)
|
.with_vacation_subject_prefix(untrusted.default_subject_prefix)
|
||||||
.with_env_variable("name", types::brand_server!())
|
.with_env_variable("name", "Stalwart Server")
|
||||||
.with_env_variable("version", VERSION_PUBLIC)
|
.with_env_variable("version", VERSION_PUBLIC)
|
||||||
.with_env_variable("location", "MS")
|
.with_env_variable("location", "MS")
|
||||||
.with_env_variable("phase", "during");
|
.with_env_variable("phase", "during");
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::expr::{
|
use crate::expr::{
|
||||||
@@ -428,26 +426,15 @@ impl SpamFilterLists {
|
|||||||
&tag.tag,
|
&tag.tag,
|
||||||
SpamFilterAction::Allow(tag.score.into_inner() as f32),
|
SpamFilterAction::Allow(tag.score.into_inner() as f32),
|
||||||
),
|
),
|
||||||
SpamTag::Discard(tag) => {
|
SpamTag::Discard(tag) => lists
|
||||||
warn_llm_refusal(&tag.tag);
|
.scores
|
||||||
lists
|
.insert_pattern(&tag.tag, SpamFilterAction::Discard),
|
||||||
.scores
|
SpamTag::Reject(tag) => lists
|
||||||
.insert_pattern(&tag.tag, SpamFilterAction::Discard)
|
.scores
|
||||||
}
|
.insert_pattern(&tag.tag, SpamFilterAction::Reject),
|
||||||
SpamTag::Reject(tag) => {
|
|
||||||
warn_llm_refusal(&tag.tag);
|
|
||||||
lists
|
|
||||||
.scores
|
|
||||||
.insert_pattern(&tag.tag, SpamFilterAction::Reject)
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// inbuxa: AI-2: at start and each reload, models off this network are flagged
|
|
||||||
for model in bp.list_infallible::<registry::schema::structs::AiModel>().await {
|
|
||||||
crate::enterprise::llm::warn_if_remote(&model.object).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
for ext in bp.list_infallible::<SpamFileExtension>().await {
|
for ext in bp.list_infallible::<SpamFileExtension>().await {
|
||||||
let ext = ext.object;
|
let ext = ext.object;
|
||||||
lists.file_extensions.insert_pattern(
|
lists.file_extensions.insert_pattern(
|
||||||
@@ -753,16 +740,3 @@ mod tests {
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// inbuxa: AI-13: a Discard or Reject on the model's tag counts as no entry
|
|
||||||
fn warn_llm_refusal(tag: &str) {
|
|
||||||
if inbuxa_features::ai::answer::is_llm_tag(tag) {
|
|
||||||
trc::event!(
|
|
||||||
Registry(trc::RegistryEvent::BuildWarning),
|
|
||||||
Details = format!(
|
|
||||||
"Spam tag {tag} discards or rejects, which the language model's opinion alone \
|
|
||||||
may not do: it scores 0 (AI-13)"
|
|
||||||
),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use std::io::Cursor;
|
use std::io::Cursor;
|
||||||
@@ -40,7 +38,7 @@ pub mod storage;
|
|||||||
pub mod telemetry;
|
pub mod telemetry;
|
||||||
|
|
||||||
impl Core {
|
impl Core {
|
||||||
pub async fn parse(bp: &mut Bootstrap, storage: Storage) -> Self {
|
pub async fn parse(bp: &mut Bootstrap, mut storage: Storage) -> Self {
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
sieve: Scripting::parse(bp).await,
|
sieve: Scripting::parse(bp).await,
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -64,9 +62,6 @@ pub struct Http {
|
|||||||
pub url_https: String,
|
pub url_https: String,
|
||||||
pub allowed_endpoint: IfBlock,
|
pub allowed_endpoint: IfBlock,
|
||||||
pub response_headers: Vec<(hyper::header::HeaderName, hyper::header::HeaderValue)>,
|
pub response_headers: Vec<(hyper::header::HeaderName, hyper::header::HeaderValue)>,
|
||||||
/// inbuxa: origins allowed cross-origin access (contract C-14). Empty when
|
|
||||||
/// CORS is permissive (bootstrap, recovery, or `usePermissiveCors`).
|
|
||||||
pub cors_origins: Vec<hyper::header::HeaderValue>,
|
|
||||||
pub use_forwarded: bool,
|
pub use_forwarded: bool,
|
||||||
pub redirect_root: Option<String>,
|
pub redirect_root: Option<String>,
|
||||||
}
|
}
|
||||||
@@ -195,7 +190,7 @@ impl Network {
|
|||||||
}),
|
}),
|
||||||
info: Info {
|
info: Info {
|
||||||
provider: Provider {
|
provider: Provider {
|
||||||
name: types::brand!().into(),
|
name: "Stalwart".into(),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
},
|
},
|
||||||
..Default::default()
|
..Default::default()
|
||||||
@@ -413,17 +408,6 @@ impl Http {
|
|||||||
#[cfg(not(feature = "dev_mode"))]
|
#[cfg(not(feature = "dev_mode"))]
|
||||||
let use_permissive_cors = http.use_permissive_cors || bp.registry.is_recovery_mode();
|
let use_permissive_cors = http.use_permissive_cors || bp.registry.is_recovery_mode();
|
||||||
|
|
||||||
// inbuxa: otherwise only the front ends' origins get cross-origin
|
|
||||||
// access, echoed per request (contract C-14)
|
|
||||||
let cors_origins = if use_permissive_cors {
|
|
||||||
Vec::new()
|
|
||||||
} else {
|
|
||||||
crate::manager::first_party::front_end_origins()
|
|
||||||
.into_iter()
|
|
||||||
.filter_map(|origin| hyper::header::HeaderValue::from_str(&origin).ok())
|
|
||||||
.collect()
|
|
||||||
};
|
|
||||||
|
|
||||||
if use_permissive_cors {
|
if use_permissive_cors {
|
||||||
http_headers.push((
|
http_headers.push((
|
||||||
hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN,
|
hyper::header::ACCESS_CONTROL_ALLOW_ORIGIN,
|
||||||
@@ -480,7 +464,6 @@ impl Http {
|
|||||||
http.rate_limit_anonymous
|
http.rate_limit_anonymous
|
||||||
},
|
},
|
||||||
response_headers: http_headers,
|
response_headers: http_headers,
|
||||||
cors_origins,
|
|
||||||
use_forwarded: http.use_x_forwarded,
|
use_forwarded: http.use_x_forwarded,
|
||||||
redirect_root: http.redirect_root,
|
redirect_root: http.redirect_root,
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use super::{
|
use super::{
|
||||||
@@ -71,7 +69,7 @@ impl Listeners {
|
|||||||
bind: Map::new(vec![
|
bind: Map::new(vec![
|
||||||
SocketAddr::from_str(&format!(
|
SocketAddr::from_str(&format!(
|
||||||
"[::]:{}",
|
"[::]:{}",
|
||||||
types::branding::env_var("RECOVERY_MODE_PORT")
|
std::env::var("STALWART_RECOVERY_MODE_PORT")
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|p| p.parse::<u16>().ok())
|
.and_then(|p| p.parse::<u16>().ok())
|
||||||
.unwrap_or(8080)
|
.unwrap_or(8080)
|
||||||
|
|||||||
@@ -214,6 +214,7 @@ impl Resolvers {
|
|||||||
let config_dnssec = resolver_config.clone();
|
let config_dnssec = resolver_config.clone();
|
||||||
let mut opts_dnssec = opts.clone();
|
let mut opts_dnssec = opts.clone();
|
||||||
opts_dnssec.validate = true;
|
opts_dnssec.validate = true;
|
||||||
|
opts_dnssec.num_concurrent_reqs = 1;
|
||||||
|
|
||||||
let dnssec = DnssecResolver {
|
let dnssec = DnssecResolver {
|
||||||
resolver: TokioResolver::builder_with_config(
|
resolver: TokioResolver::builder_with_config(
|
||||||
@@ -343,6 +344,7 @@ impl Default for Resolvers {
|
|||||||
let config_dnssec = config.clone();
|
let config_dnssec = config.clone();
|
||||||
let mut opts_dnssec = opts.clone();
|
let mut opts_dnssec = opts.clone();
|
||||||
opts_dnssec.validate = true;
|
opts_dnssec.validate = true;
|
||||||
|
opts_dnssec.num_concurrent_reqs = 1;
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
dns: MessageAuthenticator::new(config, opts).expect("Failed to build DNS resolver"),
|
dns: MessageAuthenticator::new(config, opts).expect("Failed to build DNS resolver"),
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use coordinator::Coordinator;
|
use coordinator::Coordinator;
|
||||||
@@ -43,19 +41,12 @@ impl Storage {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
let coordinator = Coordinator::build(bp, &memory).await.unwrap_or_default();
|
|
||||||
// inbuxa: ST-7: with more than one node, read replicas share
|
|
||||||
// high-water marks through the in-memory store
|
|
||||||
if !matches!(coordinator, Coordinator::None) {
|
|
||||||
bp.data_store.share_marks(&memory);
|
|
||||||
}
|
|
||||||
|
|
||||||
Storage {
|
Storage {
|
||||||
registry: bp.registry.clone(),
|
registry: bp.registry.clone(),
|
||||||
data: bp.data_store.clone(),
|
data: bp.data_store.clone(),
|
||||||
blob: BlobStore::build(bp).await.unwrap_or_default(),
|
blob: BlobStore::build(bp).await.unwrap_or_default(),
|
||||||
search,
|
search,
|
||||||
coordinator,
|
coordinator: Coordinator::build(bp, &memory).await.unwrap_or_default(),
|
||||||
memory,
|
memory,
|
||||||
tracing: Store::build_tracing(bp).await.unwrap_or_default(),
|
tracing: Store::build_tracing(bp).await.unwrap_or_default(),
|
||||||
metrics: Store::build_metrics(bp).await.unwrap_or_default(),
|
metrics: Store::build_metrics(bp).await.unwrap_or_default(),
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::config::storage::Storage;
|
use crate::config::storage::Storage;
|
||||||
@@ -42,15 +40,6 @@ pub enum TelemetrySubscriberType {
|
|||||||
Webhook(WebhookTracer),
|
Webhook(WebhookTracer),
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
JournalTracer(crate::telemetry::tracers::journald::Subscriber),
|
JournalTracer(crate::telemetry::tracers::journald::Subscriber),
|
||||||
// inbuxa: MON-10: trace history
|
|
||||||
StoreTracer(StoreTracer),
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Where trace history goes: traces to `tracing`, index tasks to `data`.
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct StoreTracer {
|
|
||||||
pub tracing: store::Store,
|
|
||||||
pub data: store::Store,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
@@ -397,7 +386,6 @@ impl Tracers {
|
|||||||
TelemetrySubscriberType::JournalTracer(_) => {
|
TelemetrySubscriberType::JournalTracer(_) => {
|
||||||
EventType::Telemetry(TelemetryEvent::JournalError).into()
|
EventType::Telemetry(TelemetryEvent::JournalError).into()
|
||||||
}
|
}
|
||||||
TelemetrySubscriberType::StoreTracer(_) => None,
|
|
||||||
};
|
};
|
||||||
|
|
||||||
// Parse disabled events
|
// Parse disabled events
|
||||||
@@ -489,36 +477,6 @@ impl Tracers {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// inbuxa: MON-10 to MON-12: trace history, when a tracing store is set:
|
|
||||||
// info and above, the span edges and MAIL FROM, never raw I/O
|
|
||||||
if !storage.tracing.is_none() {
|
|
||||||
let mut interests = Interests::default();
|
|
||||||
for event_type in EventType::variants() {
|
|
||||||
let event_level = custom_levels
|
|
||||||
.get(event_type)
|
|
||||||
.copied()
|
|
||||||
.unwrap_or(event_type.level());
|
|
||||||
if !event_type.is_raw_io()
|
|
||||||
&& (Level::Info.is_contained(event_level)
|
|
||||||
|| event_type.is_span_start()
|
|
||||||
|| event_type.is_span_end()
|
|
||||||
|| event_type.as_str().starts_with("smtp.mail-from"))
|
|
||||||
{
|
|
||||||
interests.set(event_type.to_id() as usize);
|
|
||||||
global_interests.set(event_type.to_id() as usize);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
tracers.push(TelemetrySubscriber {
|
|
||||||
id: "trace-history".to_string(),
|
|
||||||
interests,
|
|
||||||
typ: TelemetrySubscriberType::StoreTracer(StoreTracer {
|
|
||||||
tracing: storage.tracing.clone(),
|
|
||||||
data: storage.data.clone(),
|
|
||||||
}),
|
|
||||||
lossy: true,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "dev_mode")]
|
#[cfg(feature = "dev_mode")]
|
||||||
if let Ok(level) = std::env::var("LOG") {
|
if let Ok(level) = std::env::var("LOG") {
|
||||||
let level = Level::from_str(&level).expect("Invalid LOG level");
|
let level = Level::from_str(&level).expect("Invalid LOG level");
|
||||||
@@ -545,7 +503,7 @@ impl Tracers {
|
|||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
// Add default tracer if none were found
|
// Add default tracer if none were found
|
||||||
let level = types::branding::env_var("RECOVERY_MODE_LOG_LEVEL")
|
let level = std::env::var("STALWART_RECOVERY_MODE_LOG_LEVEL")
|
||||||
.ok()
|
.ok()
|
||||||
.and_then(|level| Level::from_str(&level).ok())
|
.and_then(|level| Level::from_str(&level).ok())
|
||||||
.unwrap_or(Level::Info);
|
.unwrap_or(Level::Info);
|
||||||
@@ -584,10 +542,10 @@ impl Metrics {
|
|||||||
let metrics = bp.setting_infallible::<structs::Metrics>().await;
|
let metrics = bp.setting_infallible::<structs::Metrics>().await;
|
||||||
let resource = Resource::builder()
|
let resource = Resource::builder()
|
||||||
.with_service_name("stalwart")
|
.with_service_name("stalwart")
|
||||||
.with_attribute(KeyValue::new(SERVICE_VERSION, types::brand_version_full!()))
|
.with_attribute(KeyValue::new(SERVICE_VERSION, env!("CARGO_PKG_VERSION")))
|
||||||
.build();
|
.build();
|
||||||
let instrumentation = InstrumentationScope::builder("stalwart")
|
let instrumentation = InstrumentationScope::builder("stalwart")
|
||||||
.with_version(types::brand_version_full!())
|
.with_version(env!("CARGO_PKG_VERSION"))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
Metrics {
|
Metrics {
|
||||||
|
|||||||
@@ -1,355 +0,0 @@
|
|||||||
/*
|
|
||||||
* SPDX-FileCopyrightText: 2026 Coffey Labs
|
|
||||||
*
|
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only
|
|
||||||
*/
|
|
||||||
|
|
||||||
//! Calling the operator's model (AI spam classification spec, AI-5 to AI-11,
|
|
||||||
//! AI-21 to AI-25). The rules live in `inbuxa_features::ai`; this makes the
|
|
||||||
//! HTTP request. The wire types are the OpenAI-compatible chat completions
|
|
||||||
//! shapes local model servers speak.
|
|
||||||
|
|
||||||
use crate::Server;
|
|
||||||
use inbuxa_features::ai::{
|
|
||||||
gate::{Gate, Refused, Transition},
|
|
||||||
limits::{self, AiLimits},
|
|
||||||
locality,
|
|
||||||
request::{self, Kind, MAX_RESPONSE_BYTES},
|
|
||||||
};
|
|
||||||
use registry::schema::{
|
|
||||||
enums::AiModelType,
|
|
||||||
prelude::ObjectType,
|
|
||||||
structs::AiModel,
|
|
||||||
};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use std::time::{Duration, Instant};
|
|
||||||
use store::registry::RegistryQuery;
|
|
||||||
use trc::AiEvent;
|
|
||||||
use types::id::Id;
|
|
||||||
|
|
||||||
/// A chat completions request.
|
|
||||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
|
||||||
pub struct ChatCompletionRequest {
|
|
||||||
pub model: String,
|
|
||||||
pub messages: Vec<Message>,
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pub temperature: Option<f64>,
|
|
||||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
|
||||||
pub max_tokens: Option<u32>,
|
|
||||||
#[serde(default)]
|
|
||||||
pub stream: bool,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One chat message.
|
|
||||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
|
||||||
pub struct Message {
|
|
||||||
pub role: String,
|
|
||||||
pub content: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A chat completions response.
|
|
||||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
|
||||||
pub struct ChatCompletionResponse {
|
|
||||||
pub created: i64,
|
|
||||||
pub object: String,
|
|
||||||
pub id: String,
|
|
||||||
pub model: String,
|
|
||||||
pub choices: Vec<ChatCompletionChoice>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One choice in a response.
|
|
||||||
#[derive(Debug, Clone, Default, Serialize, Deserialize)]
|
|
||||||
pub struct ChatCompletionChoice {
|
|
||||||
pub index: u32,
|
|
||||||
pub finish_reason: String,
|
|
||||||
pub message: Message,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Why a call produced no answer. Every one leaves mail flowing (AI-9).
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub enum Failure {
|
|
||||||
Refused(Refused),
|
|
||||||
Timeout,
|
|
||||||
Http(String),
|
|
||||||
Status(u16),
|
|
||||||
BadAnswer,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// One call to make.
|
|
||||||
pub struct Call<'x> {
|
|
||||||
pub model_id: Id,
|
|
||||||
pub model: &'x AiModel,
|
|
||||||
/// Set for an account's own script (AI-24, AI-25).
|
|
||||||
pub account_id: Option<u32>,
|
|
||||||
pub system: Option<&'x str>,
|
|
||||||
pub user: &'x str,
|
|
||||||
pub temperature: f64,
|
|
||||||
pub max_tokens: u32,
|
|
||||||
pub timeout: Duration,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn kind(model: &AiModel) -> Kind {
|
|
||||||
match model.model_type {
|
|
||||||
AiModelType::Chat => Kind::Chat,
|
|
||||||
AiModelType::Text => Kind::Text,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Server {
|
|
||||||
/// The fork's limits, as stored now.
|
|
||||||
pub async fn ai_limits(&self) -> AiLimits {
|
|
||||||
limits::get(&self.core.storage.data)
|
|
||||||
.await
|
|
||||||
.unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A model by its id.
|
|
||||||
pub async fn ai_model_by_id(&self, id: Id) -> Option<AiModel> {
|
|
||||||
self.registry().object::<AiModel>(id).await.ok().flatten()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A model by name, or failing that by id (AI-20).
|
|
||||||
pub async fn ai_model_by_name(&self, name: &str) -> Option<(Id, AiModel)> {
|
|
||||||
let ids = self
|
|
||||||
.registry()
|
|
||||||
.query::<Vec<Id>>(RegistryQuery::new(ObjectType::AiModel))
|
|
||||||
.await
|
|
||||||
.ok()?;
|
|
||||||
let mut by_id = None;
|
|
||||||
for id in ids {
|
|
||||||
if let Some(model) = self.ai_model_by_id(id).await {
|
|
||||||
if model.name == name {
|
|
||||||
return Some((id, model));
|
|
||||||
}
|
|
||||||
if id.to_string() == name {
|
|
||||||
by_id = Some((id, model));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
by_id
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Makes one call. The answer, or why there is none; either way the
|
|
||||||
/// outcome is logged, with no message content and no secret (AI-5).
|
|
||||||
pub async fn ai_call(&self, call: Call<'_>) -> Result<String, Failure> {
|
|
||||||
let limits = self.ai_limits().await;
|
|
||||||
let gate = Gate::global();
|
|
||||||
let permit = match gate.try_start(call.model_id.id(), call.account_id, limits.gate()) {
|
|
||||||
Ok(permit) => permit,
|
|
||||||
Err(refused) => {
|
|
||||||
trc::event!(
|
|
||||||
Ai(AiEvent::ApiError),
|
|
||||||
Details = call.model.name.clone(),
|
|
||||||
AccountId = call.account_id,
|
|
||||||
Reason = format!("{refused:?}"),
|
|
||||||
);
|
|
||||||
return Err(Failure::Refused(refused));
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let started = Instant::now();
|
|
||||||
let result = tokio::time::timeout(call.timeout, self.ai_request(&call)).await;
|
|
||||||
let result = match result {
|
|
||||||
Ok(result) => result,
|
|
||||||
Err(_) => Err(Failure::Timeout),
|
|
||||||
};
|
|
||||||
let transition = permit.finish(result.is_ok(), limits.failure_backoff.into_inner());
|
|
||||||
match &transition {
|
|
||||||
Some(Transition::Paused) => trc::event!(
|
|
||||||
Ai(AiEvent::ApiError),
|
|
||||||
Details = call.model.name.clone(),
|
|
||||||
Reason = format!(
|
|
||||||
"Paused for {}s after repeated failures",
|
|
||||||
limits.failure_backoff.into_inner().as_secs()
|
|
||||||
),
|
|
||||||
),
|
|
||||||
Some(Transition::Resumed) => trc::event!(
|
|
||||||
Ai(AiEvent::LlmResponse),
|
|
||||||
Details = call.model.name.clone(),
|
|
||||||
Reason = "Resumed after a pause",
|
|
||||||
),
|
|
||||||
None => {}
|
|
||||||
}
|
|
||||||
match &result {
|
|
||||||
Ok(answer) => trc::event!(
|
|
||||||
Ai(AiEvent::LlmResponse),
|
|
||||||
Details = call.model.name.clone(),
|
|
||||||
AccountId = call.account_id,
|
|
||||||
Elapsed = started.elapsed(),
|
|
||||||
Result = request::cut(answer, 1024),
|
|
||||||
),
|
|
||||||
Err(failure) => trc::event!(
|
|
||||||
Ai(AiEvent::ApiError),
|
|
||||||
Details = call.model.name.clone(),
|
|
||||||
AccountId = call.account_id,
|
|
||||||
Elapsed = started.elapsed(),
|
|
||||||
Code = match failure {
|
|
||||||
Failure::Status(code) => *code as u64,
|
|
||||||
_ => 0,
|
|
||||||
},
|
|
||||||
Reason = format!("{failure:?}"),
|
|
||||||
),
|
|
||||||
}
|
|
||||||
result
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn ai_request(&self, call: &Call<'_>) -> Result<String, Failure> {
|
|
||||||
let model = call.model;
|
|
||||||
let kind = kind(model);
|
|
||||||
let body = request::body(
|
|
||||||
kind,
|
|
||||||
&model.model,
|
|
||||||
call.system,
|
|
||||||
call.user,
|
|
||||||
call.temperature,
|
|
||||||
call.max_tokens,
|
|
||||||
);
|
|
||||||
// Secrets are read now, from their source (AI-8)
|
|
||||||
let headers = model
|
|
||||||
.http_auth
|
|
||||||
.build_headers(model.http_headers.clone(), Some("application/json"))
|
|
||||||
.await
|
|
||||||
.map_err(Failure::Http)?;
|
|
||||||
let client = utils::http::http_client_builder(model.allow_invalid_certs)
|
|
||||||
// A redirect would send content to a host nobody named (AI-8)
|
|
||||||
.redirect(reqwest::redirect::Policy::none())
|
|
||||||
.connect_timeout(call.timeout)
|
|
||||||
.timeout(call.timeout)
|
|
||||||
.default_headers(headers)
|
|
||||||
.build()
|
|
||||||
.map_err(|err| Failure::Http(err.to_string()))?;
|
|
||||||
let mut response = client
|
|
||||||
.post(&model.url)
|
|
||||||
.body(body.to_string())
|
|
||||||
.send()
|
|
||||||
.await
|
|
||||||
.map_err(|err| {
|
|
||||||
if err.is_timeout() {
|
|
||||||
Failure::Timeout
|
|
||||||
} else {
|
|
||||||
Failure::Http(err.without_url().to_string())
|
|
||||||
}
|
|
||||||
})?;
|
|
||||||
let status = response.status().as_u16();
|
|
||||||
if status != 200 {
|
|
||||||
return Err(Failure::Status(status));
|
|
||||||
}
|
|
||||||
let mut bytes = Vec::new();
|
|
||||||
while let Some(chunk) = response
|
|
||||||
.chunk()
|
|
||||||
.await
|
|
||||||
.map_err(|err| Failure::Http(err.without_url().to_string()))?
|
|
||||||
{
|
|
||||||
bytes.extend_from_slice(&chunk);
|
|
||||||
if bytes.len() > MAX_RESPONSE_BYTES {
|
|
||||||
return Err(Failure::BadAnswer);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
request::answer(kind, &bytes).ok_or(Failure::BadAnswer)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// AI-2: warns when a model's endpoint isn't on this network.
|
|
||||||
pub async fn ai_warn_if_remote(&self, model: &AiModel) {
|
|
||||||
warn_if_remote(model).await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// AI-2: warns when a model's endpoint isn't on this network. Names are
|
|
||||||
/// resolved; any address outside the local ranges counts.
|
|
||||||
pub async fn warn_if_remote(model: &AiModel) {
|
|
||||||
let local = match locality::classify(&model.url) {
|
|
||||||
Some(local) => local,
|
|
||||||
None => {
|
|
||||||
let host = locality::host(&model.url).unwrap_or_default().to_string();
|
|
||||||
match tokio::net::lookup_host((host.as_str(), 443)).await {
|
|
||||||
Ok(addrs) => {
|
|
||||||
let addrs = addrs.map(|a| a.ip()).collect::<Vec<_>>();
|
|
||||||
!addrs.is_empty()
|
|
||||||
&& addrs.into_iter().all(locality::is_local_ip)
|
|
||||||
}
|
|
||||||
Err(_) => false,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
};
|
|
||||||
if !local {
|
|
||||||
trc::event!(
|
|
||||||
Registry(trc::RegistryEvent::BuildWarning),
|
|
||||||
Details = locality::warning(&model.name, &model.url),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The most of a script's prompt sent (AI-23).
|
|
||||||
const MAX_PROMPT_BYTES: usize = 32 * 1024;
|
|
||||||
|
|
||||||
/// The most of an answer a script gets back (AI-22).
|
|
||||||
const MAX_SCRIPT_ANSWER_BYTES: usize = 8 * 1024;
|
|
||||||
|
|
||||||
/// The longest an account's own script waits (AI-23).
|
|
||||||
const ACCOUNT_SCRIPT_CEILING: Duration = Duration::from_secs(60);
|
|
||||||
|
|
||||||
/// `llm_prompt(model, prompt, temperature)` (AI-20 to AI-25). The answer as
|
|
||||||
/// plain text, or `None`, which the script sees as `false`.
|
|
||||||
pub async fn sieve_prompt(
|
|
||||||
ctx: crate::scripts::plugins::PluginContext<'_>,
|
|
||||||
) -> Option<String> {
|
|
||||||
use registry::schema::enums::Permission;
|
|
||||||
use sieve::runtime::Variable;
|
|
||||||
|
|
||||||
let server = ctx.server;
|
|
||||||
let name = ctx.arguments.first()?.to_string();
|
|
||||||
let prompt = ctx.arguments.get(1)?.to_string();
|
|
||||||
let temperature = match ctx.arguments.get(2) {
|
|
||||||
Some(Variable::Float(t)) => Some(*t),
|
|
||||||
Some(Variable::Integer(t)) => Some(*t as f64),
|
|
||||||
_ => None,
|
|
||||||
};
|
|
||||||
|
|
||||||
// AI-23: trusted system scripts always; an account's own with interactAi
|
|
||||||
let account_id = match ctx.access_token {
|
|
||||||
Some(token) if !token.has_permission(Permission::InteractAi) => {
|
|
||||||
trc::event!(
|
|
||||||
Ai(AiEvent::ApiError),
|
|
||||||
SpanId = ctx.session_id,
|
|
||||||
AccountId = token.account_id(),
|
|
||||||
Reason = "The account may not call AI models",
|
|
||||||
);
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
Some(token) => Some(token.account_id()),
|
|
||||||
None => None,
|
|
||||||
};
|
|
||||||
|
|
||||||
let Some((model_id, model)) = server.ai_model_by_name(name.as_ref()).await else {
|
|
||||||
trc::event!(
|
|
||||||
Ai(AiEvent::ApiError),
|
|
||||||
SpanId = ctx.session_id,
|
|
||||||
AccountId = account_id,
|
|
||||||
Reason = format!("No AI model named {name:?}"),
|
|
||||||
);
|
|
||||||
return None;
|
|
||||||
};
|
|
||||||
let limits = server.ai_limits().await;
|
|
||||||
let timeout = match account_id {
|
|
||||||
Some(_) => model.timeout.into_inner().min(ACCOUNT_SCRIPT_CEILING),
|
|
||||||
None => model
|
|
||||||
.timeout
|
|
||||||
.into_inner()
|
|
||||||
.min(limits.spam_call_ceiling.into_inner()),
|
|
||||||
};
|
|
||||||
let prompt = request::cut(&prompt, MAX_PROMPT_BYTES);
|
|
||||||
let answer = server
|
|
||||||
.ai_call(Call {
|
|
||||||
model_id,
|
|
||||||
model: &model,
|
|
||||||
account_id,
|
|
||||||
system: None,
|
|
||||||
user: &prompt,
|
|
||||||
temperature: temperature.unwrap_or_else(|| model.temperature.into_inner()),
|
|
||||||
max_tokens: request::PROMPT_MAX_TOKENS,
|
|
||||||
timeout,
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.ok()?;
|
|
||||||
// Plain data: never evaluated (AI-22)
|
|
||||||
Some(request::cut(answer.trim(), MAX_SCRIPT_ANSWER_BYTES))
|
|
||||||
}
|
|
||||||
@@ -1,10 +0,0 @@
|
|||||||
/*
|
|
||||||
* SPDX-FileCopyrightText: 2026 Coffey Labs
|
|
||||||
*
|
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only
|
|
||||||
*/
|
|
||||||
|
|
||||||
//! Rebuilt features that sit on the server itself, at the paths the shared
|
|
||||||
//! tests name. The rules live in `inbuxa_features`.
|
|
||||||
|
|
||||||
pub mod llm;
|
|
||||||
@@ -23,6 +23,13 @@ pub(crate) fn fn_is_number(v: Vec<Variable>) -> Variable {
|
|||||||
matches!(&v[0], Variable::Integer(_) | Variable::Float(_)).into()
|
matches!(&v[0], Variable::Integer(_) | Variable::Float(_)).into()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(crate) fn fn_bit_and(v: Vec<Variable>) -> Variable {
|
||||||
|
match (v[0].to_integer(), v[1].to_integer()) {
|
||||||
|
(Some(lhs), Some(rhs)) => Variable::Integer(lhs & rhs),
|
||||||
|
_ => Variable::Integer(0),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
pub(crate) fn fn_is_ip_addr(v: Vec<Variable>) -> Variable {
|
pub(crate) fn fn_is_ip_addr(v: Vec<Variable>) -> Variable {
|
||||||
v[0].to_string()
|
v[0].to_string()
|
||||||
.as_str()
|
.as_str()
|
||||||
|
|||||||
@@ -46,6 +46,7 @@ pub(crate) const FUNCTIONS: &[(&str, fn(Vec<Variable>) -> Variable, u32)] = &[
|
|||||||
("email_part", email::fn_email_part, 2),
|
("email_part", email::fn_email_part, 2),
|
||||||
("is_empty", misc::fn_is_empty, 1),
|
("is_empty", misc::fn_is_empty, 1),
|
||||||
("is_number", misc::fn_is_number, 1),
|
("is_number", misc::fn_is_number, 1),
|
||||||
|
("bit_and", misc::fn_bit_and, 2),
|
||||||
("is_ip_addr", misc::fn_is_ip_addr, 1),
|
("is_ip_addr", misc::fn_is_ip_addr, 1),
|
||||||
("is_ipv4_addr", misc::fn_is_ipv4_addr, 1),
|
("is_ipv4_addr", misc::fn_is_ipv4_addr, 1),
|
||||||
("is_ipv6_addr", misc::fn_is_ipv6_addr, 1),
|
("is_ipv6_addr", misc::fn_is_ipv6_addr, 1),
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::config::smtp::{
|
use crate::config::smtp::{
|
||||||
@@ -45,11 +43,6 @@ pub enum PushEvent {
|
|||||||
account_id: u32,
|
account_id: u32,
|
||||||
broadcast: bool,
|
broadcast: bool,
|
||||||
},
|
},
|
||||||
// inbuxa: SCIM-52: ends the push subscriptions the account itself holds
|
|
||||||
// (IMAP IDLE, JMAP event streams and WebSockets) on this node
|
|
||||||
Revoke {
|
|
||||||
account_id: u32,
|
|
||||||
},
|
|
||||||
Stop,
|
Stop,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|||||||
+59
-20
@@ -2,14 +2,8 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// inbuxa: composite stores (sharded members, read replicas) nest store
|
|
||||||
// futures deeply enough to pass rustc's default query depth
|
|
||||||
#![recursion_limit = "512"]
|
|
||||||
|
|
||||||
#![warn(clippy::large_futures)]
|
#![warn(clippy::large_futures)]
|
||||||
|
|
||||||
use crate::auth::{AccessTokenInner, EmailAddress};
|
use crate::auth::{AccessTokenInner, EmailAddress};
|
||||||
@@ -73,7 +67,6 @@ pub mod i18n;
|
|||||||
pub mod ipc;
|
pub mod ipc;
|
||||||
pub mod manager;
|
pub mod manager;
|
||||||
pub mod network;
|
pub mod network;
|
||||||
pub mod enterprise; // inbuxa: rebuilt features (AI spam classification)
|
|
||||||
pub mod scripts;
|
pub mod scripts;
|
||||||
pub mod sharing;
|
pub mod sharing;
|
||||||
pub mod storage;
|
pub mod storage;
|
||||||
@@ -85,9 +78,9 @@ pub use psl;
|
|||||||
pub static VERSION_PRIVATE: &str = env!("CARGO_PKG_VERSION");
|
pub static VERSION_PRIVATE: &str = env!("CARGO_PKG_VERSION");
|
||||||
pub static VERSION_PUBLIC: &str = "1.0.0";
|
pub static VERSION_PUBLIC: &str = "1.0.0";
|
||||||
|
|
||||||
pub static USER_AGENT: &str = concat!(types::brand!(), "/1.0.0");
|
pub static USER_AGENT: &str = "Stalwart/1.0.0";
|
||||||
pub static DAEMON_NAME: &str = concat!(types::brand!(), " v", types::brand_version!(),);
|
pub static DAEMON_NAME: &str = concat!("Stalwart v", env!("CARGO_PKG_VERSION"),);
|
||||||
pub static PROD_ID: &str = types::brand_prodid!();
|
pub static PROD_ID: &str = "-//Stalwart Labs LLC//Stalwart Server//EN";
|
||||||
|
|
||||||
/*
|
/*
|
||||||
|
|
||||||
@@ -168,9 +161,6 @@ pub struct Data {
|
|||||||
pub struct LogoCache {
|
pub struct LogoCache {
|
||||||
domain_id: u32,
|
domain_id: u32,
|
||||||
tenant_id: Option<u32>,
|
tenant_id: Option<u32>,
|
||||||
// inbuxa: read again when the /logo endpoint (per-tenant and per-domain
|
|
||||||
// branding) is rebuilt; docs/spec/features/multi-tenancy.md MT-22.
|
|
||||||
#[allow(dead_code)]
|
|
||||||
data: Option<Resource<Vec<u8>>>,
|
data: Option<Resource<Vec<u8>>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -425,10 +415,59 @@ pub struct ThrottleKeyHasher {
|
|||||||
#[derive(Clone, Default)]
|
#[derive(Clone, Default)]
|
||||||
pub struct ThrottleKeyHasherBuilder {}
|
pub struct ThrottleKeyHasherBuilder {}
|
||||||
|
|
||||||
/// The logo embedded in calendar emails when no custom logo is set: INBUXA's
|
pub const DEFAULT_LOGO_BASE64: &str = "iVBORw0KGgoAAAANSUhEUgAAAMgAAAAnCAMAAAB9lPf7AAABOFBMVEUAAAAAADoAAEkPDkIPDkIQ\r\n\
|
||||||
/// compact lockup at 380x80, twice its 180-pixel display width. Base64 with
|
DkIQDkLcLVTYMVTbLVTbLVQPDkLWM2YQDkIPD0IODEHaJlPbLVQWDT8MC0IQDkIQDkIPDkIODkEQ\r\n\
|
||||||
/// CRLF line breaks, ready for a base64 MIME part.
|
D0ITDEAQDkIPDkIODkIPDkIPDkIRDUIQDkIQDUIPDkLcLVQQDkIQDkIQDkIQDULbLVQQDUIPDkIQ\r\n\
|
||||||
pub const DEFAULT_LOGO_BASE64: &str = include_str!(concat!(
|
EEIPDkIPD0EPDkHcLlUPDkLbLFQPDULbLFPbLVQQDkLbLFPcK1TbLVTbLVQQDUIPDkIPDkIPDULc\r\n\
|
||||||
env!("CARGO_MANIFEST_DIR"),
|
LVTcLVQQDkLbLFTcLFTbLFQPDkIQDkIQDULbLVUSEkPcLVTbLVQQDULbLFTcLVTbLVTbLVPbLFQP\r\n\
|
||||||
"/../../resources/branding/email-logo.png.b64"
|
DUHbLVMPDkPbLVTdLFXbLFQNDULcLVTcLlMRD0cQDkIQDkXpMFnrMFrtMFvlL1jjLlfdLVThLlYS\r\n\
|
||||||
));
|
EErnL1gRD0n0Ml2YjG1wAAAAWnRSTlMABAb59/379wr7/lMF9HgoBvQJF/BtZSQwGu7JNulAO95x\r\n\
|
||||||
|
WD3TsF1M3b6kH5MRiRe5saujyH9oHezk4tjGmn9fwkc1vrVqYA8N19DPqnFQkYh1V0a4LSITmSiJ\r\n\
|
||||||
|
LN30AAAKZUlEQVRYw91ZCVvbRhCVrcuWD7AxYLANtrEx5opDIBCOQBLO5qTQ0uyubyD//x/0za4O\r\n\
|
||||||
|
RIG0/dLvazu0tbTaWc3bOd6sqv2PJen9/LcF9o++fnf58r8OBcb/vNBttzvrc0Ck/VcFMN6+a/fs\r\n\
|
||||||
|
uG23+x9+fcopkUiE/ks/35ew2j8ucMCz3wbteNwZtIcZp2O/jj3mlWjo+t8nHzNdx3ac/sLrTDee\r\n\
|
||||||
|
GXRf7cMpD+OYnF9dO6zvnc/gOuLv93dBRScTkz/KWrwu+mBUfTrrwhHtod1b0J696N/E7T5S5UEo\r\n\
|
||||||
|
xbrBlIidyp90CvCO1cu56you/jFBAP1y2evZdq/z4suwv3CiaXPr7X7Gbg9fbP4xvtKccSNlGEYq\r\n\
|
||||||
|
ZQpWG3GRTM2ki49biUkjgpks8aOAZCcT6ZX7ME4+Izkyw85Pn7T9m+FCjMb2X3UHSJXM62TIKxFt\r\n\
|
||||||
|
lXHdEPAG/jUNnelFQjJVM8T1BK4e98hIiqd+DBCskcgZjE/dW+zlFiVHd+sjXfcICEnsS7wTtwfd\r\n\
|
||||||
|
hZ8DJFBsMNPirLxabSQqTSFMQ5RWyErBDTH/NBCdGz8MyPm1wUtjocXe/NQZZuLtwednMN4FkpSO\r\n\
|
||||||
|
+vqhh1Tp3bx7qwXyXuhcLLsLNHJAwvZg/6TBLRYGEoE8AOTplAqrPx6nR8wQ01N3Fht90evF4+2b\r\n\
|
||||||
|
y1+k7QEQLTkqQfbt+M3wi29NUZgWO8RSJLg1ucVTY6hj5j0geCh//pZHAvX7s+nNtOr4fSCbw0Hc\r\n\
|
||||||
|
cdbd8ElKIIESMf3AsftbSW8nJphusqqWdTMOGQNgVRdINUQvkZWrLP24Ix6Q74qn46kHEtwqIKda\r\n\
|
||||||
|
IJtbDgQ4YpoLxMk89+Xy+W/rAyc+OPOBpBki6wIX7v2s4CZblUBMXjtstgoNLYK/6PxarVQqt8Zh\r\n\
|
||||||
|
zEThEKMKSCPaah4WKporK/Vm6yCP+SqDC61ma0paW10k9SYVpirUq3Jqcw23F8tr0K8wg+sHrSbN\r\n\
|
||||||
|
l/LMadvxwfDyKyKL/vn4DQSipNdG19XtO3G7+8rf6Ap5pKJlPZ9H8/l8ccoFQrXsukIoG2Vcco6R\r\n\
|
||||||
|
UkNrXfPrI83zSA135YhXOm6hseHt8yEe1Wh4puapT89rixjdQF3kGFvKHtA7FskOeow/RbGKCG2n\r\n\
|
||||||
|
7Xw5kdG1+bzXaUvp9uIkjiRGH0iCWSafzitmDUhdATFNpP4RZm0wYRm6EFTKxHxBpMSEC6QKE1I6\r\n\
|
||||||
|
B+NItWWWMsSupmRsmudok7QjqoaGVOdsoiVS7Fw+tfhx4dpI5cSyAoL3cWPyTmvScWx0JC9din+h\r\n\
|
||||||
|
5POH+MBx4rJVCWTKgLrQV4tZt7QADWxSQCAWgCCATcsSorxbKDGMUUELgOQt/KSBltR3hMW5vuRG\r\n\
|
||||||
|
Fowz84glMJUl2PbuLtRNqOssDSA5WJ7CdeAREssDEqNmcQg+7Ldp42PJoCwPHLgq/iWG0WDrl29T\r\n\
|
||||||
|
WJzx7cONxEjUTz9KdpFeQqCNaXm80WKFGWBdmS8JHdABxE/2XWGwA68GcuBgx4CFu0WWYvDOEqw1\r\n\
|
||||||
|
We0C6qeJMtR9ILRVopmeqMxQsvPczCTeB9UACrXvGftGNu8xd6SD0PJHAokc3ILPLcoHxsuL1RUM\r\n\
|
||||||
|
uUC8klRnusXqXryUsekhIGkGnyxBi0JQJycuyiWy20JavMcMizW9TgS8FQJSfaRqPfuEFB+VB6qB\r\n\
|
||||||
|
HVfNu+sjGz3LG8DA0093XBJdRIaZOgmhKW1g0OeRLHEjDBZlTJSGSP+EgOTJdtXN7FJkmWI7S+l3\r\n\
|
||||||
|
IWBoXpvKcZ26haxSh39MH4iOZEFqRh7ikcE7UGGMjrh2x3Gb949bXVx2tl5iGI/mzohHgkI+u1gS\r\n\
|
||||||
|
sqpYhoFYLqxo0YAQI0Q1iJagQi8y/S6QCJoDg61pEQlZ7BSELmaI5pZhW0GT5QSGZz31VWZ5QHRA\r\n\
|
||||||
|
VlXCAxIJPJLpqOYEmF4M2zZS5d16Fz1Lx/l8Iod//TDsnmlhOb3YqO+kBMBYpkFxfRfIHkuJ3NSd\r\n\
|
||||||
|
7iwMJIuAMtSWTyApNiZuU2yV7N4RBhm8qlI+YKogRwwZhA8D2cygXfS3fl12JNTQ954rR8Veo3V0\r\n\
|
||||||
|
FkbvdkBu2V1qrL5HncTy46EW5RDm1QLQ8lEABFPyVPgasL3ODFacFJbYpcTnkBGNHCi2Tz0TI1R2\r\n\
|
||||||
|
fY/IaveYR7po4LuUDKNu827b6j6WdJv5+Dd4JCwemEZJwKhCCMgBgBz4M5UFodBCbKXYsqZdlbjY\r\n\
|
||||||
|
jmo1IclgA2oEqA4gO8GLqAYEQMYfBYIjleuBrzBdNu/tNjX0SSpdOF5RMcPxypVssUgFNjhrFok/\r\n\
|
||||||
|
SlfaiOUDacKiwl3qSYWBRMhmUctqDYHOmWLJYMdIfKhRaqwBSPlOr3la+nNAvENuB9wuoXzd3/dy\r\n\
|
||||||
|
BgfeTMDrpL9kCo5AjfqOgdk6zy3dBbIGM8ungQ5VqRAQFUVFmd3owWYo92kB1CwA2aMFx4LQWjL4\r\n\
|
||||||
|
nwIympSfHRS3K0dIGMnX7uA+BZ3vEbCCKAdNaJQ2kE+PBUAitMMwM+h6j8LJTuM12XXsCF46pTW5\r\n\
|
||||||
|
KMnEL+BGcrZoBMleFeb3gYS5XW1+LBaTvNIhN4V5XUWwicYp6582doCshhxxgeCv4R22ICojrDCQ\r\n\
|
||||||
|
qIymwxGhUxWKkg9EHrROqeyeeOq4UrUFLrceBxINkv1jUkv63N6TTC7v+rbP9JgUC5pGHXVqlq6j\r\n\
|
||||||
|
tEqF9mtZJrvOqpIQT7cFtfowEUJJbPH7QGaJBfdAIChiWFMYYrEMXlJFt0bq85qm1I+Y+Vho5a5k\r\n\
|
||||||
|
BCjZ7C/c5/ZRfKgL8fp+JqP5sssMU5jpK1WQVgU3qWhSJFOkS0lLsG6/soGyFgaimkWTQ6ZX5KFk\r\n\
|
||||||
|
mq5l8dMUoeLhsVI/4vxBIJjExXHoYNXuXXqUobh94VWY19fbnbNk0K8bwtA5m24try63cozrqrhH\r\n\
|
||||||
|
y7SP7+v11h7CDWC5aI03EukaQ3m4D4RYXPaCa3QXkXkWkIR2INUPKonEeUFA/SEgM7Q/VrNeb07g\r\n\
|
||||||
|
joDEbfrwcBJwu90P83q/ZzuvRoMzbDHHcFjgjISncIHAIj6/zYFRmLgFM0xOM90wGROMERuDskNA\r\n\
|
||||||
|
lB2cYlG1vccEhCIroihwG+oW1AWDZr0mjHtAVIeZMjm19Mtq6GSBPgXJ7deSHrcrXh9VTsInoW/v\r\n\
|
||||||
|
7n7AWGoJOjfRNzpYnhpXWzRVuuVwj8Fr5Lb3DCwH0QXbI4aUQAw/tKQDLaqyEBmXpi4K/hvGcAz0\r\n\
|
||||||
|
1NdQX1J+izLu15AqY1DSU2LVHXr22ekPB+1vZ59wI7m815M8j7uXW996g2Evg5Y4EKhdrJWE8sjO\r\n\
|
||||||
|
xpRf79emucAmluWU8RqXE94nNDqr3tJRlwt+W/WOhtecX9e9NZu3uEsH3KEdF6S62DnWaOo1AdGh\r\n\
|
||||||
|
XgnqVKNg4H3c8wjk69zc3Nu3b+ZG3c+Oc3SVJG+9efP2LR5u/vFDxkqxOn5+lMhTwPujK/nZ2dmZ\r\n\
|
||||||
|
vDslX61U5vMS4szsDPY+S0+vvL7lAoNeZ4kZeHQaesNIYvz8uCg7AzUzWpwNNJRWkVZceur/vSUf\r\n\
|
||||||
|
GAtDCZrI0KAvoeG/Lt9Xx5MfIhFiicj9QSmhGd649zg098nPik+rB+/T/k/yO9A7bEvKcQkCAAAA\r\n\
|
||||||
|
AElFTkSuQmCC";
|
||||||
|
|||||||
@@ -11,8 +11,11 @@ use registry::schema::{enums::CompressionAlgo, structs::Application};
|
|||||||
use std::{
|
use std::{
|
||||||
borrow::Cow,
|
borrow::Cow,
|
||||||
io::{self, Cursor, Read},
|
io::{self, Cursor, Read},
|
||||||
path::PathBuf,
|
path::{Path, PathBuf},
|
||||||
sync::Arc,
|
sync::{
|
||||||
|
Arc,
|
||||||
|
atomic::{AtomicU64, Ordering},
|
||||||
|
},
|
||||||
time::Duration,
|
time::Duration,
|
||||||
};
|
};
|
||||||
use store::{
|
use store::{
|
||||||
@@ -36,16 +39,18 @@ enum IndexEdit<'x> {
|
|||||||
pub struct WebApplications {
|
pub struct WebApplications {
|
||||||
applications: ArcSwap<Vec<WebApplicationManager>>,
|
applications: ArcSwap<Vec<WebApplicationManager>>,
|
||||||
routes: ArcSwap<AHashMap<String, Arc<AppRoutes>>>,
|
routes: ArcSwap<AHashMap<String, Arc<AppRoutes>>>,
|
||||||
|
generation: AtomicU64,
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct AppRoutes {
|
pub struct AppRoutes {
|
||||||
resources: AHashMap<String, Resource<PathBuf>>,
|
resources: AHashMap<String, Resource<PathBuf>>,
|
||||||
oauth_client_id_meta: Option<String>,
|
oauth_client_id_meta: Option<String>,
|
||||||
|
_bundle_dir: TempDir,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct WebApplicationManager {
|
pub struct WebApplicationManager {
|
||||||
bundle_path: TempDir,
|
base_path: PathBuf,
|
||||||
prefixes: Vec<String>,
|
prefixes: Vec<String>,
|
||||||
description: String,
|
description: String,
|
||||||
url: String,
|
url: String,
|
||||||
@@ -79,6 +84,7 @@ impl WebApplications {
|
|||||||
Self {
|
Self {
|
||||||
applications: ArcSwap::new(Arc::new(Vec::new())),
|
applications: ArcSwap::new(Arc::new(Vec::new())),
|
||||||
routes: ArcSwap::new(Arc::new(AHashMap::new())),
|
routes: ArcSwap::new(Arc::new(AHashMap::new())),
|
||||||
|
generation: AtomicU64::new(0),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -128,48 +134,55 @@ impl WebApplications {
|
|||||||
}
|
}
|
||||||
|
|
||||||
pub async fn unpack_all(&self, server: &Server, update: bool) {
|
pub async fn unpack_all(&self, server: &Server, update: bool) {
|
||||||
let mut routes = AHashMap::new();
|
let previous = self.routes.load_full();
|
||||||
|
let sweep_orphans = previous.is_empty();
|
||||||
|
let mut routes = AHashMap::with_capacity(previous.len());
|
||||||
|
|
||||||
for app in self.applications.load().as_ref() {
|
for app in self.applications.load().as_ref() {
|
||||||
if update && let Err(err) = app.delete(server).await {
|
match app
|
||||||
trc::event!(
|
.unpack(server, self.next_generation(), update, sweep_orphans)
|
||||||
Resource(trc::ResourceEvent::Error),
|
.await
|
||||||
Reason = err,
|
{
|
||||||
Url = app.url.clone(),
|
Ok(app_routes) => {
|
||||||
Details = format!(
|
let app_routes = Arc::new(app_routes);
|
||||||
"Failed to delete application bundle for prefixes: {}",
|
|
||||||
app.prefixes.join(", ")
|
|
||||||
)
|
|
||||||
);
|
|
||||||
}
|
|
||||||
match app.unpack(server).await {
|
|
||||||
Ok(resources) => {
|
|
||||||
let app_routes = Arc::new(AppRoutes {
|
|
||||||
resources,
|
|
||||||
oauth_client_id_meta: app
|
|
||||||
.oauth_client_id
|
|
||||||
.as_deref()
|
|
||||||
.map(oauth_client_id_meta),
|
|
||||||
});
|
|
||||||
|
|
||||||
for prefix in &app.prefixes {
|
for prefix in &app.prefixes {
|
||||||
routes.insert(prefix.clone(), app_routes.clone());
|
routes.insert(prefix.clone(), app_routes.clone());
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
|
let mut is_retained = false;
|
||||||
|
for prefix in &app.prefixes {
|
||||||
|
if let Some(app_routes) = previous.get(prefix) {
|
||||||
|
routes.insert(prefix.clone(), app_routes.clone());
|
||||||
|
is_retained = true;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
trc::event!(
|
trc::event!(
|
||||||
Resource(trc::ResourceEvent::Error),
|
Resource(trc::ResourceEvent::Error),
|
||||||
Reason = err,
|
Reason = err,
|
||||||
Url = app.url.clone(),
|
Url = app.url.clone(),
|
||||||
Details = format!(
|
Details = format!(
|
||||||
"Failed to unpack application for prefixes: {}",
|
"Failed to unpack application for prefixes: {}, {}",
|
||||||
app.prefixes.join(", ")
|
app.prefixes.join(", "),
|
||||||
|
if is_retained {
|
||||||
|
"the previously unpacked bundle remains in service"
|
||||||
|
} else {
|
||||||
|
"no bundle is available to serve"
|
||||||
|
}
|
||||||
)
|
)
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
self.routes.store(Arc::new(routes));
|
self.routes.store(Arc::new(routes));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn next_generation(&self) -> u64 {
|
||||||
|
self.generation.fetch_add(1, Ordering::Relaxed)
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl WebApplicationManager {
|
impl WebApplicationManager {
|
||||||
@@ -182,7 +195,7 @@ impl WebApplicationManager {
|
|||||||
.join(app.id.id().to_string());
|
.join(app.id.id().to_string());
|
||||||
|
|
||||||
Self {
|
Self {
|
||||||
bundle_path: TempDir::new(base_path),
|
base_path,
|
||||||
blob_key: BlobHash::generate(format!("{}{}", APP_BLOB_PREFIX, app.id.id()).as_bytes()),
|
blob_key: BlobHash::generate(format!("{}{}", APP_BLOB_PREFIX, app.id.id()).as_bytes()),
|
||||||
url: app.object.resource_url,
|
url: app.object.resource_url,
|
||||||
description: app.object.description,
|
description: app.object.description,
|
||||||
@@ -202,82 +215,43 @@ impl WebApplicationManager {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn unpack(&self, server: &Server) -> trc::Result<AHashMap<String, Resource<PathBuf>>> {
|
async fn unpack(
|
||||||
// Delete any existing bundles
|
&self,
|
||||||
self.bundle_path.clean().await.map_err(unpack_error)?;
|
server: &Server,
|
||||||
|
generation: u64,
|
||||||
// Obtain application bundle
|
force_refresh: bool,
|
||||||
let bundle = if let Some(bundle) = server
|
sweep_orphans: bool,
|
||||||
.blob_store()
|
) -> trc::Result<AppRoutes> {
|
||||||
.get_blob(self.blob_key.as_slice(), 0..usize::MAX)
|
let cached = if force_refresh {
|
||||||
.await?
|
None
|
||||||
{
|
|
||||||
bundle
|
|
||||||
} else {
|
} else {
|
||||||
// Fetch app bundle
|
|
||||||
let resource = fetch_resource(&self.url, None, Duration::from_secs(60), MAX_APP_SIZE)
|
|
||||||
.await
|
|
||||||
.map_err(|err| {
|
|
||||||
trc::ResourceEvent::Error
|
|
||||||
.caused_by(trc::location!())
|
|
||||||
.ctx(Key::Url, self.url.clone())
|
|
||||||
.reason(err)
|
|
||||||
.details("Failed to fetch application bundle")
|
|
||||||
})?;
|
|
||||||
|
|
||||||
// Store in blob store for future use
|
|
||||||
server
|
server
|
||||||
.blob_store()
|
.blob_store()
|
||||||
.put_blob(self.blob_key.as_slice(), &resource, CompressionAlgo::None)
|
.get_blob(self.blob_key.as_slice(), 0..usize::MAX)
|
||||||
.await
|
.await?
|
||||||
.caused_by(trc::location!())?;
|
};
|
||||||
|
let is_cached = cached.is_some();
|
||||||
// Schedule expiration
|
let bundle = match cached {
|
||||||
let mut batch = BatchBuilder::new();
|
Some(bundle) => bundle,
|
||||||
batch
|
None => self.fetch().await?,
|
||||||
.set(
|
|
||||||
BlobOp::Link {
|
|
||||||
hash: self.blob_key.clone(),
|
|
||||||
to: BlobLink::Temporary {
|
|
||||||
until: now() + self.expiry,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
vec![],
|
|
||||||
)
|
|
||||||
.set(
|
|
||||||
BlobOp::Commit {
|
|
||||||
hash: self.blob_key.clone(),
|
|
||||||
},
|
|
||||||
Vec::new(),
|
|
||||||
);
|
|
||||||
server
|
|
||||||
.store()
|
|
||||||
.write(batch.build_all())
|
|
||||||
.await
|
|
||||||
.caused_by(trc::location!())?;
|
|
||||||
|
|
||||||
trc::event!(
|
|
||||||
Resource(trc::ResourceEvent::ApplicationUpdated),
|
|
||||||
Url = self.url.clone(),
|
|
||||||
Details = self.description.clone(),
|
|
||||||
);
|
|
||||||
|
|
||||||
resource
|
|
||||||
};
|
};
|
||||||
|
|
||||||
|
let staging = TempDir::new(self.base_path.join(format!("{:x}-{generation:x}", now())));
|
||||||
|
staging.create().await.map_err(unpack_error)?;
|
||||||
|
|
||||||
let url = self.url.clone();
|
let url = self.url.clone();
|
||||||
let bundle_path = self.bundle_path.path.clone();
|
let bundle_path = staging.path.clone();
|
||||||
let routes = tokio::task::spawn_blocking(move || -> trc::Result<_> {
|
let (resources, bundle) = tokio::task::spawn_blocking(move || -> trc::Result<_> {
|
||||||
let mut bundle = zip::ZipArchive::new(Cursor::new(bundle)).map_err(|err| {
|
let mut archive = zip::ZipArchive::new(Cursor::new(bundle)).map_err(|err| {
|
||||||
trc::ResourceEvent::Error
|
trc::ResourceEvent::Error
|
||||||
.caused_by(trc::location!())
|
.caused_by(trc::location!())
|
||||||
.reason(err)
|
.reason(err)
|
||||||
.ctx(Key::Url, url.clone())
|
.ctx(Key::Url, url.clone())
|
||||||
.details("Failed to decompress application bundle")
|
.details("Failed to decompress application bundle")
|
||||||
})?;
|
})?;
|
||||||
let mut routes = AHashMap::new();
|
let mut resources = AHashMap::with_capacity(archive.len());
|
||||||
for i in 0..bundle.len() {
|
for i in 0..archive.len() {
|
||||||
let mut file = bundle.by_index(i).map_err(|err| {
|
let mut file = archive.by_index(i).map_err(|err| {
|
||||||
trc::ResourceEvent::Error
|
trc::ResourceEvent::Error
|
||||||
.caused_by(trc::location!())
|
.caused_by(trc::location!())
|
||||||
.reason(err)
|
.reason(err)
|
||||||
@@ -315,9 +289,9 @@ impl WebApplicationManager {
|
|||||||
contents: path,
|
contents: path,
|
||||||
};
|
};
|
||||||
|
|
||||||
routes.insert(file_name, resource);
|
resources.insert(file_name, resource);
|
||||||
}
|
}
|
||||||
Ok(routes)
|
Ok((resources, archive.into_inner().into_inner()))
|
||||||
})
|
})
|
||||||
.await
|
.await
|
||||||
.map_err(|err| {
|
.map_err(|err| {
|
||||||
@@ -327,21 +301,81 @@ impl WebApplicationManager {
|
|||||||
.details("Bundle unpack task panicked")
|
.details("Bundle unpack task panicked")
|
||||||
})??;
|
})??;
|
||||||
|
|
||||||
|
if !is_cached && let Err(err) = self.cache(server, &bundle).await {
|
||||||
|
trc::event!(
|
||||||
|
Resource(trc::ResourceEvent::Error),
|
||||||
|
Reason = err,
|
||||||
|
Url = self.url.clone(),
|
||||||
|
Details = "Failed to cache application bundle, it will be downloaded again"
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if sweep_orphans {
|
||||||
|
remove_siblings(&self.base_path, &staging.path).await;
|
||||||
|
}
|
||||||
|
|
||||||
trc::event!(
|
trc::event!(
|
||||||
Resource(trc::ResourceEvent::ApplicationUnpacked),
|
Resource(trc::ResourceEvent::ApplicationUnpacked),
|
||||||
Url = self.url.clone(),
|
Url = self.url.clone(),
|
||||||
Path = self.bundle_path.path.to_string_lossy().into_owned(),
|
Path = staging.path.to_string_lossy().into_owned(),
|
||||||
);
|
);
|
||||||
|
|
||||||
Ok(routes)
|
Ok(AppRoutes {
|
||||||
|
resources,
|
||||||
|
oauth_client_id_meta: self.oauth_client_id.as_deref().map(oauth_client_id_meta),
|
||||||
|
_bundle_dir: staging,
|
||||||
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn delete(&self, server: &Server) -> trc::Result<()> {
|
async fn fetch(&self) -> trc::Result<Vec<u8>> {
|
||||||
|
fetch_resource(&self.url, None, Duration::from_secs(60), MAX_APP_SIZE)
|
||||||
|
.await
|
||||||
|
.map_err(|err| {
|
||||||
|
trc::ResourceEvent::Error
|
||||||
|
.caused_by(trc::location!())
|
||||||
|
.ctx(Key::Url, self.url.clone())
|
||||||
|
.reason(err)
|
||||||
|
.details("Failed to fetch application bundle")
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn cache(&self, server: &Server, bundle: &[u8]) -> trc::Result<()> {
|
||||||
server
|
server
|
||||||
.blob_store()
|
.blob_store()
|
||||||
.delete_blob(self.blob_key.as_slice())
|
.put_blob(self.blob_key.as_slice(), bundle, CompressionAlgo::None)
|
||||||
.await
|
.await
|
||||||
.map(|_| ())
|
.caused_by(trc::location!())?;
|
||||||
|
|
||||||
|
let mut batch = BatchBuilder::new();
|
||||||
|
batch
|
||||||
|
.set(
|
||||||
|
BlobOp::Link {
|
||||||
|
hash: self.blob_key.clone(),
|
||||||
|
to: BlobLink::Temporary {
|
||||||
|
until: now() + self.expiry,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
vec![],
|
||||||
|
)
|
||||||
|
.set(
|
||||||
|
BlobOp::Commit {
|
||||||
|
hash: self.blob_key.clone(),
|
||||||
|
},
|
||||||
|
Vec::new(),
|
||||||
|
);
|
||||||
|
server
|
||||||
|
.store()
|
||||||
|
.write(batch.build_all())
|
||||||
|
.await
|
||||||
|
.caused_by(trc::location!())?;
|
||||||
|
|
||||||
|
trc::event!(
|
||||||
|
Resource(trc::ResourceEvent::ApplicationUpdated),
|
||||||
|
Url = self.url.clone(),
|
||||||
|
Details = self.description.clone(),
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn delete_bundle(server: &Server, app_id: Id) -> trc::Result<()> {
|
pub async fn delete_bundle(server: &Server, app_id: Id) -> trc::Result<()> {
|
||||||
@@ -361,7 +395,6 @@ impl Resource<Vec<u8>> {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct TempDir {
|
pub struct TempDir {
|
||||||
pub path: PathBuf,
|
pub path: PathBuf,
|
||||||
}
|
}
|
||||||
@@ -371,11 +404,36 @@ impl TempDir {
|
|||||||
TempDir { path }
|
TempDir { path }
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn clean(&self) -> io::Result<()> {
|
pub async fn create(&self) -> io::Result<()> {
|
||||||
if tokio::fs::metadata(&self.path).await.is_ok() {
|
if tokio::fs::metadata(&self.path).await.is_ok() {
|
||||||
let _ = tokio::fs::remove_dir_all(&self.path).await;
|
let _ = tokio::fs::remove_dir_all(&self.path).await;
|
||||||
}
|
}
|
||||||
tokio::fs::create_dir(&self.path).await
|
tokio::fs::create_dir_all(&self.path).await
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Drop for TempDir {
|
||||||
|
fn drop(&mut self) {
|
||||||
|
let _ = std::fs::remove_dir_all(&self.path);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn remove_siblings(base_path: &Path, keep: &Path) {
|
||||||
|
let Ok(mut entries) = tokio::fs::read_dir(base_path).await else {
|
||||||
|
return;
|
||||||
|
};
|
||||||
|
|
||||||
|
while let Ok(Some(entry)) = entries.next_entry().await {
|
||||||
|
let path = entry.path();
|
||||||
|
if path == keep {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
|
||||||
|
if matches!(entry.file_type().await, Ok(file_type) if file_type.is_dir()) {
|
||||||
|
let _ = tokio::fs::remove_dir_all(&path).await;
|
||||||
|
} else {
|
||||||
|
let _ = tokio::fs::remove_file(&path).await;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -385,12 +443,6 @@ fn unpack_error(err: std::io::Error) -> trc::Error {
|
|||||||
.details("Failed to unpack application bundle")
|
.details("Failed to unpack application bundle")
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Drop for TempDir {
|
|
||||||
fn drop(&mut self) {
|
|
||||||
let _ = std::fs::remove_dir_all(&self.path);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Default for WebApplications {
|
impl Default for WebApplications {
|
||||||
fn default() -> Self {
|
fn default() -> Self {
|
||||||
Self::new()
|
Self::new()
|
||||||
@@ -521,9 +573,9 @@ mod tests {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn fixture(name: &str, client_id: Option<&str>) -> (WebApplications, TempDir) {
|
async fn fixture(name: &str, client_id: Option<&str>) -> WebApplications {
|
||||||
let dir = TempDir::new(std::env::temp_dir().join(format!("stalwart-app-{name}")));
|
let dir = TempDir::new(std::env::temp_dir().join(format!("stalwart-app-{name}")));
|
||||||
dir.clean().await.unwrap();
|
dir.create().await.unwrap();
|
||||||
tokio::fs::write(dir.path.join("index.html"), INDEX)
|
tokio::fs::write(dir.path.join("index.html"), INDEX)
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
@@ -544,6 +596,7 @@ mod tests {
|
|||||||
let routes = Arc::new(AppRoutes {
|
let routes = Arc::new(AppRoutes {
|
||||||
resources,
|
resources,
|
||||||
oauth_client_id_meta: client_id.map(oauth_client_id_meta),
|
oauth_client_id_meta: client_id.map(oauth_client_id_meta),
|
||||||
|
_bundle_dir: dir,
|
||||||
});
|
});
|
||||||
|
|
||||||
let mut map = AHashMap::new();
|
let mut map = AHashMap::new();
|
||||||
@@ -553,7 +606,7 @@ mod tests {
|
|||||||
let apps = WebApplications::new();
|
let apps = WebApplications::new();
|
||||||
apps.routes.store(Arc::new(map));
|
apps.routes.store(Arc::new(map));
|
||||||
|
|
||||||
(apps, dir)
|
apps
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn serve_html(apps: &WebApplications, prefix: &str, path: &str) -> String {
|
async fn serve_html(apps: &WebApplications, prefix: &str, path: &str) -> String {
|
||||||
@@ -565,7 +618,7 @@ mod tests {
|
|||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn serving_index_injects_the_prefix_and_client_id() {
|
async fn serving_index_injects_the_prefix_and_client_id() {
|
||||||
let (apps, _dir) = fixture("serve-configured", Some("pocket-id-client")).await;
|
let apps = fixture("serve-configured", Some("pocket-id-client")).await;
|
||||||
|
|
||||||
let html = serve_html(&apps, "admin", "index.html").await;
|
let html = serve_html(&apps, "admin", "index.html").await;
|
||||||
assert!(html.contains("<base href=\"/admin/\" />"), "{html}");
|
assert!(html.contains("<base href=\"/admin/\" />"), "{html}");
|
||||||
@@ -584,7 +637,7 @@ mod tests {
|
|||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn unknown_paths_fall_back_to_a_rewritten_index() {
|
async fn unknown_paths_fall_back_to_a_rewritten_index() {
|
||||||
let (apps, _dir) = fixture("serve-fallback", Some("pocket-id-client")).await;
|
let apps = fixture("serve-fallback", Some("pocket-id-client")).await;
|
||||||
|
|
||||||
let html = serve_html(&apps, "admin", "settings/directory").await;
|
let html = serve_html(&apps, "admin", "settings/directory").await;
|
||||||
assert!(html.contains("<base href=\"/admin/\" />"), "{html}");
|
assert!(html.contains("<base href=\"/admin/\" />"), "{html}");
|
||||||
@@ -596,7 +649,7 @@ mod tests {
|
|||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn assets_and_unknown_prefixes_are_untouched() {
|
async fn assets_and_unknown_prefixes_are_untouched() {
|
||||||
let (apps, _dir) = fixture("serve-assets", Some("pocket-id-client")).await;
|
let apps = fixture("serve-assets", Some("pocket-id-client")).await;
|
||||||
|
|
||||||
let served = apps.serve("admin", "app.js").await.unwrap().unwrap();
|
let served = apps.serve("admin", "app.js").await.unwrap().unwrap();
|
||||||
assert_eq!(served.resource.contents, b"export const x = 1;\n");
|
assert_eq!(served.resource.contents, b"export const x = 1;\n");
|
||||||
@@ -608,7 +661,7 @@ mod tests {
|
|||||||
|
|
||||||
#[tokio::test]
|
#[tokio::test]
|
||||||
async fn serving_index_without_a_client_id_keeps_the_placeholder() {
|
async fn serving_index_without_a_client_id_keeps_the_placeholder() {
|
||||||
let (apps, _dir) = fixture("serve-unconfigured", None).await;
|
let apps = fixture("serve-unconfigured", None).await;
|
||||||
|
|
||||||
let html = serve_html(&apps, "admin", "index.html").await;
|
let html = serve_html(&apps, "admin", "index.html").await;
|
||||||
assert!(html.contains("<base href=\"/admin/\" />"), "{html}");
|
assert!(html.contains("<base href=\"/admin/\" />"), "{html}");
|
||||||
@@ -624,4 +677,65 @@ mod tests {
|
|||||||
|
|
||||||
assert_eq!(rewrite_index(bundle, "admin", None), bundle.as_bytes());
|
assert_eq!(rewrite_index(bundle, "admin", None), bundle.as_bytes());
|
||||||
}
|
}
|
||||||
|
#[tokio::test]
|
||||||
|
async fn missing_parent_directories_are_created() {
|
||||||
|
let base = std::env::temp_dir().join("stalwart-app-nested");
|
||||||
|
let _ = tokio::fs::remove_dir_all(&base).await;
|
||||||
|
|
||||||
|
let dir = TempDir::new(base.join("webui").join("0"));
|
||||||
|
dir.create().await.unwrap();
|
||||||
|
|
||||||
|
assert!(tokio::fs::metadata(&dir.path).await.is_ok());
|
||||||
|
|
||||||
|
drop(dir);
|
||||||
|
let _ = tokio::fs::remove_dir_all(&base).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn dropping_the_routes_removes_the_bundle_directory() {
|
||||||
|
let apps = fixture("drop-guard", None).await;
|
||||||
|
let path = apps
|
||||||
|
.routes
|
||||||
|
.load()
|
||||||
|
.get("admin")
|
||||||
|
.unwrap()
|
||||||
|
._bundle_dir
|
||||||
|
.path
|
||||||
|
.clone();
|
||||||
|
|
||||||
|
assert!(tokio::fs::metadata(&path).await.is_ok());
|
||||||
|
|
||||||
|
apps.routes.store(Arc::new(AHashMap::new()));
|
||||||
|
|
||||||
|
assert!(tokio::fs::metadata(&path).await.is_err());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[tokio::test]
|
||||||
|
async fn sweeping_orphans_spares_the_current_generation() {
|
||||||
|
let base = std::env::temp_dir().join("stalwart-app-sweep");
|
||||||
|
let _ = tokio::fs::remove_dir_all(&base).await;
|
||||||
|
|
||||||
|
let current = TempDir::new(base.join("1"));
|
||||||
|
current.create().await.unwrap();
|
||||||
|
let orphan = base.join("0");
|
||||||
|
tokio::fs::create_dir_all(&orphan).await.unwrap();
|
||||||
|
let stray = base.join("webui.zip");
|
||||||
|
tokio::fs::write(&stray, b"not a bundle").await.unwrap();
|
||||||
|
|
||||||
|
remove_siblings(&base, ¤t.path).await;
|
||||||
|
|
||||||
|
assert!(tokio::fs::metadata(¤t.path).await.is_ok());
|
||||||
|
assert!(tokio::fs::metadata(&orphan).await.is_err());
|
||||||
|
assert!(tokio::fs::metadata(&stray).await.is_err());
|
||||||
|
|
||||||
|
drop(current);
|
||||||
|
let _ = tokio::fs::remove_dir_all(&base).await;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn generations_never_repeat() {
|
||||||
|
let apps = WebApplications::new();
|
||||||
|
|
||||||
|
assert_ne!(apps.next_generation(), apps.next_generation());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::Core;
|
use crate::Core;
|
||||||
@@ -323,7 +321,6 @@ impl Family {
|
|||||||
SUBSPACE_REGISTRY_IDX,
|
SUBSPACE_REGISTRY_IDX,
|
||||||
SUBSPACE_REGISTRY_PK,
|
SUBSPACE_REGISTRY_PK,
|
||||||
SUBSPACE_DIRECTORY,
|
SUBSPACE_DIRECTORY,
|
||||||
store::SUBSPACE_INBUXA, // inbuxa: masked email
|
|
||||||
],
|
],
|
||||||
Family::Changelog => &[SUBSPACE_LOGS],
|
Family::Changelog => &[SUBSPACE_LOGS],
|
||||||
Family::Queue => &[SUBSPACE_QUEUE_MESSAGE, SUBSPACE_QUEUE_EVENT],
|
Family::Queue => &[SUBSPACE_QUEUE_MESSAGE, SUBSPACE_QUEUE_EVENT],
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use super::{backup::BackupParams, console::store_console};
|
use super::{backup::BackupParams, console::store_console};
|
||||||
@@ -40,12 +38,11 @@ pub struct IpcReceivers {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const HELP: &str = concat!(
|
const HELP: &str = concat!(
|
||||||
types::brand_server!(),
|
"Stalwart Server v",
|
||||||
" ",
|
env!("CARGO_PKG_VERSION"),
|
||||||
types::brand_version_full!(),
|
|
||||||
r#"
|
r#"
|
||||||
|
|
||||||
Usage: inbuxa [OPTIONS]
|
Usage: stalwart [OPTIONS]
|
||||||
|
|
||||||
Options:
|
Options:
|
||||||
-c, --config <PATH> Start server with the specified configuration file
|
-c, --config <PATH> Start server with the specified configuration file
|
||||||
@@ -90,7 +87,7 @@ impl BootManager {
|
|||||||
std::process::exit(0);
|
std::process::exit(0);
|
||||||
}
|
}
|
||||||
("version" | "V", _) => {
|
("version" | "V", _) => {
|
||||||
println!("{}", types::brand_version_full!());
|
println!("{}", env!("CARGO_PKG_VERSION"));
|
||||||
std::process::exit(0);
|
std::process::exit(0);
|
||||||
}
|
}
|
||||||
("config" | "c", Some(value)) => {
|
("config" | "c", Some(value)) => {
|
||||||
@@ -159,7 +156,8 @@ impl BootManager {
|
|||||||
// Enable telemetry
|
// Enable telemetry
|
||||||
|
|
||||||
|
|
||||||
telemetry.enable();
|
#[cfg(not(feature = "enterprise"))]
|
||||||
|
telemetry.enable(false);
|
||||||
|
|
||||||
if bootstrap.registry.is_bootstrap_mode() {
|
if bootstrap.registry.is_bootstrap_mode() {
|
||||||
trc::event!(
|
trc::event!(
|
||||||
@@ -167,20 +165,20 @@ impl BootManager {
|
|||||||
Hostname = bootstrap.registry.local_hostname().to_string(),
|
Hostname = bootstrap.registry.local_hostname().to_string(),
|
||||||
Details =
|
Details =
|
||||||
"No configuration file was found. Port 8080 is open for initial setup.",
|
"No configuration file was found. Port 8080 is open for initial setup.",
|
||||||
Version = types::brand_version_full!(),
|
Version = env!("CARGO_PKG_VERSION"),
|
||||||
);
|
);
|
||||||
} else if bootstrap.registry.is_recovery_mode() {
|
} else if bootstrap.registry.is_recovery_mode() {
|
||||||
trc::event!(
|
trc::event!(
|
||||||
Server(trc::ServerEvent::RecoveryMode),
|
Server(trc::ServerEvent::RecoveryMode),
|
||||||
Details = "Port 8080 is open for troubleshooting and recovery.",
|
Details = "Port 8080 is open for troubleshooting and recovery.",
|
||||||
Hostname = bootstrap.registry.local_hostname().to_string(),
|
Hostname = bootstrap.registry.local_hostname().to_string(),
|
||||||
Version = types::brand_version_full!(),
|
Version = env!("CARGO_PKG_VERSION"),
|
||||||
);
|
);
|
||||||
} else {
|
} else {
|
||||||
trc::event!(
|
trc::event!(
|
||||||
Server(trc::ServerEvent::Startup),
|
Server(trc::ServerEvent::Startup),
|
||||||
Hostname = bootstrap.registry.local_hostname().to_string(),
|
Hostname = bootstrap.registry.local_hostname().to_string(),
|
||||||
Version = types::brand_version_full!(),
|
Version = env!("CARGO_PKG_VERSION"),
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -242,7 +240,7 @@ impl BootManager {
|
|||||||
}
|
}
|
||||||
StoreOp::Export(path) => {
|
StoreOp::Export(path) => {
|
||||||
// Enable telemetry
|
// Enable telemetry
|
||||||
telemetry.enable();
|
telemetry.enable(false);
|
||||||
|
|
||||||
// Parse settings and backup
|
// Parse settings and backup
|
||||||
Box::pin(Core::parse(&mut bootstrap, storage))
|
Box::pin(Core::parse(&mut bootstrap, storage))
|
||||||
@@ -253,7 +251,7 @@ impl BootManager {
|
|||||||
}
|
}
|
||||||
StoreOp::Import(path) => {
|
StoreOp::Import(path) => {
|
||||||
// Enable telemetry
|
// Enable telemetry
|
||||||
telemetry.enable();
|
telemetry.enable(false);
|
||||||
|
|
||||||
// Parse settings and restore
|
// Parse settings and restore
|
||||||
Box::pin(Core::parse(&mut bootstrap, storage))
|
Box::pin(Core::parse(&mut bootstrap, storage))
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use base64::Engine;
|
use base64::Engine;
|
||||||
@@ -14,9 +12,8 @@ use store::write::{AnyClass, AnyKey, BatchBuilder, ValueClass};
|
|||||||
use store::{Deserialize, IterateParams, SUBSPACE_INDEXES, SUBSPACE_REGISTRY_IDX, Store};
|
use store::{Deserialize, IterateParams, SUBSPACE_INDEXES, SUBSPACE_REGISTRY_IDX, Store};
|
||||||
|
|
||||||
const HELP: &str = concat!(
|
const HELP: &str = concat!(
|
||||||
types::brand_server!(),
|
"Stalwart Server v",
|
||||||
" ",
|
env!("CARGO_PKG_VERSION"),
|
||||||
types::brand_version_full!(),
|
|
||||||
r#" Data Store CLI
|
r#" Data Store CLI
|
||||||
|
|
||||||
Enter commands (type 'help' for available commands).
|
Enter commands (type 'help' for available commands).
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::auth::permissions::DefaultPermissions;
|
use crate::auth::permissions::DefaultPermissions;
|
||||||
@@ -56,10 +54,28 @@ async fn insert_safe_defaults(bp: &mut Bootstrap) -> trc::Result<()> {
|
|||||||
let is_recovery_mode = bp.registry.is_recovery_mode();
|
let is_recovery_mode = bp.registry.is_recovery_mode();
|
||||||
let is_bootstrap_mode = bp.registry.is_bootstrap_mode();
|
let is_bootstrap_mode = bp.registry.is_bootstrap_mode();
|
||||||
|
|
||||||
// inbuxa: no web interface is installed on the mail host, and nothing is
|
#[cfg(not(feature = "test_mode"))]
|
||||||
// downloaded for one (docs/spec/SPEC.md §5.3). Administration is INBUXA
|
if bp.registry.count_object(ObjectType::Application).await? == 0 {
|
||||||
// Admin and webmail is ihasmail, both deployed separately. An install
|
bp.registry
|
||||||
// upgraded from Stalwart keeps any web application it already has.
|
.write(RegistryWrite::insert(
|
||||||
|
&Application {
|
||||||
|
auto_update_frequency: Duration::from_millis(30 * 24 * 60 * 60 * 1000),
|
||||||
|
description: "Stalwart Web Interface".to_string(),
|
||||||
|
enabled: true,
|
||||||
|
#[cfg(not(feature = "dev_mode"))]
|
||||||
|
resource_url:
|
||||||
|
"https://github.com/stalwartlabs/webui/releases/latest/download/webui.zip"
|
||||||
|
.into(),
|
||||||
|
#[cfg(feature = "dev_mode")]
|
||||||
|
resource_url: "file:///Users/me/code/webui/.ignore/webui.zip".into(),
|
||||||
|
unpack_directory: None,
|
||||||
|
oauth_client_id: None,
|
||||||
|
url_prefix: Map::new(vec!["/admin".into(), "/account".into()]),
|
||||||
|
}
|
||||||
|
.into(),
|
||||||
|
))
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
|
||||||
if is_bootstrap_mode {
|
if is_bootstrap_mode {
|
||||||
#[cfg(not(any(feature = "dev_mode", feature = "test_mode")))]
|
#[cfg(not(any(feature = "dev_mode", feature = "test_mode")))]
|
||||||
@@ -82,10 +98,6 @@ async fn insert_safe_defaults(bp: &mut Bootstrap) -> trc::Result<()> {
|
|||||||
return Ok(());
|
return Ok(());
|
||||||
}
|
}
|
||||||
|
|
||||||
// inbuxa: registration is required (contract C-5), so the first-party
|
|
||||||
// front ends are registered on every start (C-6)
|
|
||||||
super::first_party::ensure_first_party_clients(bp).await?;
|
|
||||||
|
|
||||||
if bp.registry.count_object(ObjectType::MtaQueueQuota).await? == 0 {
|
if bp.registry.count_object(ObjectType::MtaQueueQuota).await? == 0 {
|
||||||
bp.registry
|
bp.registry
|
||||||
.write(RegistryWrite::insert(
|
.write(RegistryWrite::insert(
|
||||||
@@ -515,9 +527,9 @@ async fn insert_safe_defaults(bp: &mut Bootstrap) -> trc::Result<()> {
|
|||||||
&Tracer::Log(TracerLog {
|
&Tracer::Log(TracerLog {
|
||||||
enable: true,
|
enable: true,
|
||||||
ansi: false,
|
ansi: false,
|
||||||
prefix: "inbuxa.log".into(),
|
prefix: "stalwart.log".into(),
|
||||||
rotate: LogRotateFrequency::Daily,
|
rotate: LogRotateFrequency::Daily,
|
||||||
path: "/var/log/inbuxa".into(),
|
path: "/var/log/stalwart".into(),
|
||||||
..Default::default()
|
..Default::default()
|
||||||
})
|
})
|
||||||
.into(),
|
.into(),
|
||||||
|
|||||||
@@ -1,371 +0,0 @@
|
|||||||
/*
|
|
||||||
* SPDX-FileCopyrightText: 2026 Coffey Labs
|
|
||||||
*
|
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only
|
|
||||||
*/
|
|
||||||
|
|
||||||
//! First-party OAuth clients (docs/spec/contract.md C-6).
|
|
||||||
//!
|
|
||||||
//! INBUXA requires OAuth clients to be registered (C-5), so the front ends
|
|
||||||
//! that ship with it are registered for it, on every start:
|
|
||||||
//!
|
|
||||||
//! - the web interface the server serves itself (`Application`, `/admin` and
|
|
||||||
//! `/account`), as its OAuth client id, `stalwart-webui` unless the
|
|
||||||
//! application names another;
|
|
||||||
//! - INBUXA Admin hosted elsewhere, as `inbuxa-admin`, when `INBUXA_ADMIN_URL`
|
|
||||||
//! is set;
|
|
||||||
//! - ihasmail-inbuxa, as the confidential client `ihasmail-inbuxa`, when
|
|
||||||
//! `INBUXA_WEBMAIL_URL` and `INBUXA_WEBMAIL_CLIENT_SECRET` are set.
|
|
||||||
//!
|
|
||||||
//! inbuxa: the environment variables stand in for `x:FrontEnds` (C-4) until
|
|
||||||
//! that object exists; the installer and INBUXA Admin's setup wizard will set
|
|
||||||
//! it instead.
|
|
||||||
//!
|
|
||||||
//! A missing client is created. An existing one gains any redirect URI it
|
|
||||||
//! lacks and, for ihasmail-inbuxa, the configured secret; nothing an operator
|
|
||||||
//! added is removed.
|
|
||||||
|
|
||||||
use directory::core::secret::{hash_secret, verify_secret_hash};
|
|
||||||
use registry::{
|
|
||||||
schema::{
|
|
||||||
enums::{PasswordHashAlgorithm, ServiceProtocol},
|
|
||||||
prelude::{ObjectType, Property, UTCDateTime},
|
|
||||||
structs::{Application, OAuthClient, SystemSettings},
|
|
||||||
},
|
|
||||||
types::map::Map,
|
|
||||||
};
|
|
||||||
use store::registry::{
|
|
||||||
bootstrap::Bootstrap,
|
|
||||||
write::{RegistryWrite, RegistryWriteResult},
|
|
||||||
};
|
|
||||||
|
|
||||||
/// The client id the upstream web interface uses when its application names none.
|
|
||||||
pub const WEB_INTERFACE_CLIENT_ID: &str = "stalwart-webui";
|
|
||||||
pub const ADMIN_CLIENT_ID: &str = "inbuxa-admin";
|
|
||||||
pub const WEBMAIL_CLIENT_ID: &str = "ihasmail-inbuxa";
|
|
||||||
|
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
|
||||||
pub struct FirstPartyClient {
|
|
||||||
pub client_id: String,
|
|
||||||
pub description: String,
|
|
||||||
pub redirect_uris: Vec<String>,
|
|
||||||
pub secret: Option<String>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The first-party clients this server should have, from its applications and
|
|
||||||
/// the front-end addresses it was given.
|
|
||||||
pub fn first_party_clients(
|
|
||||||
base_url: &str,
|
|
||||||
applications: &[Application],
|
|
||||||
admin_url: Option<&str>,
|
|
||||||
webmail: Option<(&str, &str)>,
|
|
||||||
) -> Vec<FirstPartyClient> {
|
|
||||||
let base_url = base_url.trim_end_matches('/');
|
|
||||||
let mut clients: Vec<FirstPartyClient> = Vec::new();
|
|
||||||
|
|
||||||
for app in applications.iter().filter(|app| app.enabled) {
|
|
||||||
let client_id = app
|
|
||||||
.oauth_client_id
|
|
||||||
.as_deref()
|
|
||||||
.filter(|id| !id.is_empty())
|
|
||||||
.unwrap_or(WEB_INTERFACE_CLIENT_ID);
|
|
||||||
let redirect_uris = app
|
|
||||||
.url_prefix
|
|
||||||
.iter()
|
|
||||||
.map(|prefix| {
|
|
||||||
format!(
|
|
||||||
"{base_url}/{}/oauth/callback",
|
|
||||||
prefix.trim_matches('/')
|
|
||||||
)
|
|
||||||
})
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
if redirect_uris.is_empty() {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(client) = clients.iter_mut().find(|c| c.client_id == client_id) {
|
|
||||||
for uri in redirect_uris {
|
|
||||||
if !client.redirect_uris.contains(&uri) {
|
|
||||||
client.redirect_uris.push(uri);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
clients.push(FirstPartyClient {
|
|
||||||
client_id: client_id.to_string(),
|
|
||||||
description: format!("{} (served by this server)", app.description),
|
|
||||||
redirect_uris,
|
|
||||||
secret: None,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(url) = admin_url.map(|url| url.trim().trim_end_matches('/')).filter(|url| !url.is_empty()) {
|
|
||||||
clients.push(FirstPartyClient {
|
|
||||||
client_id: ADMIN_CLIENT_ID.to_string(),
|
|
||||||
description: "INBUXA Admin".to_string(),
|
|
||||||
redirect_uris: vec![format!("{url}/oauth/callback")],
|
|
||||||
secret: None,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some((url, secret)) = webmail {
|
|
||||||
let url = url.trim().trim_end_matches('/');
|
|
||||||
if !url.is_empty() && !secret.is_empty() {
|
|
||||||
clients.push(FirstPartyClient {
|
|
||||||
client_id: WEBMAIL_CLIENT_ID.to_string(),
|
|
||||||
description: "ihasmail webmail".to_string(),
|
|
||||||
redirect_uris: vec![format!("{url}/api/auth/callback")],
|
|
||||||
secret: Some(secret.to_string()),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
clients
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The address the server's own pages are served from, as `Http` works it out.
|
|
||||||
fn base_url(bp: &Bootstrap, system: &SystemSettings) -> String {
|
|
||||||
if let Some(url) = bp.registry.public_url() {
|
|
||||||
return url.to_string();
|
|
||||||
}
|
|
||||||
let default_hostname = if !system.default_hostname.is_empty() {
|
|
||||||
system.default_hostname.as_str()
|
|
||||||
} else {
|
|
||||||
bp.registry.local_hostname()
|
|
||||||
};
|
|
||||||
let host = system
|
|
||||||
.services
|
|
||||||
.iter()
|
|
||||||
.find(|(service, _)| matches!(service, ServiceProtocol::Jmap))
|
|
||||||
.and_then(|(_, details)| details.hostname.as_deref())
|
|
||||||
.unwrap_or(default_hostname);
|
|
||||||
format!("https://{host}")
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The origin (`scheme://host[:port]`) of a front end's address, lowercased,
|
|
||||||
/// without a default port. `None` if it isn't an `http` or `https` URL.
|
|
||||||
pub fn origin_of(url: &str) -> Option<String> {
|
|
||||||
let uri = url.trim().parse::<hyper::Uri>().ok()?;
|
|
||||||
let scheme = uri.scheme_str()?.to_ascii_lowercase();
|
|
||||||
let default_port = match scheme.as_str() {
|
|
||||||
"https" => 443,
|
|
||||||
"http" => 80,
|
|
||||||
_ => return None,
|
|
||||||
};
|
|
||||||
let host = uri.host()?.to_ascii_lowercase();
|
|
||||||
if host.is_empty() {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
Some(match uri.port_u16() {
|
|
||||||
Some(port) if port != default_port => format!("{scheme}://{host}:{port}"),
|
|
||||||
_ => format!("{scheme}://{host}"),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The origins allowed to make cross-origin requests (contract C-14): INBUXA
|
|
||||||
/// Admin's, the webmail's, and `INBUXA_CORS_EXTRA_ORIGINS` (comma-separated).
|
|
||||||
///
|
|
||||||
/// inbuxa: read from the environment until `x:FrontEnds` exists (C-4).
|
|
||||||
pub fn front_end_origins() -> Vec<String> {
|
|
||||||
let mut origins = Vec::new();
|
|
||||||
for url in [env("ADMIN_URL"), env("WEBMAIL_URL")].into_iter().flatten() {
|
|
||||||
origins.extend(origin_of(&url));
|
|
||||||
}
|
|
||||||
if let Some(extra) = env("CORS_EXTRA_ORIGINS") {
|
|
||||||
origins.extend(extra.split(',').filter_map(origin_of));
|
|
||||||
}
|
|
||||||
origins.sort();
|
|
||||||
origins.dedup();
|
|
||||||
origins
|
|
||||||
}
|
|
||||||
|
|
||||||
fn env(name: &str) -> Option<String> {
|
|
||||||
types::branding::env_var(name)
|
|
||||||
.ok()
|
|
||||||
.map(|value| value.trim().to_string())
|
|
||||||
.filter(|value| !value.is_empty())
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn ensure_first_party_clients(bp: &mut Bootstrap) -> trc::Result<()> {
|
|
||||||
let system = bp.setting_infallible::<SystemSettings>().await;
|
|
||||||
let base_url = base_url(bp, &system);
|
|
||||||
let applications = bp
|
|
||||||
.list_infallible::<Application>()
|
|
||||||
.await
|
|
||||||
.into_iter()
|
|
||||||
.map(|app| app.object)
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
let admin_url = env("ADMIN_URL");
|
|
||||||
let webmail_url = env("WEBMAIL_URL");
|
|
||||||
let webmail_secret = env("WEBMAIL_CLIENT_SECRET");
|
|
||||||
if webmail_url.is_some() && webmail_secret.is_none() {
|
|
||||||
trc::event!(
|
|
||||||
Auth(trc::AuthEvent::Error),
|
|
||||||
Details = "INBUXA_WEBMAIL_URL is set without INBUXA_WEBMAIL_CLIENT_SECRET; the webmail client was not registered."
|
|
||||||
);
|
|
||||||
}
|
|
||||||
let webmail = webmail_url.as_deref().zip(webmail_secret.as_deref());
|
|
||||||
|
|
||||||
for client in first_party_clients(&base_url, &applications, admin_url.as_deref(), webmail) {
|
|
||||||
ensure_client(bp, client).await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn ensure_client(bp: &mut Bootstrap, client: FirstPartyClient) -> trc::Result<()> {
|
|
||||||
let existing = match bp
|
|
||||||
.registry
|
|
||||||
.primary_key(
|
|
||||||
ObjectType::OAuthClient.into(),
|
|
||||||
Property::ClientId,
|
|
||||||
client.client_id.as_bytes().to_vec(),
|
|
||||||
)
|
|
||||||
.await?
|
|
||||||
{
|
|
||||||
Some(object_id) => bp
|
|
||||||
.registry
|
|
||||||
.object::<OAuthClient>(object_id.id())
|
|
||||||
.await?
|
|
||||||
.map(|object| (object_id.id(), object)),
|
|
||||||
None => None,
|
|
||||||
};
|
|
||||||
|
|
||||||
let result = if let Some((id, current)) = existing {
|
|
||||||
let mut updated = current.clone();
|
|
||||||
for uri in &client.redirect_uris {
|
|
||||||
if !updated.redirect_uris.contains(uri) {
|
|
||||||
updated.redirect_uris.push(uri.clone());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if let Some(secret) = &client.secret {
|
|
||||||
let matches = match updated.secret.as_deref() {
|
|
||||||
Some(hash) if !hash.is_empty() => {
|
|
||||||
verify_secret_hash(hash, secret.as_bytes()).await?
|
|
||||||
}
|
|
||||||
_ => false,
|
|
||||||
};
|
|
||||||
if !matches {
|
|
||||||
updated.secret = Some(
|
|
||||||
hash_secret(PasswordHashAlgorithm::Argon2id, secret.as_bytes().to_vec())
|
|
||||||
.await?,
|
|
||||||
);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if updated == current {
|
|
||||||
return Ok(());
|
|
||||||
}
|
|
||||||
bp.registry
|
|
||||||
.write(RegistryWrite::update(id, &updated.into(), ¤t.into()))
|
|
||||||
.await?
|
|
||||||
} else {
|
|
||||||
let secret = match &client.secret {
|
|
||||||
Some(secret) => Some(
|
|
||||||
hash_secret(PasswordHashAlgorithm::Argon2id, secret.as_bytes().to_vec()).await?,
|
|
||||||
),
|
|
||||||
None => None,
|
|
||||||
};
|
|
||||||
bp.registry
|
|
||||||
.write(RegistryWrite::insert(
|
|
||||||
&OAuthClient {
|
|
||||||
client_id: client.client_id.clone(),
|
|
||||||
description: Some(client.description),
|
|
||||||
redirect_uris: Map::new(client.redirect_uris),
|
|
||||||
secret,
|
|
||||||
created_at: UTCDateTime::now(),
|
|
||||||
..Default::default()
|
|
||||||
}
|
|
||||||
.into(),
|
|
||||||
))
|
|
||||||
.await?
|
|
||||||
};
|
|
||||||
|
|
||||||
if !matches!(result, RegistryWriteResult::Success(_)) {
|
|
||||||
return Err(trc::StoreEvent::UnexpectedError
|
|
||||||
.into_err()
|
|
||||||
.details("Failed to register a first-party OAuth client.")
|
|
||||||
.ctx(trc::Key::Id, client.client_id)
|
|
||||||
.reason(result.to_string())
|
|
||||||
.caused_by(trc::location!()));
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
fn web_interface() -> Application {
|
|
||||||
Application {
|
|
||||||
description: "Stalwart Web Interface".to_string(),
|
|
||||||
enabled: true,
|
|
||||||
url_prefix: Map::new(vec!["/admin".into(), "/account".into()]),
|
|
||||||
..Default::default()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn web_interface_gets_one_uri_per_prefix() {
|
|
||||||
let clients = first_party_clients("https://mail.example.org/", &[web_interface()], None, None);
|
|
||||||
assert_eq!(
|
|
||||||
clients,
|
|
||||||
vec![FirstPartyClient {
|
|
||||||
client_id: WEB_INTERFACE_CLIENT_ID.to_string(),
|
|
||||||
description: "Stalwart Web Interface (served by this server)".to_string(),
|
|
||||||
redirect_uris: vec![
|
|
||||||
"https://mail.example.org/admin/oauth/callback".to_string(),
|
|
||||||
"https://mail.example.org/account/oauth/callback".to_string(),
|
|
||||||
],
|
|
||||||
secret: None,
|
|
||||||
}]
|
|
||||||
);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn disabled_applications_and_named_clients() {
|
|
||||||
let mut disabled = web_interface();
|
|
||||||
disabled.enabled = false;
|
|
||||||
let mut named = web_interface();
|
|
||||||
named.oauth_client_id = Some("custom".to_string());
|
|
||||||
named.url_prefix = Map::new(vec!["portal".into()]);
|
|
||||||
let clients = first_party_clients("https://h", &[disabled, named], None, None);
|
|
||||||
assert_eq!(clients.len(), 1);
|
|
||||||
assert_eq!(clients[0].client_id, "custom");
|
|
||||||
assert_eq!(clients[0].redirect_uris, vec!["https://h/portal/oauth/callback"]);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn front_ends_from_their_addresses() {
|
|
||||||
let clients = first_party_clients(
|
|
||||||
"https://h",
|
|
||||||
&[],
|
|
||||||
Some("https://admin.example.org/"),
|
|
||||||
Some(("https://webmail.example.org", "s3cret")),
|
|
||||||
);
|
|
||||||
assert_eq!(clients.len(), 2);
|
|
||||||
assert_eq!(clients[0].client_id, ADMIN_CLIENT_ID);
|
|
||||||
assert_eq!(clients[0].redirect_uris, vec!["https://admin.example.org/oauth/callback"]);
|
|
||||||
assert_eq!(clients[0].secret, None);
|
|
||||||
assert_eq!(clients[1].client_id, WEBMAIL_CLIENT_ID);
|
|
||||||
assert_eq!(clients[1].redirect_uris, vec!["https://webmail.example.org/api/auth/callback"]);
|
|
||||||
assert_eq!(clients[1].secret.as_deref(), Some("s3cret"));
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn origins() {
|
|
||||||
assert_eq!(origin_of("https://Admin.Example.org/"), Some("https://admin.example.org".into()));
|
|
||||||
assert_eq!(origin_of("https://admin.example.org:443/x"), Some("https://admin.example.org".into()));
|
|
||||||
assert_eq!(origin_of("http://localhost:5173"), Some("http://localhost:5173".into()));
|
|
||||||
assert_eq!(origin_of("https://h:8443/app"), Some("https://h:8443".into()));
|
|
||||||
assert_eq!(origin_of("ftp://h"), None);
|
|
||||||
assert_eq!(origin_of("not a url"), None);
|
|
||||||
assert_eq!(origin_of(""), None);
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn webmail_needs_a_secret() {
|
|
||||||
let clients = first_party_clients("https://h", &[], Some(" "), Some(("https://w", "")));
|
|
||||||
assert!(clients.is_empty());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::USER_AGENT;
|
use crate::USER_AGENT;
|
||||||
@@ -20,7 +18,6 @@ pub mod backup;
|
|||||||
pub mod boot;
|
pub mod boot;
|
||||||
pub mod console;
|
pub mod console;
|
||||||
pub mod defaults;
|
pub mod defaults;
|
||||||
pub mod first_party;
|
|
||||||
pub mod restore;
|
pub mod restore;
|
||||||
|
|
||||||
pub const SPAM_TRAINER_KEY: &[u8] = "STALWART_SPAM_TRAIN_DATA.lz4".as_bytes();
|
pub const SPAM_TRAINER_KEY: &[u8] = "STALWART_SPAM_TRAIN_DATA.lz4".as_bytes();
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use super::backup::MAGIC_MARKER;
|
use super::backup::MAGIC_MARKER;
|
||||||
@@ -54,9 +52,9 @@ impl Core {
|
|||||||
if !conflicts.is_empty() {
|
if !conflicts.is_empty() {
|
||||||
eprintln!(
|
eprintln!(
|
||||||
"Cannot import: the target database already contains data in the key ranges being \
|
"Cannot import: the target database already contains data in the key ranges being \
|
||||||
imported. This usually means the server was started before the import ran, which \
|
imported. This usually means Stalwart was started before the import ran, which \
|
||||||
can create duplicate entries. Import into a fresh, empty database and do not \
|
can create duplicate entries. Import into a fresh, empty database and do not \
|
||||||
start the server before importing. Conflicting dumps:"
|
start Stalwart before importing. Conflicting dumps:"
|
||||||
);
|
);
|
||||||
for path in conflicts {
|
for path in conflicts {
|
||||||
eprintln!(" {}", path.display());
|
eprintln!(" {}", path.display());
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <[email protected]>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// Adapted from rustls-acme (https://github.com/FlorianUekermann/rustls-acme), licensed under MIT/Apache-2.0.
|
// Adapted from rustls-acme (https://github.com/FlorianUekermann/rustls-acme), licensed under MIT/Apache-2.0.
|
||||||
@@ -98,7 +96,38 @@ impl AcmeRequestBuilder {
|
|||||||
reuse_key_pem: Option<String>,
|
reuse_key_pem: Option<String>,
|
||||||
dns_parameters: Option<AcmeDnsParameters>,
|
dns_parameters: Option<AcmeDnsParameters>,
|
||||||
) -> AcmeResult<PemCert> {
|
) -> AcmeResult<PemCert> {
|
||||||
let mut params = CertificateParams::new(domains.clone()).map_err(|err| {
|
let mut published = BTreeSet::new();
|
||||||
|
let result = self
|
||||||
|
.run_order(
|
||||||
|
server,
|
||||||
|
&domains,
|
||||||
|
reuse_key_pem,
|
||||||
|
dns_parameters.as_ref(),
|
||||||
|
&mut published,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
if let Some(dns_parameters) = &dns_parameters {
|
||||||
|
for (zone, challenge_name) in published {
|
||||||
|
let _ = dns_parameters
|
||||||
|
.updater
|
||||||
|
.delete_rrset(&zone, &challenge_name, dns_update::DnsRecordType::TXT)
|
||||||
|
.await;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
result
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn run_order(
|
||||||
|
&self,
|
||||||
|
server: &Server,
|
||||||
|
domains: &[String],
|
||||||
|
reuse_key_pem: Option<String>,
|
||||||
|
dns_parameters: Option<&AcmeDnsParameters>,
|
||||||
|
published: &mut BTreeSet<(String, String)>,
|
||||||
|
) -> AcmeResult<PemCert> {
|
||||||
|
let mut params = CertificateParams::new(domains.to_vec()).map_err(|err| {
|
||||||
AcmeError::Crypto(format!("Failed to create certificate params: {}", err))
|
AcmeError::Crypto(format!("Failed to create certificate params: {}", err))
|
||||||
})?;
|
})?;
|
||||||
params.distinguished_name = DistinguishedName::new();
|
params.distinguished_name = DistinguishedName::new();
|
||||||
@@ -110,7 +139,7 @@ impl AcmeRequestBuilder {
|
|||||||
AcmeError::Crypto(format!("Failed to generate key pair: {}", err))
|
AcmeError::Crypto(format!("Failed to generate key pair: {}", err))
|
||||||
})?,
|
})?,
|
||||||
};
|
};
|
||||||
let response = self.new_order(domains.clone()).await?;
|
let response = self.new_order(domains.to_vec()).await?;
|
||||||
let order_url = response.location;
|
let order_url = response.location;
|
||||||
let mut order = response.body;
|
let mut order = response.body;
|
||||||
let mut retry_after = None;
|
let mut retry_after = None;
|
||||||
@@ -119,7 +148,7 @@ impl AcmeRequestBuilder {
|
|||||||
Acme(AcmeEvent::OrderStart),
|
Acme(AcmeEvent::OrderStart),
|
||||||
Url = self.directory.new_order.to_string(),
|
Url = self.directory.new_order.to_string(),
|
||||||
Details = order_url.to_string(),
|
Details = order_url.to_string(),
|
||||||
Hostname = domains.as_slice(),
|
Hostname = domains,
|
||||||
Type = self.challenge.as_str(),
|
Type = self.challenge.as_str(),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -128,19 +157,20 @@ impl AcmeRequestBuilder {
|
|||||||
OrderStatus::Pending => {
|
OrderStatus::Pending => {
|
||||||
if matches!(self.challenge, ChallengeType::Dns01) {
|
if matches!(self.challenge, ChallengeType::Dns01) {
|
||||||
for url in &order.authorizations {
|
for url in &order.authorizations {
|
||||||
self.authorize(server, url, dns_parameters.as_ref()).await?;
|
self.authorize(server, url, dns_parameters, Some(published))
|
||||||
|
.await?;
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
let auth_futures = order
|
let auth_futures = order
|
||||||
.authorizations
|
.authorizations
|
||||||
.iter()
|
.iter()
|
||||||
.map(|url| self.authorize(server, url, dns_parameters.as_ref()));
|
.map(|url| self.authorize(server, url, dns_parameters, None));
|
||||||
try_join_all(auth_futures).await?;
|
try_join_all(auth_futures).await?;
|
||||||
}
|
}
|
||||||
trc::event!(
|
trc::event!(
|
||||||
Acme(AcmeEvent::AuthCompleted),
|
Acme(AcmeEvent::AuthCompleted),
|
||||||
Url = self.directory.new_order.to_string(),
|
Url = self.directory.new_order.to_string(),
|
||||||
Hostname = domains.as_slice(),
|
Hostname = domains,
|
||||||
);
|
);
|
||||||
let response = self.order(&order_url).await?;
|
let response = self.order(&order_url).await?;
|
||||||
order = response.body;
|
order = response.body;
|
||||||
@@ -151,7 +181,7 @@ impl AcmeRequestBuilder {
|
|||||||
trc::event!(
|
trc::event!(
|
||||||
Acme(AcmeEvent::OrderProcessing),
|
Acme(AcmeEvent::OrderProcessing),
|
||||||
Url = self.directory.new_order.to_string(),
|
Url = self.directory.new_order.to_string(),
|
||||||
Hostname = domains.as_slice(),
|
Hostname = domains,
|
||||||
Total = i,
|
Total = i,
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -179,7 +209,7 @@ impl AcmeRequestBuilder {
|
|||||||
trc::event!(
|
trc::event!(
|
||||||
Acme(AcmeEvent::OrderReady),
|
Acme(AcmeEvent::OrderReady),
|
||||||
Url = self.directory.new_order.to_string(),
|
Url = self.directory.new_order.to_string(),
|
||||||
Hostname = domains.as_slice(),
|
Hostname = domains,
|
||||||
);
|
);
|
||||||
|
|
||||||
let csr = params.serialize_request(&key_pair).map_err(|err| {
|
let csr = params.serialize_request(&key_pair).map_err(|err| {
|
||||||
@@ -192,10 +222,10 @@ impl AcmeRequestBuilder {
|
|||||||
trc::event!(
|
trc::event!(
|
||||||
Acme(AcmeEvent::OrderValid),
|
Acme(AcmeEvent::OrderValid),
|
||||||
Url = self.directory.new_order.to_string(),
|
Url = self.directory.new_order.to_string(),
|
||||||
Hostname = domains.as_slice(),
|
Hostname = domains,
|
||||||
);
|
);
|
||||||
|
|
||||||
let certificate = self.select_certificate(&domains, certificate).await?;
|
let certificate = self.select_certificate(domains, certificate).await?;
|
||||||
|
|
||||||
return Ok(PemCert {
|
return Ok(PemCert {
|
||||||
certificate,
|
certificate,
|
||||||
@@ -213,7 +243,7 @@ impl AcmeRequestBuilder {
|
|||||||
Acme(AcmeEvent::OrderInvalid),
|
Acme(AcmeEvent::OrderInvalid),
|
||||||
Url = self.directory.new_order.to_string(),
|
Url = self.directory.new_order.to_string(),
|
||||||
Details = order_url.to_string(),
|
Details = order_url.to_string(),
|
||||||
Hostname = domains.as_slice(),
|
Hostname = domains,
|
||||||
Reason = reason.clone(),
|
Reason = reason.clone(),
|
||||||
);
|
);
|
||||||
|
|
||||||
@@ -228,6 +258,7 @@ impl AcmeRequestBuilder {
|
|||||||
server: &Server,
|
server: &Server,
|
||||||
url: &String,
|
url: &String,
|
||||||
dns_parameters: Option<&AcmeDnsParameters>,
|
dns_parameters: Option<&AcmeDnsParameters>,
|
||||||
|
published: Option<&mut BTreeSet<(String, String)>>,
|
||||||
) -> AcmeResult<()> {
|
) -> AcmeResult<()> {
|
||||||
let response = self
|
let response = self
|
||||||
.auth(url)
|
.auth(url)
|
||||||
@@ -236,7 +267,7 @@ impl AcmeRequestBuilder {
|
|||||||
let mut retry_after = response.retry_after;
|
let mut retry_after = response.retry_after;
|
||||||
let auth = response.body;
|
let auth = response.body;
|
||||||
|
|
||||||
let domain = match auth.status {
|
let (domain, challenge_url) = match auth.status {
|
||||||
AuthStatus::Pending => {
|
AuthStatus::Pending => {
|
||||||
let Identifier::Dns(domain) = auth.identifier;
|
let Identifier::Dns(domain) = auth.identifier;
|
||||||
|
|
||||||
@@ -289,7 +320,12 @@ impl AcmeRequestBuilder {
|
|||||||
.await?;
|
.await?;
|
||||||
}
|
}
|
||||||
ChallengeType::Dns01 => {
|
ChallengeType::Dns01 => {
|
||||||
let dns_parameters = dns_parameters.unwrap();
|
let Some(dns_parameters) = dns_parameters else {
|
||||||
|
return Err(AcmeError::Invalid(
|
||||||
|
"DNS-01 challenge requested but a DNS provider was not configured"
|
||||||
|
.to_string(),
|
||||||
|
));
|
||||||
|
};
|
||||||
let domain = domain.strip_prefix("*.").unwrap_or(&domain);
|
let domain = domain.strip_prefix("*.").unwrap_or(&domain);
|
||||||
|
|
||||||
let zone = dns_parameters
|
let zone = dns_parameters
|
||||||
@@ -310,6 +346,11 @@ impl AcmeRequestBuilder {
|
|||||||
)
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(AcmeError::Dns)?;
|
.map_err(AcmeError::Dns)?;
|
||||||
|
|
||||||
|
if let Some(published) = published {
|
||||||
|
published.insert((zone.to_string(), challenge_name.clone()));
|
||||||
|
}
|
||||||
|
|
||||||
dns_parameters
|
dns_parameters
|
||||||
.updater
|
.updater
|
||||||
.wait_for_txt_propagation(&challenge_name, zone, &proof)
|
.wait_for_txt_propagation(&challenge_name, zone, &proof)
|
||||||
@@ -320,7 +361,7 @@ impl AcmeRequestBuilder {
|
|||||||
}
|
}
|
||||||
|
|
||||||
self.challenge(&challenge.url).await?;
|
self.challenge(&challenge.url).await?;
|
||||||
domain
|
(domain, challenge.url.clone())
|
||||||
}
|
}
|
||||||
AuthStatus::Valid => return Ok(()),
|
AuthStatus::Valid => return Ok(()),
|
||||||
_ => {
|
_ => {
|
||||||
@@ -347,20 +388,14 @@ impl AcmeRequestBuilder {
|
|||||||
|
|
||||||
match response.body.status {
|
match response.body.status {
|
||||||
AuthStatus::Pending => {
|
AuthStatus::Pending => {
|
||||||
// inbuxa: keep polling, don't post the challenge again.
|
|
||||||
// RFC 8555 section 7.5.1 has the client post a challenge
|
|
||||||
// once to say it's ready and then poll the authorization,
|
|
||||||
// which stays pending while validation runs. Posting it
|
|
||||||
// again is refused once the server has moved the
|
|
||||||
// challenge to "processing" (pebble answers 400
|
|
||||||
// malformed, "Cannot update challenge with status
|
|
||||||
// processing"), and that refusal failed the renewal.
|
|
||||||
trc::event!(
|
trc::event!(
|
||||||
Acme(AcmeEvent::AuthPending),
|
Acme(AcmeEvent::AuthPending),
|
||||||
Hostname = domain.to_string(),
|
Hostname = domain.to_string(),
|
||||||
Url = self.directory.new_order.to_string(),
|
Url = self.directory.new_order.to_string(),
|
||||||
Total = i,
|
Total = i,
|
||||||
);
|
);
|
||||||
|
|
||||||
|
self.challenge(&challenge_url).await?
|
||||||
}
|
}
|
||||||
AuthStatus::Valid => {
|
AuthStatus::Valid => {
|
||||||
trc::event!(
|
trc::event!(
|
||||||
|
|||||||
@@ -1150,6 +1150,36 @@ impl DnsUpdater {
|
|||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub async fn delete_rrset(
|
||||||
|
&self,
|
||||||
|
origin: &str,
|
||||||
|
name: &str,
|
||||||
|
record_type: DnsRecordType,
|
||||||
|
) -> Result<(), String> {
|
||||||
|
if let Err(err) = self
|
||||||
|
.updater
|
||||||
|
.set_rrset(
|
||||||
|
name,
|
||||||
|
record_type,
|
||||||
|
self.ttl.as_secs() as u32,
|
||||||
|
Vec::new(),
|
||||||
|
origin,
|
||||||
|
)
|
||||||
|
.await
|
||||||
|
{
|
||||||
|
trc::event!(
|
||||||
|
Dns(DnsEvent::RecordDeletionFailed),
|
||||||
|
Hostname = name.to_string(),
|
||||||
|
Details = origin.to_string(),
|
||||||
|
Type = record_type.as_str(),
|
||||||
|
Reason = err.to_string(),
|
||||||
|
);
|
||||||
|
return Err(format!("Failed to delete DNS RRSet: {}", err));
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn add_to_rrset(
|
pub async fn add_to_rrset(
|
||||||
&self,
|
&self,
|
||||||
origin: &str,
|
origin: &str,
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -23,9 +21,10 @@ use crate::{
|
|||||||
manager::SPAM_CLASSIFIER_KEY,
|
manager::SPAM_CLASSIFIER_KEY,
|
||||||
network::RcptResolution,
|
network::RcptResolution,
|
||||||
};
|
};
|
||||||
|
use ahash::AHashSet;
|
||||||
use directory::Recipient;
|
use directory::Recipient;
|
||||||
use mail_auth::IpLookupStrategy;
|
use mail_auth::IpLookupStrategy;
|
||||||
use registry::schema::enums::ExpressionVariable;
|
use registry::schema::{enums::ExpressionVariable, structs::MaskedEmail};
|
||||||
use sieve::Sieve;
|
use sieve::Sieve;
|
||||||
use std::{
|
use std::{
|
||||||
borrow::Cow,
|
borrow::Cow,
|
||||||
@@ -34,9 +33,11 @@ use std::{
|
|||||||
};
|
};
|
||||||
use store::{
|
use store::{
|
||||||
Deserialize, IterateParams, ValueKey,
|
Deserialize, IterateParams, ValueKey,
|
||||||
write::{AlignedBytes, Archive, QueueClass, ValueClass},
|
write::{AlignedBytes, Archive, QueueClass, ValueClass, now},
|
||||||
};
|
};
|
||||||
use trc::{AddContext, SpamEvent};
|
use trc::{AddContext, SpamEvent};
|
||||||
|
use types::id::Id;
|
||||||
|
use utils::DomainPart;
|
||||||
|
|
||||||
impl Server {
|
impl Server {
|
||||||
pub async fn rcpt_resolve(
|
pub async fn rcpt_resolve(
|
||||||
@@ -74,27 +75,6 @@ impl Server {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// inbuxa: ME-4, ME-9: a live masked address is rewritten to its
|
|
||||||
// owner's, which keeps the mask as the original recipient
|
|
||||||
if let inbuxa_features::masked_email::ops::Lookup::Accepts(mask) =
|
|
||||||
inbuxa_features::masked_email::ops::lookup(
|
|
||||||
&self.core.storage.data,
|
|
||||||
self.registry(),
|
|
||||||
&format!("{local_part}@{domain_part}"),
|
|
||||||
)
|
|
||||||
.await?
|
|
||||||
{
|
|
||||||
let owner = self.account(mask.object.account_id.document_id()).await?;
|
|
||||||
if let Some(address) = owner.addresses.first()
|
|
||||||
&& let Some(owner_domain) = self.domain_by_id(address.domain_id).await?
|
|
||||||
&& let Some(owner_domain) = owner_domain.names.first()
|
|
||||||
{
|
|
||||||
return Ok(RcptResolution::Rewrite(format!(
|
|
||||||
"{}@{}",
|
|
||||||
address.local_part, owner_domain
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Obtain external directory, if configured
|
// Obtain external directory, if configured
|
||||||
let directory = self
|
let directory = self
|
||||||
@@ -108,17 +88,6 @@ impl Server {
|
|||||||
Cow::Borrowed(rcpt)
|
Cow::Borrowed(rcpt)
|
||||||
};
|
};
|
||||||
match directory.recipient(address.as_ref()).await? {
|
match directory.recipient(address.as_ref()).await? {
|
||||||
// inbuxa: DIR-6: an answer for another directory's domain is no answer
|
|
||||||
Recipient::Account(account)
|
|
||||||
if self
|
|
||||||
.assert_directory_serves(directory, &account.email)
|
|
||||||
.await
|
|
||||||
.is_err() => {}
|
|
||||||
Recipient::Group(group)
|
|
||||||
if self
|
|
||||||
.assert_directory_serves(directory, &group.email)
|
|
||||||
.await
|
|
||||||
.is_err() => {}
|
|
||||||
Recipient::Account(account) => {
|
Recipient::Account(account) => {
|
||||||
Box::pin(self.synchronize_account(account)).await?;
|
Box::pin(self.synchronize_account(account)).await?;
|
||||||
return Ok(if is_subaddressed {
|
return Ok(if is_subaddressed {
|
||||||
@@ -163,7 +132,10 @@ impl Server {
|
|||||||
}
|
}
|
||||||
EmailCache::MailingList(id) => {
|
EmailCache::MailingList(id) => {
|
||||||
if let Some(list) = self.try_list(id).await? {
|
if let Some(list) = self.try_list(id).await? {
|
||||||
return Ok(RcptResolution::Expand(list.recipients.clone()));
|
return Ok(RcptResolution::Expand(
|
||||||
|
self.expand_nested_lists(id, list.recipients.clone())
|
||||||
|
.await?,
|
||||||
|
));
|
||||||
} else {
|
} else {
|
||||||
self.inner
|
self.inner
|
||||||
.cache
|
.cache
|
||||||
@@ -195,6 +167,56 @@ impl Server {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn expand_nested_lists(
|
||||||
|
&self,
|
||||||
|
list_id: u32,
|
||||||
|
recipients: Arc<[Box<str>]>,
|
||||||
|
) -> trc::Result<Arc<[Box<str>]>> {
|
||||||
|
let mut has_nested = false;
|
||||||
|
for member in recipients.iter() {
|
||||||
|
if let Some(EmailCache::MailingList(_)) = self.rcpt_id_from_email(member).await? {
|
||||||
|
has_nested = true;
|
||||||
|
break;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if !has_nested {
|
||||||
|
return Ok(recipients);
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut expanded = Vec::with_capacity(recipients.len());
|
||||||
|
let mut seen: AHashSet<Box<str>> = AHashSet::with_capacity(recipients.len());
|
||||||
|
let mut visited = AHashSet::from_iter([list_id]);
|
||||||
|
let mut pending: Vec<Arc<[Box<str>]>> = Vec::new();
|
||||||
|
let mut members = recipients;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
for member in members.iter() {
|
||||||
|
if let Some(EmailCache::MailingList(nested_id)) =
|
||||||
|
self.rcpt_id_from_email(member).await?
|
||||||
|
{
|
||||||
|
if !visited.insert(nested_id) {
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
if let Some(nested) = self.try_list(nested_id).await? {
|
||||||
|
pending.push(nested.recipients.clone());
|
||||||
|
continue;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
if seen.insert(member.to_canonical_address().into()) {
|
||||||
|
expanded.push(member.clone());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let Some(next) = pending.pop() else {
|
||||||
|
break;
|
||||||
|
};
|
||||||
|
members = next;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(expanded.into())
|
||||||
|
}
|
||||||
|
|
||||||
pub async fn get_dkim_signers(
|
pub async fn get_dkim_signers(
|
||||||
&self,
|
&self,
|
||||||
domain: &str,
|
domain: &str,
|
||||||
|
|||||||
@@ -2,11 +2,11 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use sieve::{FunctionMap, runtime::Variable};
|
use sieve::{FunctionMap, compiler::Number, runtime::Variable};
|
||||||
|
use std::time::Instant;
|
||||||
|
use trc::{AiEvent, SecurityEvent};
|
||||||
|
|
||||||
use super::PluginContext;
|
use super::PluginContext;
|
||||||
|
|
||||||
@@ -14,9 +14,7 @@ pub fn register(plugin_id: u32, fnc_map: &mut FunctionMap) {
|
|||||||
fnc_map.set_external_function("llm_prompt", plugin_id, 3);
|
fnc_map.set_external_function("llm_prompt", plugin_id, 3);
|
||||||
}
|
}
|
||||||
|
|
||||||
// inbuxa: AI-20 to AI-25, `llm_prompt(model, prompt, temperature)`
|
|
||||||
pub async fn exec(ctx: PluginContext<'_>) -> trc::Result<Variable> {
|
pub async fn exec(ctx: PluginContext<'_>) -> trc::Result<Variable> {
|
||||||
Ok(crate::enterprise::llm::sieve_prompt(ctx)
|
|
||||||
.await
|
Ok(false.into())
|
||||||
.map_or(Variable::from(false), Variable::from))
|
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,60 +0,0 @@
|
|||||||
/*
|
|
||||||
* SPDX-FileCopyrightText: 2026 Coffey Labs
|
|
||||||
*
|
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only
|
|
||||||
*/
|
|
||||||
|
|
||||||
//! Which logo applies to a domain name (branding spec BT-1, BT-2). The rules
|
|
||||||
//! live in `inbuxa_features::branding::logo`; this finds the domain through
|
|
||||||
//! the server's domain cache and reads the three levels from the registry
|
|
||||||
//! each time, so a change shows at once on every node (BT-10).
|
|
||||||
|
|
||||||
use crate::Server;
|
|
||||||
use inbuxa_features::branding::logo::{self, Logo, Source};
|
|
||||||
use registry::schema::structs::{Domain, Enterprise, Tenant};
|
|
||||||
use types::id::Id;
|
|
||||||
|
|
||||||
impl Server {
|
|
||||||
/// The logos that apply to a domain name, most specific first. An unknown
|
|
||||||
/// name gets what a known domain with no logo of its own gets (BT-6).
|
|
||||||
pub async fn logos_for(&self, name: &str) -> trc::Result<Vec<Logo>> {
|
|
||||||
let mut domain = None;
|
|
||||||
for candidate in logo::lookup_names(name) {
|
|
||||||
if let Some(found) = self.domain(&candidate).await? {
|
|
||||||
domain = Some(found);
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
let registry = self.registry();
|
|
||||||
let domain_logo = match &domain {
|
|
||||||
Some(domain) => registry
|
|
||||||
.object::<Domain>(Id::from(domain.id))
|
|
||||||
.await?
|
|
||||||
.and_then(|d| d.logo),
|
|
||||||
None => None,
|
|
||||||
};
|
|
||||||
let tenant_id = domain.as_ref().and_then(|d| d.id_tenant);
|
|
||||||
let tenant_logo = match tenant_id {
|
|
||||||
Some(tenant_id) => registry
|
|
||||||
.object::<Tenant>(Id::from(tenant_id))
|
|
||||||
.await?
|
|
||||||
.and_then(|t| t.logo),
|
|
||||||
None => None,
|
|
||||||
};
|
|
||||||
let server_logo = registry
|
|
||||||
.object::<Enterprise>(Id::singleton())
|
|
||||||
.await?
|
|
||||||
.and_then(|e| e.logo_url);
|
|
||||||
Ok(logo::chain([
|
|
||||||
(
|
|
||||||
Source::Domain(domain.as_ref().map_or(u32::MAX, |d| d.id)),
|
|
||||||
domain_logo.as_deref(),
|
|
||||||
),
|
|
||||||
(
|
|
||||||
Source::Tenant(tenant_id.unwrap_or(u32::MAX)),
|
|
||||||
tenant_logo.as_deref(),
|
|
||||||
),
|
|
||||||
(Source::Server, server_logo.as_deref()),
|
|
||||||
]))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::Server;
|
use crate::Server;
|
||||||
@@ -20,7 +18,6 @@ use store::{BlobStore, InMemoryStore, RegistryStore, SearchStore, Store};
|
|||||||
|
|
||||||
pub mod archive;
|
pub mod archive;
|
||||||
pub mod blob;
|
pub mod blob;
|
||||||
pub mod branding; // inbuxa: branding BT-1, BT-2
|
|
||||||
pub mod dav;
|
pub mod dav;
|
||||||
pub mod document;
|
pub mod document;
|
||||||
pub mod encryption;
|
pub mod encryption;
|
||||||
@@ -98,26 +95,11 @@ impl Server {
|
|||||||
self.registry().count_object(ObjectType::Domain).await
|
self.registry().count_object(ObjectType::Domain).await
|
||||||
}
|
}
|
||||||
|
|
||||||
// inbuxa: BT-9: the first logo mail can carry inline; none leaves the
|
#[cfg(not(feature = "enterprise"))]
|
||||||
// built-in INBUXA logo
|
|
||||||
pub async fn logo_resource(
|
pub async fn logo_resource(
|
||||||
&self,
|
&self,
|
||||||
domain: &str,
|
_: &str,
|
||||||
) -> trc::Result<Option<crate::manager::application::Resource<Vec<u8>>>> {
|
) -> trc::Result<Option<crate::manager::application::Resource<Vec<u8>>>> {
|
||||||
Ok(self
|
Ok(None)
|
||||||
.logos_for(domain)
|
|
||||||
.await?
|
|
||||||
.into_iter()
|
|
||||||
.find(|logo| logo.is_embeddable())
|
|
||||||
.and_then(|logo| match logo {
|
|
||||||
inbuxa_features::branding::logo::Logo::Image {
|
|
||||||
content_type,
|
|
||||||
bytes,
|
|
||||||
} => Some(crate::manager::application::Resource::new(
|
|
||||||
content_type,
|
|
||||||
bytes,
|
|
||||||
)),
|
|
||||||
inbuxa_features::branding::logo::Logo::Url(_) => None,
|
|
||||||
}))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -33,9 +31,9 @@ impl Server {
|
|||||||
.add_context(|err| err.caused_by(trc::location!()).account_id(account_id))
|
.add_context(|err| err.caused_by(trc::location!()).account_id(account_id))
|
||||||
}
|
}
|
||||||
|
|
||||||
// inbuxa: MT-20: storage used by all a tenant's members together
|
#[cfg(not(feature = "enterprise"))]
|
||||||
pub async fn get_used_quota_tenant(&self, tenant_id: u32) -> trc::Result<i64> {
|
pub async fn get_used_quota_tenant(&self, _tenant_id: u32) -> trc::Result<i64> {
|
||||||
inbuxa_features::tenancy::quota::used(&self.core.storage.data, tenant_id).await
|
Ok(0)
|
||||||
}
|
}
|
||||||
|
|
||||||
pub async fn has_available_quota(
|
pub async fn has_available_quota(
|
||||||
@@ -54,21 +52,6 @@ impl Server {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// inbuxa: MT-19: the tenant's limit applies too, whichever is reached first
|
|
||||||
if let Some(tenant_id) = account.id_tenant {
|
|
||||||
let tenant = self.tenant(tenant_id).await?;
|
|
||||||
if tenant.quota_disk != 0 {
|
|
||||||
let used_quota = self.get_used_quota_tenant(tenant_id).await?.max(0) as u64;
|
|
||||||
|
|
||||||
if used_quota + item_size > tenant.quota_disk {
|
|
||||||
return Err(trc::LimitEvent::TenantQuota
|
|
||||||
.into_err()
|
|
||||||
.ctx(trc::Key::Id, tenant_id)
|
|
||||||
.ctx(trc::Key::Limit, tenant.quota_disk)
|
|
||||||
.ctx(trc::Key::Size, used_quota));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,265 +0,0 @@
|
|||||||
/*
|
|
||||||
* SPDX-FileCopyrightText: 2026 Coffey Labs
|
|
||||||
*
|
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only
|
|
||||||
*/
|
|
||||||
|
|
||||||
//! Alerts (monitoring spec MON-25 to MON-30). Each enabled `x:Alert` is read
|
|
||||||
//! from the registry at evaluation, so a change needs no reload (MON-3), and
|
|
||||||
//! fires when its condition goes from false to true (MON-26).
|
|
||||||
|
|
||||||
use crate::{
|
|
||||||
Server,
|
|
||||||
expr::{functions::EmptyResolver, if_block::BootstrapExprExt},
|
|
||||||
};
|
|
||||||
use ahash::AHashSet;
|
|
||||||
use mail_builder::{
|
|
||||||
MessageBuilder,
|
|
||||||
headers::{HeaderType, address::Address},
|
|
||||||
};
|
|
||||||
use registry::{
|
|
||||||
schema::{
|
|
||||||
prelude::{ExpressionContext, ObjectType},
|
|
||||||
structs::{Alert, AlertEmail, AlertEvent, Expression, ExpressionMatch},
|
|
||||||
},
|
|
||||||
types::{id::ObjectId, list::List},
|
|
||||||
};
|
|
||||||
use std::sync::Mutex;
|
|
||||||
use store::registry::{RegistryQuery, bootstrap::Bootstrap};
|
|
||||||
use trc::{Collector, MetricType, TelemetryEvent};
|
|
||||||
use types::id::Id;
|
|
||||||
|
|
||||||
/// An alert email, ready to queue.
|
|
||||||
#[derive(Debug, Clone)]
|
|
||||||
pub struct AlertMessage {
|
|
||||||
pub from: String,
|
|
||||||
pub to: Vec<String>,
|
|
||||||
pub body: Vec<u8>,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The alerts whose condition held at the last evaluation (MON-26). In
|
|
||||||
/// memory, so a restart while a condition holds fires once more.
|
|
||||||
static FIRING: Mutex<Option<AHashSet<u64>>> = Mutex::new(None);
|
|
||||||
|
|
||||||
fn is_ident_char(c: char) -> bool {
|
|
||||||
c.is_ascii_alphanumeric() || c == '_'
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The metric an underscore name stands for (`queue_count`), MON-25.
|
|
||||||
fn underscore_metric(name: &str) -> Option<MetricType> {
|
|
||||||
static NAMES: std::sync::OnceLock<ahash::AHashMap<String, MetricType>> =
|
|
||||||
std::sync::OnceLock::new();
|
|
||||||
if !name.contains('_') {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
NAMES
|
|
||||||
.get_or_init(|| {
|
|
||||||
(0..=u16::MAX)
|
|
||||||
.filter_map(MetricType::from_id)
|
|
||||||
.map(|metric| (metric.as_str().replace(['.', '-'], "_"), metric))
|
|
||||||
.collect()
|
|
||||||
})
|
|
||||||
.get(name)
|
|
||||||
.copied()
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Rewrites bare underscore metric names into `metric('dotted.name')`,
|
|
||||||
/// leaving quoted text and function names alone (MON-25).
|
|
||||||
pub fn rewrite(text: &str) -> String {
|
|
||||||
let mut out = String::with_capacity(text.len());
|
|
||||||
let chars = text.chars().collect::<Vec<_>>();
|
|
||||||
let mut i = 0;
|
|
||||||
while i < chars.len() {
|
|
||||||
let c = chars[i];
|
|
||||||
if c == '"' || c == '\'' {
|
|
||||||
let quote = c;
|
|
||||||
out.push(c);
|
|
||||||
i += 1;
|
|
||||||
while i < chars.len() {
|
|
||||||
out.push(chars[i]);
|
|
||||||
if chars[i] == quote {
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
i += 1;
|
|
||||||
}
|
|
||||||
i += 1;
|
|
||||||
} else if c.is_ascii_alphabetic() || c == '_' {
|
|
||||||
let start = i;
|
|
||||||
while i < chars.len() && is_ident_char(chars[i]) {
|
|
||||||
i += 1;
|
|
||||||
}
|
|
||||||
let word = chars[start..i].iter().collect::<String>();
|
|
||||||
let is_call = chars[i..].iter().find(|c| !c.is_whitespace()) == Some(&'(');
|
|
||||||
match underscore_metric(&word) {
|
|
||||||
Some(metric) if !is_call => {
|
|
||||||
out.push_str(&format!("metric('{}')", metric.as_str()));
|
|
||||||
}
|
|
||||||
_ => out.push_str(&word),
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
out.push(c);
|
|
||||||
i += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
out
|
|
||||||
}
|
|
||||||
|
|
||||||
/// An alert condition with underscore names rewritten.
|
|
||||||
pub fn rewrite_condition(condition: &Expression) -> Expression {
|
|
||||||
Expression {
|
|
||||||
match_: List::from_iter(condition.match_.iter().map(|m| ExpressionMatch {
|
|
||||||
if_: rewrite(&m.if_),
|
|
||||||
then: rewrite(&m.then),
|
|
||||||
})),
|
|
||||||
else_: rewrite(&condition.else_),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// `%{metric.name}%` replaced by the metric's value: whole numbers without
|
|
||||||
/// decimals, others with at most two (MON-27). Unknown names stay.
|
|
||||||
pub fn render(template: &str) -> String {
|
|
||||||
let mut out = String::with_capacity(template.len());
|
|
||||||
let mut rest = template;
|
|
||||||
while let Some(start) = rest.find("%{") {
|
|
||||||
out.push_str(&rest[..start]);
|
|
||||||
let after = &rest[start + 2..];
|
|
||||||
match after.find("}%") {
|
|
||||||
Some(end) => {
|
|
||||||
let name = &after[..end];
|
|
||||||
match MetricType::parse(name) {
|
|
||||||
Some(metric) => {
|
|
||||||
let value = Collector::read_metric(metric);
|
|
||||||
if value.fract() == 0.0 {
|
|
||||||
out.push_str(&format!("{}", value as i64));
|
|
||||||
} else {
|
|
||||||
let text = format!("{value:.2}");
|
|
||||||
out.push_str(text.trim_end_matches('0').trim_end_matches('.'));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None => out.push_str(&rest[start..start + 2 + end + 2]),
|
|
||||||
}
|
|
||||||
rest = &after[end + 2..];
|
|
||||||
}
|
|
||||||
None => {
|
|
||||||
out.push_str(&rest[start..]);
|
|
||||||
rest = "";
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
out.push_str(rest);
|
|
||||||
out
|
|
||||||
}
|
|
||||||
|
|
||||||
fn build_email(email: ®istry::schema::structs::AlertEmailProperties) -> AlertMessage {
|
|
||||||
let from = match &email.from_name {
|
|
||||||
Some(name) => Address::new_address(Some(name.clone()), email.from_address.clone()),
|
|
||||||
None => Address::new_address(None::<String>, email.from_address.clone()),
|
|
||||||
};
|
|
||||||
let to = email.to.iter().cloned().collect::<Vec<_>>();
|
|
||||||
let body = MessageBuilder::new()
|
|
||||||
.from(from)
|
|
||||||
.to(to
|
|
||||||
.iter()
|
|
||||||
.map(|addr| Address::new_address(None::<String>, addr.clone()))
|
|
||||||
.collect::<Vec<_>>())
|
|
||||||
.subject(render(&email.subject))
|
|
||||||
.header("Auto-Submitted", HeaderType::Text("auto-generated".into()))
|
|
||||||
.text_body(render(&email.body))
|
|
||||||
.write_to_vec()
|
|
||||||
.unwrap_or_default();
|
|
||||||
AlertMessage {
|
|
||||||
from: email.from_address.clone(),
|
|
||||||
to,
|
|
||||||
body,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Server {
|
|
||||||
/// Evaluates every enabled alert once (MON-25, MON-26), emits the event
|
|
||||||
/// of each that fires (MON-28), and returns the emails to queue
|
|
||||||
/// (MON-29). A failing alert is logged and skipped (MON-37).
|
|
||||||
pub async fn process_alerts(&self) -> trc::Result<Vec<AlertMessage>> {
|
|
||||||
let registry = self.registry();
|
|
||||||
let ids = registry
|
|
||||||
.query::<Vec<Id>>(RegistryQuery::new(ObjectType::Alert))
|
|
||||||
.await?;
|
|
||||||
let mut messages = Vec::new();
|
|
||||||
let mut holding = AHashSet::new();
|
|
||||||
for id in ids {
|
|
||||||
let Some(alert) = registry.object::<Alert>(id).await? else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
if !alert.enable {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let condition = rewrite_condition(&alert.condition);
|
|
||||||
let mut bp = Bootstrap::new_uninitialized(registry.clone());
|
|
||||||
let if_block = bp.compile_expr(
|
|
||||||
ObjectId::new(ObjectType::Alert, id),
|
|
||||||
&ExpressionContext {
|
|
||||||
expr: &condition,
|
|
||||||
..alert.ctx_condition()
|
|
||||||
},
|
|
||||||
);
|
|
||||||
if !bp.errors.is_empty() || if_block.is_empty() {
|
|
||||||
trc::event!(
|
|
||||||
Registry(trc::RegistryEvent::BuildWarning),
|
|
||||||
Id = id.id(),
|
|
||||||
Details = "The alert's condition can't be evaluated",
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let holds = self
|
|
||||||
.eval_if::<bool, _>(&if_block, &EmptyResolver, 0)
|
|
||||||
.await
|
|
||||||
.unwrap_or(false);
|
|
||||||
if !holds {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
holding.insert(id.id());
|
|
||||||
let was_firing = FIRING
|
|
||||||
.lock()
|
|
||||||
.unwrap()
|
|
||||||
.as_ref()
|
|
||||||
.is_some_and(|firing| firing.contains(&id.id()));
|
|
||||||
if was_firing {
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
|
|
||||||
if let AlertEvent::Enabled(event) = &alert.event_alert {
|
|
||||||
trc::event!(
|
|
||||||
Telemetry(TelemetryEvent::AlertEvent),
|
|
||||||
Id = id.id(),
|
|
||||||
Details = render(event.event_message.as_deref().unwrap_or("Alert triggered")),
|
|
||||||
);
|
|
||||||
}
|
|
||||||
if let AlertEmail::Enabled(email) = &alert.email_alert {
|
|
||||||
messages.push(build_email(email));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
*FIRING.lock().unwrap() = Some(holding);
|
|
||||||
Ok(messages)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn rewrites_underscore_names() {
|
|
||||||
assert_eq!(rewrite("domain_count > 1"), "metric('domain.count') > 1");
|
|
||||||
assert_eq!(
|
|
||||||
rewrite("metric('queue.count') > 5 && queue_count < 9"),
|
|
||||||
"metric('queue.count') > 5 && metric('queue.count') < 9"
|
|
||||||
);
|
|
||||||
assert_eq!(rewrite("'domain_count' == x"), "'domain_count' == x");
|
|
||||||
assert_eq!(rewrite("unknown_thing > 1"), "unknown_thing > 1");
|
|
||||||
}
|
|
||||||
|
|
||||||
#[test]
|
|
||||||
fn renders_placeholders() {
|
|
||||||
assert_eq!(render("no placeholders"), "no placeholders");
|
|
||||||
assert_eq!(render("%{no.such-metric}% left"), "%{no.such-metric}% left");
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,12 +2,9 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
pub mod otel;
|
pub mod otel;
|
||||||
pub mod prometheus;
|
pub mod prometheus;
|
||||||
pub mod store; // inbuxa: monitoring history (MON-4 to MON-9)
|
|
||||||
|
|
||||||
|
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::config::telemetry::OtelMetrics;
|
use crate::config::telemetry::OtelMetrics;
|
||||||
@@ -19,12 +17,12 @@ use std::time::SystemTime;
|
|||||||
use trc::{Collector, TelemetryEvent};
|
use trc::{Collector, TelemetryEvent};
|
||||||
|
|
||||||
impl OtelMetrics {
|
impl OtelMetrics {
|
||||||
pub async fn push_metrics(&self, start_time: SystemTime) {
|
pub async fn push_metrics(&self, is_enterprise: bool, start_time: SystemTime) {
|
||||||
let mut metrics = Vec::with_capacity(256);
|
let mut metrics = Vec::with_capacity(256);
|
||||||
let time = SystemTime::now();
|
let time = SystemTime::now();
|
||||||
|
|
||||||
// Add counters
|
// Add counters
|
||||||
for counter in Collector::collect_counters() {
|
for counter in Collector::collect_counters(is_enterprise) {
|
||||||
metrics.push(Metric::new(
|
metrics.push(Metric::new(
|
||||||
counter.id().as_str(),
|
counter.id().as_str(),
|
||||||
counter.id().description(),
|
counter.id().description(),
|
||||||
@@ -40,7 +38,7 @@ impl OtelMetrics {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Add gauges
|
// Add gauges
|
||||||
for gauge in Collector::collect_gauges() {
|
for gauge in Collector::collect_gauges(is_enterprise) {
|
||||||
metrics.push(Metric::new(
|
metrics.push(Metric::new(
|
||||||
gauge.id().as_str(),
|
gauge.id().as_str(),
|
||||||
gauge.id().description(),
|
gauge.id().description(),
|
||||||
@@ -54,7 +52,7 @@ impl OtelMetrics {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Add histograms
|
// Add histograms
|
||||||
for histogram in Collector::collect_histograms() {
|
for histogram in Collector::collect_histograms(is_enterprise) {
|
||||||
metrics.push(Metric::new(
|
metrics.push(Metric::new(
|
||||||
histogram.id().as_str(),
|
histogram.id().as_str(),
|
||||||
histogram.id().description(),
|
histogram.id().description(),
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use prometheus::{
|
use prometheus::{
|
||||||
@@ -18,8 +16,12 @@ impl Server {
|
|||||||
pub async fn export_prometheus_metrics(&self) -> trc::Result<String> {
|
pub async fn export_prometheus_metrics(&self) -> trc::Result<String> {
|
||||||
let mut metrics = Vec::new();
|
let mut metrics = Vec::new();
|
||||||
|
|
||||||
|
|
||||||
|
#[cfg(not(feature = "enterprise"))]
|
||||||
|
let is_enterprise = false;
|
||||||
|
|
||||||
// Add counters
|
// Add counters
|
||||||
for counter in Collector::collect_counters() {
|
for counter in Collector::collect_counters(is_enterprise) {
|
||||||
let mut metric = MetricFamily::default();
|
let mut metric = MetricFamily::default();
|
||||||
metric.set_name(metric_name(counter.id().as_str()));
|
metric.set_name(metric_name(counter.id().as_str()));
|
||||||
metric.set_help(counter.id().description().into());
|
metric.set_help(counter.id().description().into());
|
||||||
@@ -29,7 +31,7 @@ impl Server {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Add gauges
|
// Add gauges
|
||||||
for gauge in Collector::collect_gauges() {
|
for gauge in Collector::collect_gauges(is_enterprise) {
|
||||||
let mut metric = MetricFamily::default();
|
let mut metric = MetricFamily::default();
|
||||||
metric.set_name(metric_name(gauge.id().as_str()));
|
metric.set_name(metric_name(gauge.id().as_str()));
|
||||||
metric.set_help(gauge.id().description().into());
|
metric.set_help(gauge.id().description().into());
|
||||||
@@ -39,7 +41,7 @@ impl Server {
|
|||||||
}
|
}
|
||||||
|
|
||||||
// Add histograms
|
// Add histograms
|
||||||
for histogram in Collector::collect_histograms() {
|
for histogram in Collector::collect_histograms(is_enterprise) {
|
||||||
let mut metric = MetricFamily::default();
|
let mut metric = MetricFamily::default();
|
||||||
metric.set_name(metric_name(histogram.id().as_str()));
|
metric.set_name(metric_name(histogram.id().as_str()));
|
||||||
metric.set_help(histogram.id().description().into());
|
metric.set_help(histogram.id().description().into());
|
||||||
|
|||||||
@@ -1,267 +0,0 @@
|
|||||||
/*
|
|
||||||
* SPDX-FileCopyrightText: 2026 Coffey Labs
|
|
||||||
*
|
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only
|
|
||||||
*/
|
|
||||||
|
|
||||||
//! Metric history (monitoring spec MON-4 to MON-9, MON-17). Each sample is
|
|
||||||
//! stored under `TelemetryClass::Metric(id)`, as an `x:Metric` in the
|
|
||||||
//! registry's own encoding. The id is a snowflake of the tick's time, so key
|
|
||||||
//! order is time order and the timestamp is read from the id.
|
|
||||||
|
|
||||||
use crate::Server;
|
|
||||||
use ahash::AHashMap;
|
|
||||||
use registry::{
|
|
||||||
pickle::PickledStream,
|
|
||||||
schema::{
|
|
||||||
prelude::{ObjectInner, ObjectType},
|
|
||||||
structs::{DataRetention, Metric, MetricCount, MetricSum},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
use std::{future::Future, sync::Mutex, time::Duration};
|
|
||||||
use store::{
|
|
||||||
IterateParams, Store, ValueKey,
|
|
||||||
write::{BatchBuilder, TelemetryClass, ValueClass, key::DeserializeBigEndian, now},
|
|
||||||
};
|
|
||||||
use trc::{AddContext, Collector, MetricType, TelemetryEvent};
|
|
||||||
use types::id::Id;
|
|
||||||
use utils::snowflake::SnowflakeIdGenerator;
|
|
||||||
|
|
||||||
pub trait MetricsStore: Sync + Send {
|
|
||||||
/// Writes one tick's samples, all at `timestamp`.
|
|
||||||
fn write_metrics(
|
|
||||||
&self,
|
|
||||||
samples: Vec<Metric>,
|
|
||||||
timestamp: u64,
|
|
||||||
) -> impl Future<Output = trc::Result<()>> + Send;
|
|
||||||
|
|
||||||
/// Deletes samples older than `keep` (MON-17).
|
|
||||||
fn purge_metrics(&self, keep: Duration) -> impl Future<Output = trc::Result<()>> + Send;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl MetricsStore for Store {
|
|
||||||
async fn write_metrics(&self, samples: Vec<Metric>, timestamp: u64) -> trc::Result<()> {
|
|
||||||
let mut batch = BatchBuilder::new();
|
|
||||||
for sample in samples {
|
|
||||||
let Some(id) = SnowflakeIdGenerator::global_id_from_timestamp(timestamp) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
batch.set(
|
|
||||||
ValueClass::Telemetry(TelemetryClass::Metric(id)),
|
|
||||||
ObjectInner::Metric(sample).to_pickled_vec(),
|
|
||||||
);
|
|
||||||
if batch.is_large_batch() {
|
|
||||||
self.write(batch.build_all()).await?;
|
|
||||||
batch = BatchBuilder::new();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if !batch.is_empty() {
|
|
||||||
self.write(batch.build_all()).await?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn purge_metrics(&self, keep: Duration) -> trc::Result<()> {
|
|
||||||
let Some(until) = SnowflakeIdGenerator::from_duration(keep) else {
|
|
||||||
return Ok(());
|
|
||||||
};
|
|
||||||
self.delete_range(
|
|
||||||
ValueKey::from(ValueClass::Telemetry(TelemetryClass::Metric(0))),
|
|
||||||
ValueKey::from(ValueClass::Telemetry(TelemetryClass::Metric(until))),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.caused_by(trc::location!())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Decodes a stored sample. Records in any other encoding (INBUXA's history
|
|
||||||
/// from before the fork) read as `None` and are skipped.
|
|
||||||
pub fn decode_metric(bytes: &[u8]) -> Option<Metric> {
|
|
||||||
PickledStream::new(bytes)
|
|
||||||
.and_then(|mut stream| ObjectInner::unpickle(ObjectType::Metric, &mut stream))
|
|
||||||
.and_then(|inner| match inner {
|
|
||||||
ObjectInner::Metric(metric) => Some(metric),
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A stored sample as read by key: `None` when it can't be decoded.
|
|
||||||
pub struct MaybeMetric(pub Option<Metric>);
|
|
||||||
|
|
||||||
impl store::Deserialize for MaybeMetric {
|
|
||||||
fn deserialize(bytes: &[u8]) -> trc::Result<Self> {
|
|
||||||
Ok(MaybeMetric(decode_metric(bytes)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A stored sample with its id.
|
|
||||||
pub struct StoredMetric {
|
|
||||||
pub id: u64,
|
|
||||||
pub metric: Metric,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl StoredMetric {
|
|
||||||
pub fn timestamp(&self) -> u64 {
|
|
||||||
SnowflakeIdGenerator::to_timestamp(self.id)
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// What the node wrote last, so counters and histograms are written as
|
|
||||||
/// changes (MON-4). Per process: a restart counts from the start.
|
|
||||||
static LAST: Mutex<Option<AHashMap<MetricType, (u64, u64)>>> = Mutex::new(None);
|
|
||||||
|
|
||||||
/// One tick's samples (MON-4 to MON-6).
|
|
||||||
pub fn sample() -> Vec<Metric> {
|
|
||||||
let mut last_guard = LAST.lock().unwrap();
|
|
||||||
let last = last_guard.get_or_insert_with(AHashMap::new);
|
|
||||||
let mut samples = Vec::new();
|
|
||||||
|
|
||||||
// Counters: the increase since the previous sample; none if unchanged
|
|
||||||
for counter in Collector::collect_counters() {
|
|
||||||
let Some(metric) = MetricType::parse(counter.id().as_str()) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
let total = counter.value();
|
|
||||||
let previous = last.insert(metric, (total, 0)).map_or(0, |(count, _)| count);
|
|
||||||
let increase = total.saturating_sub(previous);
|
|
||||||
if increase > 0 {
|
|
||||||
samples.push(Metric::Counter(MetricCount {
|
|
||||||
count: increase,
|
|
||||||
metric,
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// Gauges: the reading, always (MON-5)
|
|
||||||
for gauge in Collector::collect_gauges() {
|
|
||||||
samples.push(Metric::Gauge(MetricCount {
|
|
||||||
count: gauge.get(),
|
|
||||||
metric: gauge.id(),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Histograms: totals, when changed (MON-4 Decision)
|
|
||||||
for histogram in Collector::collect_histograms() {
|
|
||||||
let metric = histogram.id();
|
|
||||||
let current = (histogram.count(), histogram.sum());
|
|
||||||
if last.insert(metric, current) != Some(current) {
|
|
||||||
samples.push(Metric::Histogram(MetricSum {
|
|
||||||
count: current.0,
|
|
||||||
sum: current.1,
|
|
||||||
metric,
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
samples
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The retention settings in force now (MON-3 Decision: no reload needed).
|
|
||||||
pub async fn retention(server: &Server) -> DataRetention {
|
|
||||||
server
|
|
||||||
.registry()
|
|
||||||
.object::<DataRetention>(Id::singleton())
|
|
||||||
.await
|
|
||||||
.ok()
|
|
||||||
.flatten()
|
|
||||||
.unwrap_or_default()
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Server {
|
|
||||||
/// Writes one tick of metric history, if it's on (MON-4, MON-9). Never
|
|
||||||
/// fails loudly: history is lost, mail isn't (MON-35).
|
|
||||||
pub async fn store_metrics(&self) {
|
|
||||||
let store = self.metrics_store();
|
|
||||||
if store.is_none() {
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
let samples = sample();
|
|
||||||
let count = samples.len();
|
|
||||||
let started = std::time::Instant::now();
|
|
||||||
match store.write_metrics(samples, now()).await {
|
|
||||||
Ok(()) => trc::event!(
|
|
||||||
Telemetry(TelemetryEvent::MetricsStored),
|
|
||||||
Total = count,
|
|
||||||
Elapsed = started.elapsed(),
|
|
||||||
),
|
|
||||||
Err(err) => {
|
|
||||||
trc::error!(err.details("Failed to store metric history"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The stored samples between two ids, in key order, skipping any that
|
|
||||||
/// can't be decoded or are past `holdMetricsFor` (MON-17).
|
|
||||||
pub async fn read_metrics(
|
|
||||||
&self,
|
|
||||||
from_id: u64,
|
|
||||||
to_id: u64,
|
|
||||||
ascending: bool,
|
|
||||||
mut accept: impl FnMut(&StoredMetric) -> bool + Send + Sync,
|
|
||||||
) -> trc::Result<Vec<StoredMetric>> {
|
|
||||||
let store = self.metrics_store();
|
|
||||||
let mut out = Vec::new();
|
|
||||||
if store.is_none() {
|
|
||||||
return Ok(out);
|
|
||||||
}
|
|
||||||
let floor = match retention(self).await.hold_metrics_for {
|
|
||||||
Some(keep) => SnowflakeIdGenerator::from_duration(keep.into_inner()).unwrap_or(0),
|
|
||||||
None => 0,
|
|
||||||
};
|
|
||||||
let from_id = from_id.max(floor);
|
|
||||||
if from_id > to_id {
|
|
||||||
return Ok(out);
|
|
||||||
}
|
|
||||||
let params = IterateParams::new(
|
|
||||||
ValueKey::from(ValueClass::Telemetry(TelemetryClass::Metric(from_id))),
|
|
||||||
ValueKey::from(ValueClass::Telemetry(TelemetryClass::Metric(to_id))),
|
|
||||||
);
|
|
||||||
let params = if ascending {
|
|
||||||
params.ascending()
|
|
||||||
} else {
|
|
||||||
params.descending()
|
|
||||||
};
|
|
||||||
store
|
|
||||||
.iterate(params, |key, value| {
|
|
||||||
let id = key.deserialize_be_u64(0)?;
|
|
||||||
if let Some(metric) = decode_metric(value) {
|
|
||||||
let sample = StoredMetric { id, metric };
|
|
||||||
if accept(&sample) {
|
|
||||||
out.push(sample);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Ok(true)
|
|
||||||
})
|
|
||||||
.await
|
|
||||||
.caused_by(trc::location!())?;
|
|
||||||
Ok(out)
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Test data for the shared metrics suite: 90 days of hourly ticks, a
|
|
||||||
/// counter, a gauge and a histogram each.
|
|
||||||
#[cfg(feature = "test_mode")]
|
|
||||||
pub async fn insert_test_metrics(&self) {
|
|
||||||
let now = now();
|
|
||||||
for hour in (0..90 * 24u64).rev() {
|
|
||||||
let samples = vec![
|
|
||||||
Metric::Counter(MetricCount {
|
|
||||||
count: 1 + hour % 7,
|
|
||||||
metric: MetricType::AuthSuccess,
|
|
||||||
}),
|
|
||||||
Metric::Gauge(MetricCount {
|
|
||||||
count: 20 + hour % 11,
|
|
||||||
metric: MetricType::QueueCount,
|
|
||||||
}),
|
|
||||||
Metric::Histogram(MetricSum {
|
|
||||||
count: 100 + hour,
|
|
||||||
sum: 1000 + hour * 10,
|
|
||||||
metric: MetricType::DeliveryTotalTime,
|
|
||||||
}),
|
|
||||||
];
|
|
||||||
self.metrics_store()
|
|
||||||
.write_metrics(samples, now - hour * 3600)
|
|
||||||
.await
|
|
||||||
.unwrap();
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
@@ -2,11 +2,8 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
pub mod alerts; // inbuxa: monitoring (MON-25 to MON-30)
|
|
||||||
pub mod metrics;
|
pub mod metrics;
|
||||||
pub mod tracers;
|
pub mod tracers;
|
||||||
pub mod webhooks;
|
pub mod webhooks;
|
||||||
@@ -20,13 +17,14 @@ use webhooks::spawn_webhook_tracer;
|
|||||||
use crate::config::telemetry::{Telemetry, TelemetrySubscriberType};
|
use crate::config::telemetry::{Telemetry, TelemetrySubscriberType};
|
||||||
|
|
||||||
impl Telemetry {
|
impl Telemetry {
|
||||||
pub fn enable(self) {
|
pub fn enable(self, is_enterprise: bool) {
|
||||||
// Spawn tracers
|
// Spawn tracers
|
||||||
for tracer in self.tracers.subscribers {
|
for tracer in self.tracers.subscribers {
|
||||||
tracer.typ.spawn(
|
tracer.typ.spawn(
|
||||||
SubscriberBuilder::new(tracer.id)
|
SubscriberBuilder::new(tracer.id)
|
||||||
.with_interests(tracer.interests)
|
.with_interests(tracer.interests)
|
||||||
.with_lossy(tracer.lossy),
|
.with_lossy(tracer.lossy),
|
||||||
|
is_enterprise,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -37,7 +35,7 @@ impl Telemetry {
|
|||||||
Collector::reload();
|
Collector::reload();
|
||||||
}
|
}
|
||||||
|
|
||||||
pub fn update(self) {
|
pub fn update(self, is_enterprise: bool) {
|
||||||
// Remove tracers that are no longer active
|
// Remove tracers that are no longer active
|
||||||
let active_subscribers = Collector::get_subscribers();
|
let active_subscribers = Collector::get_subscribers();
|
||||||
for subscribed_id in &active_subscribers {
|
for subscribed_id in &active_subscribers {
|
||||||
@@ -60,6 +58,7 @@ impl Telemetry {
|
|||||||
SubscriberBuilder::new(tracer.id)
|
SubscriberBuilder::new(tracer.id)
|
||||||
.with_interests(tracer.interests)
|
.with_interests(tracer.interests)
|
||||||
.with_lossy(tracer.lossy),
|
.with_lossy(tracer.lossy),
|
||||||
|
is_enterprise,
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@@ -97,7 +96,7 @@ impl Telemetry {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl TelemetrySubscriberType {
|
impl TelemetrySubscriberType {
|
||||||
pub fn spawn(self, builder: SubscriberBuilder) {
|
pub fn spawn(self, builder: SubscriberBuilder, is_enterprise: bool) {
|
||||||
match self {
|
match self {
|
||||||
TelemetrySubscriberType::ConsoleTracer(settings) => {
|
TelemetrySubscriberType::ConsoleTracer(settings) => {
|
||||||
spawn_console_tracer(builder, settings)
|
spawn_console_tracer(builder, settings)
|
||||||
@@ -105,10 +104,6 @@ impl TelemetrySubscriberType {
|
|||||||
TelemetrySubscriberType::LogTracer(settings) => spawn_log_tracer(builder, settings),
|
TelemetrySubscriberType::LogTracer(settings) => spawn_log_tracer(builder, settings),
|
||||||
TelemetrySubscriberType::Webhook(settings) => spawn_webhook_tracer(builder, settings),
|
TelemetrySubscriberType::Webhook(settings) => spawn_webhook_tracer(builder, settings),
|
||||||
TelemetrySubscriberType::OtelTracer(settings) => spawn_otel_tracer(builder, settings),
|
TelemetrySubscriberType::OtelTracer(settings) => spawn_otel_tracer(builder, settings),
|
||||||
// inbuxa: MON-10: trace history
|
|
||||||
TelemetrySubscriberType::StoreTracer(settings) => {
|
|
||||||
tracers::store::spawn_store_tracer(builder, settings.tracing, settings.data)
|
|
||||||
}
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
TelemetrySubscriberType::JournalTracer(subscriber) => {
|
TelemetrySubscriberType::JournalTracer(subscriber) => {
|
||||||
tracers::journald::spawn_journald_tracer(builder, subscriber)
|
tracers::journald::spawn_journald_tracer(builder, subscriber)
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
#[cfg(unix)]
|
#[cfg(unix)]
|
||||||
@@ -11,7 +9,6 @@ pub mod journald;
|
|||||||
pub mod log;
|
pub mod log;
|
||||||
pub mod otel;
|
pub mod otel;
|
||||||
pub mod stdout;
|
pub mod stdout;
|
||||||
pub mod store; // inbuxa: monitoring history (MON-10 to MON-17)
|
|
||||||
|
|
||||||
|
|
||||||
use registry::{
|
use registry::{
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::{LONG_1Y_SLUMBER, config::telemetry::OtelTracer};
|
use crate::{LONG_1Y_SLUMBER, config::telemetry::OtelTracer};
|
||||||
@@ -30,11 +28,11 @@ pub(crate) fn spawn_otel_tracer(builder: SubscriberBuilder, mut otel: OtelTracer
|
|||||||
tokio::spawn(async move {
|
tokio::spawn(async move {
|
||||||
let resource = Resource::builder()
|
let resource = Resource::builder()
|
||||||
.with_service_name("stalwart")
|
.with_service_name("stalwart")
|
||||||
.with_attribute(KeyValue::new(SERVICE_VERSION, types::brand_version_full!()))
|
.with_attribute(KeyValue::new(SERVICE_VERSION, env!("CARGO_PKG_VERSION")))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
let instrumentation = InstrumentationScope::builder("stalwart")
|
let instrumentation = InstrumentationScope::builder("stalwart")
|
||||||
.with_version(types::brand_version_full!())
|
.with_version(env!("CARGO_PKG_VERSION"))
|
||||||
.build();
|
.build();
|
||||||
|
|
||||||
otel.log_exporter.set_resource(&resource);
|
otel.log_exporter.set_resource(&resource);
|
||||||
|
|||||||
@@ -1,228 +0,0 @@
|
|||||||
/*
|
|
||||||
* SPDX-FileCopyrightText: 2026 Coffey Labs
|
|
||||||
*
|
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only
|
|
||||||
*/
|
|
||||||
|
|
||||||
//! Trace history (monitoring spec MON-10 to MON-17, MON-34). A lossy
|
|
||||||
//! collector subscriber gathers each inbound SMTP session and delivery
|
|
||||||
//! attempt, and writes it once, when the span closes, as an `x:Trace` in the
|
|
||||||
//! registry's own encoding under `TelemetryClass::Span(span_id)`.
|
|
||||||
|
|
||||||
use crate::telemetry::tracers::TraceEvents;
|
|
||||||
use ahash::AHashMap;
|
|
||||||
use registry::{
|
|
||||||
pickle::PickledStream,
|
|
||||||
schema::{
|
|
||||||
prelude::{ObjectInner, ObjectType},
|
|
||||||
structs::{
|
|
||||||
Task, TaskIndexTrace, TaskStatus, Trace, TraceKeyValue, TraceValue,
|
|
||||||
TraceValueString, TraceValueUnsignedInt,
|
|
||||||
},
|
|
||||||
},
|
|
||||||
};
|
|
||||||
use std::{future::Future, sync::Arc, time::Duration};
|
|
||||||
use store::{
|
|
||||||
SearchStore, Store, ValueKey,
|
|
||||||
search::{SearchFilter, SearchQuery},
|
|
||||||
write::{BatchBuilder, SearchIndex, TelemetryClass, ValueClass, now},
|
|
||||||
};
|
|
||||||
use trc::{
|
|
||||||
AddContext, DeliveryEvent, Event, EventDetails, EventType, Key, Level, SmtpEvent,
|
|
||||||
ipc::subscriber::SubscriberBuilder,
|
|
||||||
};
|
|
||||||
use utils::snowflake::SnowflakeIdGenerator;
|
|
||||||
|
|
||||||
/// Events kept per trace (MON-15).
|
|
||||||
pub const MAX_EVENTS: usize = 1000;
|
|
||||||
/// The longest string value kept (MON-15).
|
|
||||||
pub const MAX_STRING: usize = 4096;
|
|
||||||
/// A span still open after this is dropped (MON-13).
|
|
||||||
const SPAN_MAX_HOLD: u64 = 86_400;
|
|
||||||
|
|
||||||
pub trait TracingStore: Sync + Send {
|
|
||||||
/// Deletes traces older than `keep`, and their search documents
|
|
||||||
/// (MON-17).
|
|
||||||
fn purge_spans(
|
|
||||||
&self,
|
|
||||||
keep: Duration,
|
|
||||||
search: Option<&SearchStore>,
|
|
||||||
) -> impl Future<Output = trc::Result<()>> + Send;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl TracingStore for Store {
|
|
||||||
async fn purge_spans(&self, keep: Duration, search: Option<&SearchStore>) -> trc::Result<()> {
|
|
||||||
let Some(until) = SnowflakeIdGenerator::from_duration(keep) else {
|
|
||||||
return Ok(());
|
|
||||||
};
|
|
||||||
self.delete_range(
|
|
||||||
ValueKey::from(ValueClass::Telemetry(TelemetryClass::Span(0))),
|
|
||||||
ValueKey::from(ValueClass::Telemetry(TelemetryClass::Span(until))),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.caused_by(trc::location!())?;
|
|
||||||
if let Some(search) = search {
|
|
||||||
search
|
|
||||||
.unindex(
|
|
||||||
SearchQuery::new(SearchIndex::Tracing)
|
|
||||||
.with_filter(SearchFilter::lt(store::search::SearchField::Id, until)),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
.caused_by(trc::location!())?;
|
|
||||||
}
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Decodes a stored trace; `None` for records in any other encoding.
|
|
||||||
pub fn decode_trace(bytes: &[u8]) -> Option<Trace> {
|
|
||||||
PickledStream::new(bytes)
|
|
||||||
.and_then(|mut stream| ObjectInner::unpickle(ObjectType::Trace, &mut stream))
|
|
||||||
.and_then(|inner| match inner {
|
|
||||||
ObjectInner::Trace(trace) => Some(trace),
|
|
||||||
_ => None,
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A stored trace as read by key: `None` when it can't be decoded.
|
|
||||||
pub struct MaybeTrace(pub Option<Trace>);
|
|
||||||
|
|
||||||
impl store::Deserialize for MaybeTrace {
|
|
||||||
fn deserialize(bytes: &[u8]) -> trc::Result<Self> {
|
|
||||||
Ok(MaybeTrace(decode_trace(bytes)))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_stored_span(event: EventType) -> bool {
|
|
||||||
matches!(
|
|
||||||
event,
|
|
||||||
EventType::Smtp(SmtpEvent::ConnectionStart) | EventType::Delivery(DeliveryEvent::AttemptStart)
|
|
||||||
)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn is_mail_from(event: EventType) -> bool {
|
|
||||||
event.as_str().starts_with("smtp.mail-from") || event == EventType::Smtp(SmtpEvent::MultipleMailFrom)
|
|
||||||
}
|
|
||||||
|
|
||||||
struct Span {
|
|
||||||
started: u64,
|
|
||||||
is_smtp: bool,
|
|
||||||
has_mail_from: bool,
|
|
||||||
events: Vec<Arc<Event<EventDetails>>>,
|
|
||||||
cut: usize,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn truncate_values_list(values: &mut registry::types::list::List<TraceKeyValue>) {
|
|
||||||
for kv in values.values_mut() {
|
|
||||||
match &mut kv.value {
|
|
||||||
TraceValue::String(TraceValueString { value }) if value.len() > MAX_STRING => {
|
|
||||||
let mut end = MAX_STRING;
|
|
||||||
while !value.is_char_boundary(end) {
|
|
||||||
end -= 1;
|
|
||||||
}
|
|
||||||
value.truncate(end);
|
|
||||||
}
|
|
||||||
TraceValue::Event(event) => truncate_values_list(&mut event.value),
|
|
||||||
_ => {}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// The trace a closed span leaves (MON-12, MON-15).
|
|
||||||
fn build_trace(span: &Span) -> Trace {
|
|
||||||
let mut trace = Trace::from_events(span.events.iter().map(|e| e.as_ref()), span.events.len());
|
|
||||||
for event in trace.events.values_mut() {
|
|
||||||
truncate_values_list(&mut event.key_values);
|
|
||||||
}
|
|
||||||
if span.cut > 0
|
|
||||||
&& let Some(last) = trace.events.values_mut().last()
|
|
||||||
{
|
|
||||||
// The count of events cut rides on the closing event
|
|
||||||
last.key_values.push(TraceKeyValue {
|
|
||||||
key: Key::Total,
|
|
||||||
value: TraceValue::UnsignedInt(TraceValueUnsignedInt {
|
|
||||||
value: span.cut as u64,
|
|
||||||
}),
|
|
||||||
});
|
|
||||||
}
|
|
||||||
trace
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Starts the subscriber that stores traces in `tracing`, scheduling their
|
|
||||||
/// indexing in `data` (MON-16). Lossy: a slow store loses history, never
|
|
||||||
/// delays mail (MON-34, MON-35).
|
|
||||||
pub(crate) fn spawn_store_tracer(builder: SubscriberBuilder, tracing: Store, data: Store) {
|
|
||||||
let (_, mut rx) = builder.register();
|
|
||||||
tokio::spawn(async move {
|
|
||||||
let mut spans: AHashMap<u64, Span> = AHashMap::new();
|
|
||||||
while let Some(events) = rx.recv().await {
|
|
||||||
let mut closed = Vec::new();
|
|
||||||
for event in events {
|
|
||||||
let typ = event.inner.typ;
|
|
||||||
let Some(span_id) = event.span_id() else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
if is_stored_span(typ) {
|
|
||||||
spans.insert(
|
|
||||||
span_id,
|
|
||||||
Span {
|
|
||||||
started: event.inner.timestamp,
|
|
||||||
is_smtp: matches!(typ, EventType::Smtp(_)),
|
|
||||||
has_mail_from: false,
|
|
||||||
events: vec![event],
|
|
||||||
cut: 0,
|
|
||||||
},
|
|
||||||
);
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
let Some(span) = spans.get_mut(&span_id) else {
|
|
||||||
continue;
|
|
||||||
};
|
|
||||||
if is_mail_from(typ) {
|
|
||||||
span.has_mail_from = true;
|
|
||||||
}
|
|
||||||
let is_end = typ.is_span_end();
|
|
||||||
// MON-12: info and above, never raw I/O
|
|
||||||
if !typ.is_raw_io() && (is_end || event.inner.level as usize >= Level::Info as usize) {
|
|
||||||
if span.events.len() < MAX_EVENTS - 1 || is_end {
|
|
||||||
span.events.push(event);
|
|
||||||
} else {
|
|
||||||
span.cut += 1;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if is_end && let Some(span) = spans.remove(&span_id) {
|
|
||||||
// MON-11: a session that never reached MAIL FROM isn't kept
|
|
||||||
if !span.is_smtp || span.has_mail_from {
|
|
||||||
closed.push((span_id, span));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if !closed.is_empty() {
|
|
||||||
let mut batch = BatchBuilder::new();
|
|
||||||
let mut tasks = BatchBuilder::new();
|
|
||||||
for (span_id, span) in &closed {
|
|
||||||
batch.set(
|
|
||||||
ValueClass::Telemetry(TelemetryClass::Span(*span_id)),
|
|
||||||
ObjectInner::Trace(build_trace(span)).to_pickled_vec(),
|
|
||||||
);
|
|
||||||
tasks.schedule_task(Task::IndexTrace(TaskIndexTrace {
|
|
||||||
trace_id: (*span_id).into(),
|
|
||||||
status: TaskStatus::now(),
|
|
||||||
}));
|
|
||||||
}
|
|
||||||
if let Err(err) = tracing.write(batch.build_all()).await {
|
|
||||||
trc::error!(err.details("Failed to store trace history"));
|
|
||||||
} else if let Err(err) = data.write(tasks.build_all()).await {
|
|
||||||
trc::error!(err.details("Failed to schedule trace indexing"));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
// MON-13: spans open for over a day are dropped
|
|
||||||
if spans.len() > 1000 {
|
|
||||||
let now = now();
|
|
||||||
spans.retain(|_, span| now.saturating_sub(span.started) < SPAN_MAX_HOLD);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "coordinator"
|
name = "coordinator"
|
||||||
version = "0.16.22"
|
version = "0.16.23"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
|||||||
@@ -2,14 +2,8 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// inbuxa: composite stores (sharded members, read replicas) nest store
|
|
||||||
// futures deeply enough to pass rustc's default query depth
|
|
||||||
#![recursion_limit = "512"]
|
|
||||||
|
|
||||||
#![warn(clippy::large_futures)]
|
#![warn(clippy::large_futures)]
|
||||||
|
|
||||||
#[allow(unused_imports)]
|
#[allow(unused_imports)]
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "dav-proto"
|
name = "dav-proto"
|
||||||
version = "0.16.22"
|
version = "0.16.23"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "dav"
|
name = "dav"
|
||||||
version = "0.16.22"
|
version = "0.16.23"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use super::ArchivedResource;
|
use super::ArchivedResource;
|
||||||
@@ -139,26 +137,6 @@ impl DavAclHandler for Server {
|
|||||||
.validate_and_map_aces(access_token, request, collection)
|
.validate_and_map_aces(access_token, request, collection)
|
||||||
.await?;
|
.await?;
|
||||||
|
|
||||||
// inbuxa: MT-3: grants stay within the owner's tenant
|
|
||||||
let tenant_id = self
|
|
||||||
.try_account(account_id)
|
|
||||||
.await
|
|
||||||
.caused_by(trc::location!())?
|
|
||||||
.and_then(|owner| owner.id_tenant);
|
|
||||||
for grant in &grants {
|
|
||||||
if self
|
|
||||||
.try_account(grant.account_id)
|
|
||||||
.await
|
|
||||||
.caused_by(trc::location!())?
|
|
||||||
.is_none_or(|grantee| grantee.id_tenant != tenant_id)
|
|
||||||
{
|
|
||||||
return Err(DavError::Condition(DavErrorCondition::new(
|
|
||||||
StatusCode::FORBIDDEN,
|
|
||||||
BaseCondition::AllowedPrincipal,
|
|
||||||
)));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if grants.len() != acls.len() || acls.iter().zip(grants.iter()).any(|(a, b)| a != b) {
|
if grants.len() != acls.len() || acls.iter().zip(grants.iter()).any(|(a, b)| a != b) {
|
||||||
// Refresh ACLs
|
// Refresh ACLs
|
||||||
self.refresh_archived_acls(&grants, acls)
|
self.refresh_archived_acls(&grants, acls)
|
||||||
|
|||||||
@@ -2,13 +2,7 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// inbuxa: composite stores (sharded members, read replicas) nest store
|
|
||||||
// futures deeply enough to pass rustc's default query depth
|
|
||||||
#![recursion_limit = "512"]
|
|
||||||
#![warn(clippy::large_futures)]
|
#![warn(clippy::large_futures)]
|
||||||
|
|
||||||
pub mod calendar;
|
pub mod calendar;
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -76,19 +74,9 @@ pub(crate) trait DavRequestDispatcher: Sync + Send {
|
|||||||
method: DavMethod,
|
method: DavMethod,
|
||||||
body: Vec<u8>,
|
body: Vec<u8>,
|
||||||
) -> impl Future<Output = crate::Result<HttpResponse>> + Send;
|
) -> impl Future<Output = crate::Result<HttpResponse>> + Send;
|
||||||
|
|
||||||
fn dispatch_dav_inner(
|
|
||||||
&self,
|
|
||||||
headers: &RequestHeaders<'_>,
|
|
||||||
access_token: AccessToken,
|
|
||||||
resource: DavResourceName,
|
|
||||||
method: DavMethod,
|
|
||||||
body: Vec<u8>,
|
|
||||||
) -> impl Future<Output = crate::Result<HttpResponse>> + Send;
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl DavRequestDispatcher for Server {
|
impl DavRequestDispatcher for Server {
|
||||||
// inbuxa: ST-6: GET, PROPFIND and REPORT may be served by a read replica
|
|
||||||
async fn dispatch_dav_request(
|
async fn dispatch_dav_request(
|
||||||
&self,
|
&self,
|
||||||
headers: &RequestHeaders<'_>,
|
headers: &RequestHeaders<'_>,
|
||||||
@@ -96,33 +84,6 @@ impl DavRequestDispatcher for Server {
|
|||||||
resource: DavResourceName,
|
resource: DavResourceName,
|
||||||
method: DavMethod,
|
method: DavMethod,
|
||||||
body: Vec<u8>,
|
body: Vec<u8>,
|
||||||
) -> crate::Result<HttpResponse> {
|
|
||||||
if matches!(
|
|
||||||
method,
|
|
||||||
DavMethod::GET | DavMethod::HEAD | DavMethod::PROPFIND | DavMethod::REPORT
|
|
||||||
) {
|
|
||||||
let accounts = access_token
|
|
||||||
.all_ids()
|
|
||||||
.map(|account_id| (account_id, 0))
|
|
||||||
.collect::<Vec<_>>();
|
|
||||||
store::backend::scaleout::replica::replica_read(
|
|
||||||
accounts,
|
|
||||||
self.dispatch_dav_inner(headers, access_token, resource, method, body),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
} else {
|
|
||||||
self.dispatch_dav_inner(headers, access_token, resource, method, body)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn dispatch_dav_inner(
|
|
||||||
&self,
|
|
||||||
headers: &RequestHeaders<'_>,
|
|
||||||
access_token: AccessToken,
|
|
||||||
resource: DavResourceName,
|
|
||||||
method: DavMethod,
|
|
||||||
body: Vec<u8>,
|
|
||||||
) -> crate::Result<HttpResponse> {
|
) -> crate::Result<HttpResponse> {
|
||||||
// Dispatch
|
// Dispatch
|
||||||
match method {
|
match method {
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "directory"
|
name = "directory"
|
||||||
version = "0.16.22"
|
version = "0.16.23"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::Directory;
|
use crate::Directory;
|
||||||
@@ -40,7 +38,7 @@ impl OpenIdDirectory {
|
|||||||
|
|
||||||
pub async fn new(config: OidcConfig) -> Result<Self, OidcError> {
|
pub async fn new(config: OidcConfig) -> Result<Self, OidcError> {
|
||||||
let http = utils::http::http_client_builder(false)
|
let http = utils::http::http_client_builder(false)
|
||||||
.user_agent("INBUXA/1.0") // types::brand!(); this crate does not depend on types
|
.user_agent("Stalwart/1.0")
|
||||||
.timeout(Duration::from_secs(30))
|
.timeout(Duration::from_secs(30))
|
||||||
.build()
|
.build()
|
||||||
.map_err(|e| OidcError::Network(format!("HTTP client build failed: {e}")))?;
|
.map_err(|e| OidcError::Network(format!("HTTP client build failed: {e}")))?;
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -35,10 +33,7 @@ impl OpenIdDirectory {
|
|||||||
self.authenticate_opaque(token).await
|
self.authenticate_opaque(token).await
|
||||||
}
|
}
|
||||||
.map_err(|err| match err {
|
.map_err(|err| match err {
|
||||||
// inbuxa: DIR-30: a refused token is an authentication
|
OidcError::AuthorizationFailed(reason) => {
|
||||||
// failure and counts toward the sign-in ban; a network,
|
|
||||||
// provider or configuration fault is an error and doesn't
|
|
||||||
OidcError::AuthorizationFailed(reason) | OidcError::TokenValidation(reason) => {
|
|
||||||
AuthEvent::Failed.into_err().reason(reason)
|
AuthEvent::Failed.into_err().reason(reason)
|
||||||
}
|
}
|
||||||
err => AuthEvent::Error.into_err().reason(err),
|
err => AuthEvent::Error.into_err().reason(err),
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
@@ -35,9 +33,7 @@ impl Directories {
|
|||||||
let directory = match result {
|
let directory = match result {
|
||||||
Ok(directory) => directory,
|
Ok(directory) => directory,
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
// inbuxa: DIR-21: logged against the directory, which becomes
|
bp.build_error(id, err.clone());
|
||||||
// unavailable; the rest of the reload carries on
|
|
||||||
bp.build_warning(id, err.clone());
|
|
||||||
Directory::Unavailable(UnavailableDirectory::new(directory_type, err))
|
Directory::Unavailable(UnavailableDirectory::new(directory_type, err))
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
@@ -49,16 +45,11 @@ impl Directories {
|
|||||||
match directories.get(&(directory_id.id() as u32)) {
|
match directories.get(&(directory_id.id() as u32)) {
|
||||||
Some(default_directory) => default_directory.clone().into(),
|
Some(default_directory) => default_directory.clone().into(),
|
||||||
None => {
|
None => {
|
||||||
bp.build_warning(
|
bp.build_error(
|
||||||
ObjectType::Authentication.singleton(),
|
ObjectType::Authentication.singleton(),
|
||||||
format!("Default directory with ID {} not found", directory_id),
|
format!("Default directory with ID {} not found", directory_id),
|
||||||
);
|
);
|
||||||
// inbuxa: DIR-5: a missing default is unavailable, never the
|
None
|
||||||
// internal directory
|
|
||||||
Some(Arc::new(Directory::Unavailable(UnavailableDirectory::new(
|
|
||||||
registry::schema::enums::DirectoryType::Ldap,
|
|
||||||
format!("Default directory with ID {} not found", directory_id),
|
|
||||||
))))
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
} else {
|
} else {
|
||||||
|
|||||||
@@ -2,14 +2,8 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// inbuxa: composite stores (sharded members, read replicas) nest store
|
|
||||||
// futures deeply enough to pass rustc's default query depth
|
|
||||||
#![recursion_limit = "512"]
|
|
||||||
|
|
||||||
#![warn(clippy::large_futures)]
|
#![warn(clippy::large_futures)]
|
||||||
|
|
||||||
use crate::backend::oidc::OpenIdDirectory;
|
use crate::backend::oidc::OpenIdDirectory;
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "email"
|
name = "email"
|
||||||
version = "0.16.22"
|
version = "0.16.23"
|
||||||
edition = "2024"
|
edition = "2024"
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
@@ -14,7 +14,6 @@ jmap-tools = { version = "0.1" }
|
|||||||
common = { path = "../common" }
|
common = { path = "../common" }
|
||||||
groupware = { path = "../groupware" }
|
groupware = { path = "../groupware" }
|
||||||
registry = { path = "../registry" }
|
registry = { path = "../registry" }
|
||||||
inbuxa-features = { path = "../features" }
|
|
||||||
mail-parser = { version = "0.11", features = ["full_encoding"] }
|
mail-parser = { version = "0.11", features = ["full_encoding"] }
|
||||||
mail-builder = { version = "1.0" }
|
mail-builder = { version = "1.0" }
|
||||||
sieve-rs = { version = "0.7", features = ["rkyv"] }
|
sieve-rs = { version = "0.7", features = ["rkyv"] }
|
||||||
|
|||||||
@@ -2,14 +2,8 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
// inbuxa: composite stores (sharded members, read replicas) nest store
|
|
||||||
// futures deeply enough to pass rustc's default query depth
|
|
||||||
#![recursion_limit = "512"]
|
|
||||||
|
|
||||||
#![warn(clippy::large_futures)]
|
#![warn(clippy::large_futures)]
|
||||||
|
|
||||||
pub mod cache;
|
pub mod cache;
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
@@ -92,10 +90,6 @@ impl MailboxDestroy for Server {
|
|||||||
|
|
||||||
let mut deleted_ids = RoaringBitmap::new();
|
let mut deleted_ids = RoaringBitmap::new();
|
||||||
let mut thread_ids = RoaringBitmap::new();
|
let mut thread_ids = RoaringBitmap::new();
|
||||||
// inbuxa: UD-1, UD-6a: the retention in force now
|
|
||||||
let retention = inbuxa_features::undelete::settings::retention(self.registry())
|
|
||||||
.await?
|
|
||||||
.items;
|
|
||||||
self.archives(
|
self.archives(
|
||||||
account_id,
|
account_id,
|
||||||
Collection::Email,
|
Collection::Email,
|
||||||
@@ -124,20 +118,6 @@ impl MailboxDestroy for Server {
|
|||||||
}
|
}
|
||||||
deleted_ids.insert(message_id);
|
deleted_ids.insert(message_id);
|
||||||
thread_ids.insert(prev_message_data.inner.thread_id.to_native());
|
thread_ids.insert(prev_message_data.inner.thread_id.to_native());
|
||||||
// inbuxa: UD-1, UD-4: a deleted message is noted for archiving
|
|
||||||
if let Some(retention) = retention {
|
|
||||||
inbuxa_features::undelete::email::note(
|
|
||||||
&mut batch,
|
|
||||||
retention,
|
|
||||||
account_id,
|
|
||||||
message_id,
|
|
||||||
prev_message_data.inner.size.to_native() as u64,
|
|
||||||
prev_message_data.inner.mailboxes.iter().map(|m| m.mailbox_id.to_native()).collect(),
|
|
||||||
inbuxa_features::undelete::email::keywords_to_keep(
|
|
||||||
prev_message_data.inner.keywords.iter().map(|k| k.to_string()),
|
|
||||||
),
|
|
||||||
)?;
|
|
||||||
}
|
|
||||||
batch
|
batch
|
||||||
.with_collection(Collection::Email)
|
.with_collection(Collection::Email)
|
||||||
.with_document(message_id)
|
.with_document(message_id)
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use aes::cipher::{BlockModeEncrypt, KeyIvInit, block_padding::Pkcs7};
|
use aes::cipher::{BlockModeEncrypt, KeyIvInit, block_padding::Pkcs7};
|
||||||
@@ -112,7 +110,7 @@ impl EncryptMessage for Message<'_> {
|
|||||||
outer_message.extend_from_slice(
|
outer_message.extend_from_slice(
|
||||||
concat!(
|
concat!(
|
||||||
"\"\r\n\r\n",
|
"\"\r\n\r\n",
|
||||||
concat!("OpenPGP/MIME message (Automatically encrypted by ", types::brand!(), ")\r\n\r\n"),
|
"OpenPGP/MIME message (Automatically encrypted by Stalwart)\r\n\r\n",
|
||||||
"--"
|
"--"
|
||||||
)
|
)
|
||||||
.as_bytes(),
|
.as_bytes(),
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use super::metadata::MessageData;
|
use super::metadata::MessageData;
|
||||||
@@ -69,10 +67,6 @@ impl EmailDeletion for Server {
|
|||||||
batch
|
batch
|
||||||
.with_account_id(account_id)
|
.with_account_id(account_id)
|
||||||
.with_collection(Collection::Email);
|
.with_collection(Collection::Email);
|
||||||
// inbuxa: UD-1, UD-6a: the retention in force now
|
|
||||||
let retention = inbuxa_features::undelete::settings::retention(self.registry())
|
|
||||||
.await?
|
|
||||||
.items;
|
|
||||||
self.archives(
|
self.archives(
|
||||||
account_id,
|
account_id,
|
||||||
Collection::Email,
|
Collection::Email,
|
||||||
@@ -89,20 +83,6 @@ impl EmailDeletion for Server {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
thread_ids.insert(metadata.inner.thread_id.to_native());
|
thread_ids.insert(metadata.inner.thread_id.to_native());
|
||||||
// inbuxa: UD-1, UD-4: a deleted message is noted for archiving
|
|
||||||
if let Some(retention) = retention {
|
|
||||||
inbuxa_features::undelete::email::note(
|
|
||||||
batch,
|
|
||||||
retention,
|
|
||||||
account_id,
|
|
||||||
document_id,
|
|
||||||
metadata.inner.size.to_native() as u64,
|
|
||||||
metadata.inner.mailboxes.iter().map(|m| m.mailbox_id.to_native()).collect(),
|
|
||||||
inbuxa_features::undelete::email::keywords_to_keep(
|
|
||||||
metadata.inner.keywords.iter().map(|k| k.to_string()),
|
|
||||||
),
|
|
||||||
)?;
|
|
||||||
}
|
|
||||||
batch
|
batch
|
||||||
.with_document(document_id)
|
.with_document(document_id)
|
||||||
.custom(
|
.custom(
|
||||||
|
|||||||
@@ -2,15 +2,10 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use super::ingest::{EmailIngest, IngestEmail, IngestSource};
|
use super::ingest::{EmailIngest, IngestEmail, IngestSource};
|
||||||
use crate::{
|
use crate::{mailbox::INBOX_ID, sieve::ingest::SieveScriptIngest};
|
||||||
mailbox::{INBOX_ID, TRASH_ID},
|
|
||||||
sieve::ingest::SieveScriptIngest,
|
|
||||||
};
|
|
||||||
use common::{
|
use common::{
|
||||||
Server,
|
Server,
|
||||||
auth::BuildAccessToken,
|
auth::BuildAccessToken,
|
||||||
@@ -22,6 +17,8 @@ use std::{borrow::Cow, future::Future};
|
|||||||
use store::ahash::AHashMap;
|
use store::ahash::AHashMap;
|
||||||
use types::blob_hash::BlobHash;
|
use types::blob_hash::BlobHash;
|
||||||
|
|
||||||
|
pub const ORCPT_ADDR_TYPE: &str = "rfc822;";
|
||||||
|
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct IngestMessage {
|
pub struct IngestMessage {
|
||||||
pub sender_address: String,
|
pub sender_address: String,
|
||||||
@@ -40,6 +37,12 @@ pub struct IngestRecipient {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl IngestRecipient {
|
impl IngestRecipient {
|
||||||
|
pub fn orcpt_parameter(&self) -> Option<String> {
|
||||||
|
self.orcpt
|
||||||
|
.as_deref()
|
||||||
|
.map(|orcpt| format!("{ORCPT_ADDR_TYPE}{orcpt}"))
|
||||||
|
}
|
||||||
|
|
||||||
pub fn is_spam(&self) -> bool {
|
pub fn is_spam(&self) -> bool {
|
||||||
self.spam_percentage
|
self.spam_percentage
|
||||||
.is_some_and(|percentage| percentage >= 50)
|
.is_some_and(|percentage| percentage >= 50)
|
||||||
@@ -131,32 +134,7 @@ impl MailDelivery for Server {
|
|||||||
};
|
};
|
||||||
|
|
||||||
for rcpt in message.recipients {
|
for rcpt in message.recipients {
|
||||||
// inbuxa: ME-4, ME-10: a masked address delivers to its owner
|
let account_id = match self.account_id_from_email(&rcpt.address, false).await {
|
||||||
let mut mask = match inbuxa_features::masked_email::ops::resolve_recipient(
|
|
||||||
&self.core.storage.data,
|
|
||||||
self.registry(),
|
|
||||||
&rcpt.address,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(mask) => mask,
|
|
||||||
Err(err) => {
|
|
||||||
trc::error!(
|
|
||||||
err.details("Failed to look up masked address.")
|
|
||||||
.ctx(trc::Key::To, rcpt.address.to_string())
|
|
||||||
.span_id(message.session_id)
|
|
||||||
);
|
|
||||||
result.status.push(LocalDeliveryStatus::TemporaryFailure {
|
|
||||||
reason: "Address lookup failed.".into(),
|
|
||||||
});
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
};
|
|
||||||
let account_lookup = match &mask {
|
|
||||||
Some(mask) => Ok(Some(mask.object.account_id.document_id())),
|
|
||||||
None => self.account_id_from_email(&rcpt.address, false).await,
|
|
||||||
};
|
|
||||||
let account_id = match account_lookup {
|
|
||||||
Ok(Some(account_id)) => account_id,
|
Ok(Some(account_id)) => account_id,
|
||||||
Ok(None) => {
|
Ok(None) => {
|
||||||
// Something went wrong
|
// Something went wrong
|
||||||
@@ -179,22 +157,6 @@ impl MailDelivery for Server {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
// inbuxa: ME-9: rewritten at RCPT TO, the mask is the original recipient
|
|
||||||
if mask.is_none() {
|
|
||||||
match inbuxa_features::masked_email::ops::resolve_original(
|
|
||||||
&self.core.storage.data,
|
|
||||||
self.registry(),
|
|
||||||
rcpt.orcpt.as_deref(),
|
|
||||||
account_id,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
Ok(original) => mask = original,
|
|
||||||
Err(err) => {
|
|
||||||
trc::error!(err.span_id(message.session_id));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
if let Some(status) = account_ids
|
if let Some(status) = account_ids
|
||||||
.get(&account_id)
|
.get(&account_id)
|
||||||
.and_then(|pos| result.status.get(*pos))
|
.and_then(|pos| result.status.get(*pos))
|
||||||
@@ -203,35 +165,6 @@ impl MailDelivery for Server {
|
|||||||
continue;
|
continue;
|
||||||
}
|
}
|
||||||
|
|
||||||
// inbuxa: ME-9: the message names the mask it came through
|
|
||||||
let masked = match &mask {
|
|
||||||
Some(mask) => {
|
|
||||||
let raw = inbuxa_features::masked_email::ops::with_header(
|
|
||||||
&mask.object.email,
|
|
||||||
&raw_message,
|
|
||||||
);
|
|
||||||
match self.put_temporary_blob(account_id, &raw, 600).await {
|
|
||||||
Ok((hash, _)) => Some((raw, hash)),
|
|
||||||
Err(err) => {
|
|
||||||
trc::error!(err.span_id(message.session_id));
|
|
||||||
result.status.push(LocalDeliveryStatus::TemporaryFailure {
|
|
||||||
reason: "Temporary I/O error.".into(),
|
|
||||||
});
|
|
||||||
continue;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
None => None,
|
|
||||||
};
|
|
||||||
let (raw_message, message_blob) = masked
|
|
||||||
.as_ref()
|
|
||||||
.map(|(raw, hash)| (raw.as_slice(), hash))
|
|
||||||
.unwrap_or((raw_message.as_slice(), &message.message_blob));
|
|
||||||
// inbuxa: ME-5: a disabled mask files straight to Trash
|
|
||||||
let to_trash = mask.as_ref().is_some_and(|mask| {
|
|
||||||
mask.state == inbuxa_features::masked_email::State::Disabled
|
|
||||||
});
|
|
||||||
|
|
||||||
// Obtain access token
|
// Obtain access token
|
||||||
let status = match self.access_token(account_id).await.and_then(|token| {
|
let status = match self.access_token(account_id).await.and_then(|token| {
|
||||||
token
|
token
|
||||||
@@ -240,20 +173,15 @@ impl MailDelivery for Server {
|
|||||||
}) {
|
}) {
|
||||||
Ok(access_token) => {
|
Ok(access_token) => {
|
||||||
// Check if there is an active sieve script
|
// Check if there is an active sieve script
|
||||||
let active_script = if to_trash {
|
match self.sieve_script_get_active(account_id).await {
|
||||||
Ok(None)
|
|
||||||
} else {
|
|
||||||
self.sieve_script_get_active(account_id).await
|
|
||||||
};
|
|
||||||
match active_script {
|
|
||||||
Ok(None) => {
|
Ok(None) => {
|
||||||
// Ingest message
|
// Ingest message
|
||||||
self.email_ingest(IngestEmail {
|
self.email_ingest(IngestEmail {
|
||||||
raw_message,
|
raw_message: &raw_message,
|
||||||
blob_hash: Some(message_blob),
|
blob_hash: Some(&message.message_blob),
|
||||||
message: MessageParser::new().parse(raw_message),
|
message: MessageParser::new().parse(&raw_message),
|
||||||
access_token: &access_token,
|
access_token: &access_token,
|
||||||
mailbox_ids: vec![if to_trash { TRASH_ID } else { INBOX_ID }],
|
mailbox_ids: vec![INBOX_ID],
|
||||||
keywords: vec![],
|
keywords: vec![],
|
||||||
received_at: None,
|
received_at: None,
|
||||||
source: IngestSource::Smtp {
|
source: IngestSource::Smtp {
|
||||||
@@ -268,8 +196,8 @@ impl MailDelivery for Server {
|
|||||||
Ok(Some(active_script)) => {
|
Ok(Some(active_script)) => {
|
||||||
self.sieve_script_ingest(
|
self.sieve_script_ingest(
|
||||||
&access_token,
|
&access_token,
|
||||||
message_blob,
|
&message.message_blob,
|
||||||
raw_message,
|
&raw_message,
|
||||||
&message.sender_address,
|
&message.sender_address,
|
||||||
message.sender_authenticated,
|
message.sender_authenticated,
|
||||||
&rcpt,
|
&rcpt,
|
||||||
@@ -288,18 +216,6 @@ impl MailDelivery for Server {
|
|||||||
|
|
||||||
let status = match status {
|
let status = match status {
|
||||||
Ok(ingested_message) => {
|
Ok(ingested_message) => {
|
||||||
// inbuxa: ME-7: the mask saw mail, and a pending one is now enabled
|
|
||||||
if let Some(mask) = &mask
|
|
||||||
&& let Err(err) = inbuxa_features::masked_email::ops::delivered(
|
|
||||||
&self.core.storage.data,
|
|
||||||
self.registry(),
|
|
||||||
mask,
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
{
|
|
||||||
trc::error!(err.span_id(message.session_id));
|
|
||||||
}
|
|
||||||
|
|
||||||
// Notify state change
|
// Notify state change
|
||||||
if ingested_message.change_id != u64::MAX {
|
if ingested_message.change_id != u64::MAX {
|
||||||
self.broadcast_push_notification(PushNotification::EmailPush(EmailPush {
|
self.broadcast_push_notification(PushNotification::EmailPush(EmailPush {
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use super::SieveScript;
|
use super::SieveScript;
|
||||||
@@ -44,33 +42,6 @@ impl SieveScriptDelete for Server {
|
|||||||
))
|
))
|
||||||
.await?
|
.await?
|
||||||
{
|
{
|
||||||
// inbuxa: UD-1: a deleted script is kept, when archiving is on
|
|
||||||
if let Some(retention) =
|
|
||||||
inbuxa_features::undelete::settings::retention(self.registry())
|
|
||||||
.await?
|
|
||||||
.items
|
|
||||||
{
|
|
||||||
let script = obj_
|
|
||||||
.deserialize::<SieveScript>()
|
|
||||||
.caused_by(trc::location!())?;
|
|
||||||
let content = self
|
|
||||||
.blob_store()
|
|
||||||
.get_blob(script.blob_hash.as_slice(), 0..usize::MAX)
|
|
||||||
.await?
|
|
||||||
.map(|bytes| String::from_utf8_lossy(&bytes).into_owned())
|
|
||||||
.unwrap_or_default();
|
|
||||||
inbuxa_features::undelete::groupware::archive_sieve(
|
|
||||||
&self.core.storage.data,
|
|
||||||
self.registry(),
|
|
||||||
account_id,
|
|
||||||
&script.name,
|
|
||||||
content,
|
|
||||||
script.blob_hash.clone(),
|
|
||||||
retention,
|
|
||||||
)
|
|
||||||
.await?;
|
|
||||||
}
|
|
||||||
|
|
||||||
// Delete record
|
// Delete record
|
||||||
batch
|
batch
|
||||||
.with_account_id(account_id)
|
.with_account_id(account_id)
|
||||||
|
|||||||
@@ -2,8 +2,6 @@
|
|||||||
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
* SPDX-FileCopyrightText: 2020 Stalwart Labs LLC <hello@stalw.art>
|
||||||
*
|
*
|
||||||
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
* SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-SEL
|
||||||
*
|
|
||||||
* Modified by Coffey Labs in 2026 for INBUXA.
|
|
||||||
*/
|
*/
|
||||||
|
|
||||||
use super::{ActiveScript, SeenIdHash, SieveScript};
|
use super::{ActiveScript, SeenIdHash, SieveScript};
|
||||||
@@ -126,6 +124,7 @@ impl SieveScriptIngest for Server {
|
|||||||
.caused_by(trc::location!())?;
|
.caused_by(trc::location!())?;
|
||||||
|
|
||||||
// Create Sieve instance
|
// Create Sieve instance
|
||||||
|
let orcpt = envelope_to.orcpt_parameter();
|
||||||
let mut instance = self.core.sieve.untrusted_runtime.filter_parsed(message);
|
let mut instance = self.core.sieve.untrusted_runtime.filter_parsed(message);
|
||||||
|
|
||||||
// Set account name and email
|
// Set account name and email
|
||||||
@@ -141,7 +140,7 @@ impl SieveScriptIngest for Server {
|
|||||||
// Set envelope
|
// Set envelope
|
||||||
instance.set_envelope(Envelope::From, envelope_from);
|
instance.set_envelope(Envelope::From, envelope_from);
|
||||||
instance.set_envelope(Envelope::To, envelope_to.address.as_str());
|
instance.set_envelope(Envelope::To, envelope_to.address.as_str());
|
||||||
if let Some(orcpt) = &envelope_to.orcpt {
|
if let Some(orcpt) = &orcpt {
|
||||||
instance.set_envelope(Envelope::Orcpt, orcpt.as_str());
|
instance.set_envelope(Envelope::Orcpt, orcpt.as_str());
|
||||||
}
|
}
|
||||||
instance.set_spam_status(spam_status(envelope_to.spam_percentage));
|
instance.set_spam_status(spam_status(envelope_to.spam_percentage));
|
||||||
@@ -781,7 +780,7 @@ impl SieveScriptIngest for Server {
|
|||||||
fn write_received_header(buf: &mut Vec<u8>, hostname: &str, id: u64) {
|
fn write_received_header(buf: &mut Vec<u8>, hostname: &str, id: u64) {
|
||||||
buf.extend_from_slice(b"Received: from localhost (localhost [127.0.0.1])\r\n\tby ");
|
buf.extend_from_slice(b"Received: from localhost (localhost [127.0.0.1])\r\n\tby ");
|
||||||
buf.extend_from_slice(hostname.as_bytes());
|
buf.extend_from_slice(hostname.as_bytes());
|
||||||
buf.extend_from_slice(concat!(" (", types::brand!(), " SMTP) with LMTP id ").as_bytes());
|
buf.extend_from_slice(b" (Stalwart SMTP) with LMTP id ");
|
||||||
buf.extend_from_slice(format!("{id:X}").as_bytes());
|
buf.extend_from_slice(format!("{id:X}").as_bytes());
|
||||||
buf.extend_from_slice(b";\r\n\t");
|
buf.extend_from_slice(b";\r\n\t");
|
||||||
buf.extend_from_slice(Date::now().to_rfc822().as_bytes());
|
buf.extend_from_slice(Date::now().to_rfc822().as_bytes());
|
||||||
|
|||||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user