mirror of
https://github.com/fafhrd91/actix-web
synced 2025-07-03 17:41:30 +02:00
Compare commits
97 Commits
multipart-
...
web-v4.5.0
Author | SHA1 | Date | |
---|---|---|---|
59bc85fe0e | |||
3f2fd2d59f | |||
17ed73b33e | |||
73fa1184f1 | |||
8e9e9fbcdd | |||
8db3de6ede | |||
2125aca2c5 | |||
b1eb57ac4f | |||
ae7736f134 | |||
c1f88f718b | |||
7a76ba7340 | |||
8e458b34b7 | |||
e89c881624 | |||
5246d24aba | |||
643a80bff2 | |||
891ab083c6 | |||
a7375b6876 | |||
ea8cd6e976 | |||
d453b15ddd | |||
2915bb7d90 | |||
e442b00c8c | |||
ba53c4f875 | |||
08a9c66568 | |||
83be07d77d | |||
33da480709 | |||
fcfc727295 | |||
ac04d80d8e | |||
d2bd549eec | |||
46dde69d50 | |||
febba786fa | |||
561cc440b2 | |||
ccb90dd5a1 | |||
1c88af50c0 | |||
f4f459d420 | |||
d14e98b62b | |||
f4851b3914 | |||
68597b5426 | |||
9dc3ad754e | |||
17060ed993 | |||
0d9ca4d939 | |||
ff2904ee78 | |||
fdef224a06 | |||
ede0201aa4 | |||
271edafd4d | |||
5e5e5d8315 | |||
c7a0af31d3 | |||
eefe8b0733 | |||
1114a51b22 | |||
0a312037ea | |||
37d304b0f2 | |||
039f8fb193 | |||
929ceb5eb5 | |||
e95c8fe5a6 | |||
2fe5189954 | |||
4accfab196 | |||
c0615f28ed | |||
9d1f75d349 | |||
e50bceb914 | |||
f5655721aa | |||
989548e36a | |||
7d2349afb9 | |||
b78f6da05f | |||
3b8d4de0e0 | |||
40196f16be | |||
32ddf972c6 | |||
ce18f35e03 | |||
d3d0208cbd | |||
9e51116da2 | |||
3193b81a3e | |||
3acdda48e0 | |||
935d36c441 | |||
05b4c4964f | |||
fba766b4be | |||
76a0385f94 | |||
f1c9b93b87 | |||
55ddded315 | |||
2cfe257fc2 | |||
ccabcd83c0 | |||
13fed45bfa | |||
8bd4b36ffe | |||
801a51b312 | |||
b28e0fff4b | |||
043bc88f73 | |||
e1c48dba26 | |||
835a57afc6 | |||
81ac30f3df | |||
d50eccb3f7 | |||
a7983351be | |||
215a52f565 | |||
d445742974 | |||
76f6106f8f | |||
39abe3ae5e | |||
e6636f1279 | |||
2b40033a9c | |||
d2c0d472e9 | |||
45fdc08788 | |||
a12d39c93e |
@ -1,6 +1,6 @@
|
||||
[alias]
|
||||
lint = "clippy --workspace --tests --examples --bins -- -Dclippy::todo"
|
||||
lint-all = "clippy --workspace --all-features --tests --examples --bins -- -Dclippy::todo"
|
||||
lint = "clippy --workspace --all-targets -- -Dclippy::todo"
|
||||
lint-all = "clippy --workspace --all-features --all-targets -- -Dclippy::todo"
|
||||
|
||||
# lib checking
|
||||
ci-check-min = "hack --workspace check --no-default-features"
|
||||
|
14
.github/dependabot.yml
vendored
14
.github/dependabot.yml
vendored
@ -1,12 +1,10 @@
|
||||
version: 2
|
||||
updates:
|
||||
- package-ecosystem: "cargo"
|
||||
directory: "/"
|
||||
- package-ecosystem: cargo
|
||||
directory: /
|
||||
schedule:
|
||||
interval: "monthly"
|
||||
open-pull-requests-limit: 10
|
||||
- package-ecosystem: "github-actions"
|
||||
directory: "/"
|
||||
interval: weekly
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
schedule:
|
||||
interval: "monthly"
|
||||
open-pull-requests-limit: 10
|
||||
interval: weekly
|
||||
|
4
.github/workflows/bench.yml
vendored
4
.github/workflows/bench.yml
vendored
@ -5,7 +5,7 @@ on:
|
||||
branches: [master]
|
||||
|
||||
permissions:
|
||||
contents: read # to fetch code (actions/checkout)
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
@ -16,7 +16,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install Rust
|
||||
run: |
|
||||
|
46
.github/workflows/ci-post-merge.yml
vendored
46
.github/workflows/ci-post-merge.yml
vendored
@ -28,24 +28,26 @@ jobs:
|
||||
runs-on: ${{ matrix.target.os }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install OpenSSL
|
||||
if: matrix.target.os == 'windows-latest'
|
||||
run: choco install openssl -y --forcex64 --no-progress
|
||||
- name: Set OpenSSL dir in env
|
||||
if: matrix.target.os == 'windows-latest'
|
||||
shell: bash
|
||||
run: |
|
||||
echo 'OPENSSL_DIR=C:\Program Files\OpenSSL-Win64' | Out-File -FilePath $env:GITHUB_ENV -Append
|
||||
echo 'OPENSSL_DIR=C:\Program Files\OpenSSL' | Out-File -FilePath $env:GITHUB_ENV -Append
|
||||
set -e
|
||||
choco install openssl --version=1.1.1.2100 -y --no-progress
|
||||
echo 'OPENSSL_DIR=C:\Program Files\OpenSSL' >> $GITHUB_ENV
|
||||
echo "RUSTFLAGS=-C target-feature=+crt-static" >> $GITHUB_ENV
|
||||
|
||||
- name: Install Rust (${{ matrix.version.name }})
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
|
||||
with:
|
||||
toolchain: ${{ matrix.version.version }}
|
||||
|
||||
- name: Install cargo-hack
|
||||
uses: taiki-e/install-action@cargo-hack
|
||||
- name: Install cargo-hack and cargo-ci-cache-clean
|
||||
uses: taiki-e/install-action@v2.26.8
|
||||
with:
|
||||
tool: cargo-hack,cargo-ci-cache-clean
|
||||
|
||||
- name: check minimal
|
||||
run: cargo ci-check-min
|
||||
@ -55,10 +57,12 @@ jobs:
|
||||
|
||||
- name: tests
|
||||
timeout-minutes: 60
|
||||
shell: bash
|
||||
run: |
|
||||
set -e
|
||||
cargo test --lib --tests -p=actix-router --all-features
|
||||
cargo test --lib --tests -p=actix-http --all-features
|
||||
cargo test --lib --tests -p=actix-web --features=rustls-0_20,rustls-0_21,openssl -- --skip=test_reading_deflate_encoding_large_random_rustls
|
||||
cargo test --lib --tests -p=actix-web --features=rustls-0_20,rustls-0_21,rustls-0_22,openssl -- --skip=test_reading_deflate_encoding_large_random_rustls
|
||||
cargo test --lib --tests -p=actix-web-codegen --all-features
|
||||
cargo test --lib --tests -p=awc --all-features
|
||||
cargo test --lib --tests -p=actix-http-test --all-features
|
||||
@ -67,23 +71,23 @@ jobs:
|
||||
cargo test --lib --tests -p=actix-multipart --all-features
|
||||
cargo test --lib --tests -p=actix-web-actors --all-features
|
||||
|
||||
- name: Clear the cargo caches
|
||||
run: |
|
||||
cargo install cargo-cache --version 0.8.3 --no-default-features --features ci-autoclean
|
||||
cargo-cache
|
||||
- name: CI cache clean
|
||||
run: cargo-ci-cache-clean
|
||||
|
||||
ci_feature_powerset_check:
|
||||
name: Verify Feature Combinations
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install Rust
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
|
||||
|
||||
- name: Install cargo-hack
|
||||
uses: taiki-e/install-action@cargo-hack
|
||||
uses: taiki-e/install-action@v2.26.8
|
||||
with:
|
||||
tool: cargo-hack
|
||||
|
||||
- name: check feature combinations
|
||||
run: cargo ci-check-all-feature-powerset
|
||||
@ -96,13 +100,15 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install Rust
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
|
||||
|
||||
- name: Install nextest
|
||||
uses: taiki-e/install-action@nextest
|
||||
uses: taiki-e/install-action@v2.26.8
|
||||
with:
|
||||
tool: nextest
|
||||
|
||||
- name: Test with cargo-nextest
|
||||
run: cargo nextest run
|
||||
|
49
.github/workflows/ci.yml
vendored
49
.github/workflows/ci.yml
vendored
@ -33,30 +33,35 @@ jobs:
|
||||
runs-on: ${{ matrix.target.os }}
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install OpenSSL
|
||||
if: matrix.target.os == 'windows-latest'
|
||||
run: choco install openssl -y --forcex64 --no-progress
|
||||
- name: Set OpenSSL dir in env
|
||||
if: matrix.target.os == 'windows-latest'
|
||||
shell: bash
|
||||
run: |
|
||||
echo 'OPENSSL_DIR=C:\Program Files\OpenSSL-Win64' | Out-File -FilePath $env:GITHUB_ENV -Append
|
||||
echo 'OPENSSL_DIR=C:\Program Files\OpenSSL' | Out-File -FilePath $env:GITHUB_ENV -Append
|
||||
set -e
|
||||
choco install openssl --version=1.1.1.2100 -y --no-progress
|
||||
echo 'OPENSSL_DIR=C:\Program Files\OpenSSL' >> $GITHUB_ENV
|
||||
echo "RUSTFLAGS=-C target-feature=+crt-static" >> $GITHUB_ENV
|
||||
|
||||
- name: Install Rust (${{ matrix.version.name }})
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
|
||||
with:
|
||||
toolchain: ${{ matrix.version.version }}
|
||||
|
||||
- name: Install cargo-hack
|
||||
uses: taiki-e/install-action@cargo-hack
|
||||
- name: Install cargo-hack and cargo-ci-cache-clean
|
||||
uses: taiki-e/install-action@v2.26.8
|
||||
with:
|
||||
tool: cargo-hack,cargo-ci-cache-clean
|
||||
|
||||
- name: workaround MSRV issues
|
||||
if: matrix.version.name != 'stable'
|
||||
if: matrix.version.name == 'msrv'
|
||||
run: |
|
||||
cargo update -p=ciborium --precise=0.2.1
|
||||
cargo update -p=ciborium-ll --precise=0.2.1
|
||||
cargo update -p=clap --precise=4.3.24
|
||||
cargo update -p=clap_lex --precise=0.5.0
|
||||
cargo update -p=anstyle --precise=1.0.2
|
||||
|
||||
- name: check minimal
|
||||
run: cargo ci-check-min
|
||||
@ -66,10 +71,12 @@ jobs:
|
||||
|
||||
- name: tests
|
||||
timeout-minutes: 60
|
||||
shell: bash
|
||||
run: |
|
||||
set -e
|
||||
cargo test --lib --tests -p=actix-router --all-features
|
||||
cargo test --lib --tests -p=actix-http --all-features
|
||||
cargo test --lib --tests -p=actix-web --features=rustls-0_20,rustls-0_21,openssl -- --skip=test_reading_deflate_encoding_large_random_rustls
|
||||
cargo test --lib --tests -p=actix-web --features=rustls-0_20,rustls-0_21,rustls-0_22,openssl -- --skip=test_reading_deflate_encoding_large_random_rustls
|
||||
cargo test --lib --tests -p=actix-web-codegen --all-features
|
||||
cargo test --lib --tests -p=awc --all-features
|
||||
cargo test --lib --tests -p=actix-http-test --all-features
|
||||
@ -78,20 +85,19 @@ jobs:
|
||||
cargo test --lib --tests -p=actix-multipart --all-features
|
||||
cargo test --lib --tests -p=actix-web-actors --all-features
|
||||
|
||||
- name: Clear the cargo caches
|
||||
run: |
|
||||
cargo install cargo-cache --version 0.8.3 --no-default-features --features ci-autoclean
|
||||
cargo-cache
|
||||
- name: CI cache clean
|
||||
run: cargo-ci-cache-clean
|
||||
|
||||
io-uring:
|
||||
name: io-uring tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install Rust
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with: { toolchain: nightly }
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
|
||||
with:
|
||||
toolchain: nightly
|
||||
|
||||
- name: tests (io-uring)
|
||||
timeout-minutes: 60
|
||||
@ -102,11 +108,12 @@ jobs:
|
||||
name: doc tests
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install Rust (nightly)
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with: { toolchain: nightly }
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
|
||||
with:
|
||||
toolchain: nightly
|
||||
|
||||
- name: doc tests
|
||||
run: cargo ci-doctest
|
||||
|
75
.github/workflows/clippy-fmt.yml
vendored
75
.github/workflows/clippy-fmt.yml
vendored
@ -1,75 +0,0 @@
|
||||
name: Lint
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened]
|
||||
|
||||
permissions:
|
||||
contents: read # to fetch code (actions/checkout)
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
fmt:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with:
|
||||
toolchain: nightly
|
||||
components: rustfmt
|
||||
|
||||
- run: cargo fmt --all -- --check
|
||||
|
||||
clippy:
|
||||
permissions:
|
||||
checks: write # to add clippy checks to PR diffs
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with: { components: clippy }
|
||||
|
||||
- uses: giraffate/clippy-action@v1
|
||||
with:
|
||||
reporter: 'github-pr-check'
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
clippy_flags: --workspace --all-features --tests --examples --bins -- -Dclippy::todo -Aunknown_lints
|
||||
|
||||
lint-docs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with: { components: rust-docs }
|
||||
|
||||
- name: Check for broken intra-doc links
|
||||
env: { RUSTDOCFLAGS: "-D warnings" }
|
||||
run: cargo doc --no-deps --all-features --workspace
|
||||
|
||||
public-api-diff:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
with:
|
||||
ref: ${{ github.base_ref }}
|
||||
|
||||
- uses: actions/checkout@v3
|
||||
|
||||
- uses: actions-rust-lang/setup-rust-toolchain@v1
|
||||
with: { toolchain: nightly-2023-08-25 }
|
||||
|
||||
- uses: taiki-e/cache-cargo-install-action@v1
|
||||
with: { tool: cargo-public-api }
|
||||
|
||||
- name: generate API diff
|
||||
run: |
|
||||
for f in $(find -mindepth 2 -maxdepth 2 -name Cargo.toml); do
|
||||
cargo public-api --manifest-path "$f" diff ${{ github.event.pull_request.base.sha }}..${{ github.sha }}
|
||||
done
|
11
.github/workflows/coverage.yml
vendored
11
.github/workflows/coverage.yml
vendored
@ -15,14 +15,15 @@ jobs:
|
||||
coverage:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install Rust
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1.5.0
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
|
||||
with:
|
||||
components: llvm-tools-preview
|
||||
|
||||
- name: Install cargo-llvm-cov
|
||||
uses: taiki-e/install-action@v2.13.4
|
||||
uses: taiki-e/install-action@v2.26.8
|
||||
with:
|
||||
tool: cargo-llvm-cov
|
||||
|
||||
@ -30,7 +31,9 @@ jobs:
|
||||
run: cargo llvm-cov --workspace --all-features --codecov --output-path codecov.json
|
||||
|
||||
- name: Upload coverage to Codecov
|
||||
uses: codecov/codecov-action@v3.1.4
|
||||
uses: codecov/codecov-action@v4.0.0
|
||||
with:
|
||||
files: codecov.json
|
||||
fail_ci_if_error: true
|
||||
env:
|
||||
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
|
||||
|
93
.github/workflows/lint.yml
vendored
Normal file
93
.github/workflows/lint.yml
vendored
Normal file
@ -0,0 +1,93 @@
|
||||
name: Lint
|
||||
|
||||
on:
|
||||
pull_request:
|
||||
types: [opened, synchronize, reopened]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
jobs:
|
||||
fmt:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install Rust (nightly)
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
|
||||
with:
|
||||
toolchain: nightly
|
||||
components: rustfmt
|
||||
|
||||
- name: Check with Rustfmt
|
||||
run: cargo fmt --all -- --check
|
||||
|
||||
clippy:
|
||||
permissions:
|
||||
contents: read
|
||||
checks: write # to add clippy checks to PR diffs
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install Rust
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
|
||||
with:
|
||||
components: clippy
|
||||
|
||||
- name: Check with Clippy
|
||||
uses: giraffate/clippy-action@v1.0.1
|
||||
with:
|
||||
reporter: github-pr-check
|
||||
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||
clippy_flags: >-
|
||||
--workspace --all-features --tests --examples --bins --
|
||||
-A unknown_lints -D clippy::todo -D clippy::dbg_macro
|
||||
|
||||
lint-docs:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Install Rust (nightly)
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
|
||||
with:
|
||||
toolchain: nightly
|
||||
components: rust-docs
|
||||
|
||||
- name: Check for broken intra-doc links
|
||||
env:
|
||||
RUSTDOCFLAGS: -D warnings
|
||||
run: cargo +nightly doc --no-deps --workspace --all-features
|
||||
|
||||
public-api-diff:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- name: Checkout main branch
|
||||
uses: actions/checkout@v4
|
||||
with:
|
||||
ref: ${{ github.base_ref }}
|
||||
|
||||
- name: Checkout PR branch
|
||||
uses: actions/checkout@v4
|
||||
|
||||
- name: Install Rust
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
|
||||
with:
|
||||
toolchain: nightly-2023-08-25
|
||||
|
||||
- name: Install cargo-public-api
|
||||
uses: taiki-e/install-action@v2.26.8
|
||||
with:
|
||||
tool: cargo-public-api
|
||||
|
||||
- name: Generate API diff
|
||||
run: |
|
||||
for f in $(find -mindepth 2 -maxdepth 2 -name Cargo.toml); do
|
||||
cargo public-api --manifest-path "$f" diff ${{ github.event.pull_request.base.sha }}..${{ github.sha }}
|
||||
done
|
13
.github/workflows/upload-doc.yml
vendored
13
.github/workflows/upload-doc.yml
vendored
@ -5,7 +5,7 @@ on:
|
||||
branches: [master]
|
||||
|
||||
permissions:
|
||||
contents: read # to fetch code (actions/checkout)
|
||||
contents: read
|
||||
|
||||
concurrency:
|
||||
group: ${{ github.workflow }}-${{ github.ref }}
|
||||
@ -14,14 +14,17 @@ concurrency:
|
||||
jobs:
|
||||
build:
|
||||
permissions:
|
||||
contents: write # to push changes in repo (jamesives/github-pages-deploy-action)
|
||||
contents: write
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v3
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: dtolnay/rust-toolchain@nightly
|
||||
- name: Install Rust
|
||||
uses: actions-rust-lang/setup-rust-toolchain@v1.8.0
|
||||
with:
|
||||
toolchain: nightly
|
||||
|
||||
- name: Build Docs
|
||||
run: cargo +nightly doc --no-deps --workspace --all-features
|
||||
@ -32,7 +35,7 @@ jobs:
|
||||
run: echo '<meta http-equiv="refresh" content="0;url=actix_web/index.html">' > target/doc/index.html
|
||||
|
||||
- name: Deploy to GitHub Pages
|
||||
uses: JamesIves/github-pages-deploy-action@v4.4.3
|
||||
uses: JamesIves/github-pages-deploy-action@v4.5.0
|
||||
with:
|
||||
folder: target/doc
|
||||
single-commit: true
|
||||
|
@ -1,5 +1,5 @@
|
||||
overrides:
|
||||
- files: '*.md'
|
||||
- files: "*.md"
|
||||
options:
|
||||
printWidth: 9999
|
||||
proseWrap: never
|
||||
|
@ -2,6 +2,13 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
## 0.6.5
|
||||
|
||||
- Fix handling of special characters in filenames.
|
||||
|
||||
## 0.6.4
|
||||
|
||||
- Fix handling of newlines in filenames.
|
||||
- Minimum supported Rust version (MSRV) is now 1.68 due to transitive `time` dependency.
|
||||
|
||||
## 0.6.3
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-files"
|
||||
version = "0.6.3"
|
||||
version = "0.6.5"
|
||||
authors = [
|
||||
"Nikolay Kim <fafhrd91@gmail.com>",
|
||||
"Rob Ede <robjtede@icloud.com>",
|
||||
@ -47,4 +47,5 @@ actix-server = { version = "2.2", optional = true } # ensure matching tokio-urin
|
||||
actix-rt = "2.7"
|
||||
actix-test = "0.1"
|
||||
actix-web = "4"
|
||||
env_logger = "0.10"
|
||||
tempfile = "3.2"
|
||||
|
@ -1,18 +1,32 @@
|
||||
# actix-files
|
||||
# `actix-files`
|
||||
|
||||
> Static file serving for Actix Web
|
||||
<!-- prettier-ignore-start -->
|
||||
|
||||
[](https://crates.io/crates/actix-files)
|
||||
[](https://docs.rs/actix-files/0.6.3)
|
||||
[](https://docs.rs/actix-files/0.6.5)
|
||||

|
||||

|
||||
<br />
|
||||
[](https://deps.rs/crate/actix-files/0.6.3)
|
||||
[](https://deps.rs/crate/actix-files/0.6.5)
|
||||
[](https://crates.io/crates/actix-files)
|
||||
[](https://discord.gg/NWpN5mmg3x)
|
||||
|
||||
## Documentation & Resources
|
||||
<!-- prettier-ignore-end -->
|
||||
|
||||
- [API Documentation](https://docs.rs/actix-files)
|
||||
- [Example Project](https://github.com/actix/examples/tree/master/basics/static-files)
|
||||
- Minimum Supported Rust Version (MSRV): 1.68
|
||||
<!-- cargo-rdme start -->
|
||||
|
||||
Static file serving for Actix Web.
|
||||
|
||||
Provides a non-blocking service for serving static files from disk.
|
||||
|
||||
## Examples
|
||||
|
||||
```rust
|
||||
use actix_web::App;
|
||||
use actix_files::Files;
|
||||
|
||||
let app = App::new()
|
||||
.service(Files::new("/static", ".").prefer_utf8(true));
|
||||
```
|
||||
|
||||
<!-- cargo-rdme end -->
|
||||
|
33
actix-files/examples/guarded-listing.rs
Normal file
33
actix-files/examples/guarded-listing.rs
Normal file
@ -0,0 +1,33 @@
|
||||
use actix_files::Files;
|
||||
use actix_web::{get, guard, middleware, App, HttpServer, Responder};
|
||||
|
||||
const EXAMPLES_DIR: &str = concat![env!("CARGO_MANIFEST_DIR"), "/examples"];
|
||||
|
||||
#[get("/")]
|
||||
async fn index() -> impl Responder {
|
||||
"Hello world!"
|
||||
}
|
||||
|
||||
#[actix_web::main]
|
||||
async fn main() -> std::io::Result<()> {
|
||||
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
||||
|
||||
log::info!("starting HTTP server at http://localhost:8080");
|
||||
|
||||
HttpServer::new(|| {
|
||||
App::new()
|
||||
.service(index)
|
||||
.service(
|
||||
Files::new("/assets", EXAMPLES_DIR)
|
||||
.show_files_listing()
|
||||
.guard(guard::Header("show-listing", "?1")),
|
||||
)
|
||||
.service(Files::new("/assets", EXAMPLES_DIR))
|
||||
.wrap(middleware::Compress::default())
|
||||
.wrap(middleware::Logger::default())
|
||||
})
|
||||
.bind(("127.0.0.1", 8080))?
|
||||
.workers(2)
|
||||
.run()
|
||||
.await
|
||||
}
|
@ -235,7 +235,7 @@ impl Files {
|
||||
/// request starts being handled by the file service, it will not be able to back-out and try
|
||||
/// the next service, you will simply get a 404 (or 405) error response.
|
||||
///
|
||||
/// To allow `POST` requests to retrieve files, see [`Files::use_guards`].
|
||||
/// To allow `POST` requests to retrieve files, see [`Files::method_guard()`].
|
||||
///
|
||||
/// # Examples
|
||||
/// ```
|
||||
|
@ -13,7 +13,6 @@
|
||||
|
||||
#![deny(rust_2018_idioms, nonstandard_style)]
|
||||
#![warn(future_incompatible, missing_docs, missing_debug_implementations)]
|
||||
#![allow(clippy::uninlined_format_args)]
|
||||
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
|
||||
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||
@ -569,6 +568,30 @@ mod tests {
|
||||
assert_eq!(bytes, data);
|
||||
}
|
||||
|
||||
#[cfg(not(target_os = "windows"))]
|
||||
#[actix_rt::test]
|
||||
async fn test_static_files_with_special_characters() {
|
||||
// Create the file we want to test against ad-hoc. We can't check it in as otherwise
|
||||
// Windows can't even checkout this repository.
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let file_with_newlines = temp_dir.path().join("test\n\x0B\x0C\rnewline.text");
|
||||
fs::write(&file_with_newlines, "Look at my newlines").unwrap();
|
||||
|
||||
let srv = test::init_service(
|
||||
App::new().service(Files::new("/", temp_dir.path()).index_file("Cargo.toml")),
|
||||
)
|
||||
.await;
|
||||
let request = TestRequest::get()
|
||||
.uri("/test%0A%0B%0C%0Dnewline.text")
|
||||
.to_request();
|
||||
let response = test::call_service(&srv, request).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
|
||||
let bytes = test::read_body(response).await;
|
||||
let data = web::Bytes::from(fs::read(file_with_newlines).unwrap());
|
||||
assert_eq!(bytes, data);
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_files_not_allowed() {
|
||||
let srv = test::init_service(App::new().service(Files::new("/", "."))).await;
|
||||
@ -841,9 +864,9 @@ mod tests {
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_percent_encoding_2() {
|
||||
let tmpdir = tempfile::tempdir().unwrap();
|
||||
let temp_dir = tempfile::tempdir().unwrap();
|
||||
let filename = match cfg!(unix) {
|
||||
true => "ض:?#[]{}<>()@!$&'`|*+,;= %20.test",
|
||||
true => "ض:?#[]{}<>()@!$&'`|*+,;= %20\n.test",
|
||||
false => "ض#[]{}()@!$&'`+,;= %20.test",
|
||||
};
|
||||
let filename_encoded = filename
|
||||
@ -853,9 +876,9 @@ mod tests {
|
||||
write!(&mut buf, "%{:02X}", c).unwrap();
|
||||
buf
|
||||
});
|
||||
std::fs::File::create(tmpdir.path().join(filename)).unwrap();
|
||||
std::fs::File::create(temp_dir.path().join(filename)).unwrap();
|
||||
|
||||
let srv = test::init_service(App::new().service(Files::new("", tmpdir.path()))).await;
|
||||
let srv = test::init_service(App::new().service(Files::new("/", temp_dir.path()))).await;
|
||||
|
||||
let req = TestRequest::get()
|
||||
.uri(&format!("/{}", filename_encoded))
|
||||
|
@ -24,7 +24,6 @@ use bitflags::bitflags;
|
||||
use derive_more::{Deref, DerefMut};
|
||||
use futures_core::future::LocalBoxFuture;
|
||||
use mime::Mime;
|
||||
use mime_guess::from_path;
|
||||
|
||||
use crate::{encoding::equiv_utf8_text, range::HttpRange};
|
||||
|
||||
@ -128,7 +127,7 @@ impl NamedFile {
|
||||
}
|
||||
};
|
||||
|
||||
let ct = from_path(&path).first_or_octet_stream();
|
||||
let ct = mime_guess::from_path(&path).first_or_octet_stream();
|
||||
|
||||
let disposition = match ct.type_() {
|
||||
mime::IMAGE | mime::TEXT | mime::AUDIO | mime::VIDEO => DispositionType::Inline,
|
||||
@ -140,7 +139,13 @@ impl NamedFile {
|
||||
_ => DispositionType::Attachment,
|
||||
};
|
||||
|
||||
let mut parameters = vec![DispositionParam::Filename(String::from(filename.as_ref()))];
|
||||
// replace special characters in filenames which could occur on some filesystems
|
||||
let filename_s = filename
|
||||
.replace('\n', "%0A") // \n line break
|
||||
.replace('\x0B', "%0B") // \v vertical tab
|
||||
.replace('\x0C', "%0C") // \f form feed
|
||||
.replace('\r', "%0D"); // \r carriage return
|
||||
let mut parameters = vec![DispositionParam::Filename(filename_s)];
|
||||
|
||||
if !filename.is_ascii() {
|
||||
parameters.push(DispositionParam::FilenameExt(ExtendedValue {
|
||||
|
@ -2,6 +2,8 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
## 3.2.0
|
||||
|
||||
- Minimum supported Rust version (MSRV) is now 1.68 due to transitive `time` dependency.
|
||||
|
||||
## 3.1.0
|
||||
|
@ -1,11 +1,11 @@
|
||||
[package]
|
||||
name = "actix-http-test"
|
||||
version = "3.1.0"
|
||||
version = "3.2.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Various helpers for Actix applications to use during testing"
|
||||
keywords = ["http", "web", "framework", "async", "futures"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-web.git"
|
||||
repository = "https://github.com/actix/actix-web"
|
||||
categories = [
|
||||
"network-programming",
|
||||
"asynchronous",
|
||||
|
@ -1,16 +1,20 @@
|
||||
# actix-http-test
|
||||
# `actix-http-test`
|
||||
|
||||
> Various helpers for Actix applications to use during testing.
|
||||
|
||||
<!-- prettier-ignore-start -->
|
||||
|
||||
[](https://crates.io/crates/actix-http-test)
|
||||
[](https://docs.rs/actix-http-test/3.1.0)
|
||||
[](https://docs.rs/actix-http-test/3.2.0)
|
||||

|
||||

|
||||
<br>
|
||||
[](https://deps.rs/crate/actix-http-test/3.1.0)
|
||||
[](https://deps.rs/crate/actix-http-test/3.2.0)
|
||||
[](https://crates.io/crates/actix-http-test)
|
||||
[](https://discord.gg/NWpN5mmg3x)
|
||||
|
||||
<!-- prettier-ignore-end -->
|
||||
|
||||
## Documentation & Resources
|
||||
|
||||
- [API Documentation](https://docs.rs/actix-http-test)
|
||||
|
@ -2,7 +2,6 @@
|
||||
|
||||
#![deny(rust_2018_idioms, nonstandard_style)]
|
||||
#![warn(future_incompatible)]
|
||||
#![allow(clippy::uninlined_format_args)]
|
||||
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
|
||||
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||
|
@ -2,11 +2,41 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
## 3.6.0
|
||||
|
||||
### Added
|
||||
|
||||
- Add `rustls-0_22` crate feature.
|
||||
- Add `{h1::H1Service, h2::H2Service, HttpService}::rustls_0_22()` and `HttpService::rustls_0_22_with_config()` service constructors.
|
||||
- Implement `From<&HeaderMap>` for `http::HeaderMap`.
|
||||
|
||||
## 3.5.1
|
||||
|
||||
### Fixed
|
||||
|
||||
- Prevent hang when returning zero-sized response bodies through compression layer.
|
||||
|
||||
## 3.5.0
|
||||
|
||||
### Added
|
||||
|
||||
- Implement `From<HeaderMap>` for `http::HeaderMap`.
|
||||
|
||||
### Changed
|
||||
|
||||
- Updated `zstd` dependency to `0.13`.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Prevent compression of zero-sized response bodies.
|
||||
|
||||
## 3.4.0
|
||||
|
||||
### Added
|
||||
|
||||
- Add `rustls-0_20` crate feature.
|
||||
- Add `{H1Service, H2Service, HttpService}::rustls_021()` and `HttpService::rustls_021_with_config()` service constructors.
|
||||
- Add `body::to_body_limit()` function.
|
||||
- Add `{h1::H1Service, h2::H2Service, HttpService}::rustls_021()` and `HttpService::rustls_021_with_config()` service constructors.
|
||||
- Add `body::to_bytes_limited()` function.
|
||||
- Add `body::BodyLimitExceeded` error type.
|
||||
|
||||
### Changed
|
||||
|
@ -1,14 +1,14 @@
|
||||
[package]
|
||||
name = "actix-http"
|
||||
version = "3.3.1"
|
||||
version = "3.6.0"
|
||||
authors = [
|
||||
"Nikolay Kim <fafhrd91@gmail.com>",
|
||||
"Rob Ede <robjtede@icloud.com>",
|
||||
]
|
||||
description = "HTTP primitives for the Actix ecosystem"
|
||||
description = "HTTP types and services for the Actix ecosystem"
|
||||
keywords = ["actix", "http", "framework", "async", "futures"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-web.git"
|
||||
repository = "https://github.com/actix/actix-web"
|
||||
categories = [
|
||||
"network-programming",
|
||||
"asynchronous",
|
||||
@ -20,8 +20,18 @@ edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
# features that docs.rs will build with
|
||||
features = ["http2", "ws", "openssl", "rustls-0_20", "rustls-0_21", "compress-brotli", "compress-gzip", "compress-zstd"]
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
features = [
|
||||
"http2",
|
||||
"ws",
|
||||
"openssl",
|
||||
"rustls-0_20",
|
||||
"rustls-0_21",
|
||||
"rustls-0_22",
|
||||
"compress-brotli",
|
||||
"compress-gzip",
|
||||
"compress-zstd",
|
||||
]
|
||||
|
||||
[lib]
|
||||
name = "actix_http"
|
||||
@ -53,6 +63,9 @@ rustls-0_20 = ["actix-tls/accept", "actix-tls/rustls-0_20"]
|
||||
# TLS via Rustls v0.21
|
||||
rustls-0_21 = ["actix-tls/accept", "actix-tls/rustls-0_21"]
|
||||
|
||||
# TLS via Rustls v0.22
|
||||
rustls-0_22 = ["actix-tls/accept", "actix-tls/rustls-0_22"]
|
||||
|
||||
# Compression codecs
|
||||
compress-brotli = ["__compress", "brotli"]
|
||||
compress-gzip = ["__compress", "flate2"]
|
||||
@ -89,7 +102,7 @@ tokio-util = { version = "0.7", features = ["io", "codec"] }
|
||||
tracing = { version = "0.1.30", default-features = false, features = ["log"] }
|
||||
|
||||
# http2
|
||||
h2 = { version = "0.3.17", optional = true }
|
||||
h2 = { version = "0.3.24", optional = true }
|
||||
|
||||
# websockets
|
||||
local-channel = { version = "0.1", optional = true }
|
||||
@ -98,17 +111,17 @@ rand = { version = "0.8", optional = true }
|
||||
sha1 = { version = "0.10", optional = true }
|
||||
|
||||
# openssl/rustls
|
||||
actix-tls = { version = "3.1", default-features = false, optional = true }
|
||||
actix-tls = { version = "3.3", default-features = false, optional = true }
|
||||
|
||||
# compress-*
|
||||
brotli = { version = "3.3.3", optional = true }
|
||||
flate2 = { version = "1.0.13", optional = true }
|
||||
zstd = { version = "0.12", optional = true }
|
||||
zstd = { version = "0.13", optional = true }
|
||||
|
||||
[dev-dependencies]
|
||||
actix-http-test = { version = "3", features = ["openssl"] }
|
||||
actix-server = "2"
|
||||
actix-tls = { version = "3.1", features = ["openssl"] }
|
||||
actix-tls = { version = "3.3", features = ["openssl", "rustls-0_22-webpki-roots"] }
|
||||
actix-web = "4"
|
||||
|
||||
async-stream = "0.3"
|
||||
@ -117,24 +130,24 @@ env_logger = "0.10"
|
||||
futures-util = { version = "0.3.17", default-features = false, features = ["alloc"] }
|
||||
memchr = "2.4"
|
||||
once_cell = "1.9"
|
||||
rcgen = "0.11"
|
||||
rcgen = "0.12"
|
||||
regex = "1.3"
|
||||
rustversion = "1"
|
||||
rustls-pemfile = "1"
|
||||
rustls-pemfile = "2"
|
||||
serde = { version = "1.0", features = ["derive"] }
|
||||
serde_json = "1.0"
|
||||
static_assertions = "1"
|
||||
tls-openssl = { package = "openssl", version = "0.10.55" }
|
||||
tls-rustls_021 = { package = "rustls", version = "0.21" }
|
||||
tls-rustls_022 = { package = "rustls", version = "0.22" }
|
||||
tokio = { version = "1.24.2", features = ["net", "rt", "macros"] }
|
||||
|
||||
[[example]]
|
||||
name = "ws"
|
||||
required-features = ["ws", "rustls-0_21"]
|
||||
required-features = ["ws", "rustls-0_22"]
|
||||
|
||||
[[example]]
|
||||
name = "tls_rustls"
|
||||
required-features = ["http2", "rustls-0_21"]
|
||||
required-features = ["http2", "rustls-0_22"]
|
||||
|
||||
[[bench]]
|
||||
name = "response-body-compression"
|
||||
|
@ -1,22 +1,26 @@
|
||||
# actix-http
|
||||
# `actix-http`
|
||||
|
||||
> HTTP primitives for the Actix ecosystem.
|
||||
> HTTP types and services for the Actix ecosystem.
|
||||
|
||||
<!-- prettier-ignore-start -->
|
||||
|
||||
[](https://crates.io/crates/actix-http)
|
||||
[](https://docs.rs/actix-http/3.3.1)
|
||||
[](https://docs.rs/actix-http/3.6.0)
|
||||

|
||||

|
||||
<br />
|
||||
[](https://deps.rs/crate/actix-http/3.3.1)
|
||||
[](https://deps.rs/crate/actix-http/3.6.0)
|
||||
[](https://crates.io/crates/actix-http)
|
||||
[](https://discord.gg/NWpN5mmg3x)
|
||||
|
||||
<!-- prettier-ignore-end -->
|
||||
|
||||
## Documentation & Resources
|
||||
|
||||
- [API Documentation](https://docs.rs/actix-http)
|
||||
- Minimum Supported Rust Version (MSRV): 1.68
|
||||
|
||||
## Example
|
||||
## Examples
|
||||
|
||||
```rust
|
||||
use std::{env, io};
|
||||
|
@ -1,5 +1,3 @@
|
||||
#![allow(clippy::uninlined_format_args)]
|
||||
|
||||
use std::convert::Infallible;
|
||||
|
||||
use actix_http::{encoding::Encoder, ContentEncoding, Request, Response, StatusCode};
|
||||
|
@ -12,7 +12,7 @@
|
||||
//! Protocol: HTTP/1.1
|
||||
//! ```
|
||||
|
||||
extern crate tls_rustls_021 as rustls;
|
||||
extern crate tls_rustls_022 as rustls;
|
||||
|
||||
use std::io;
|
||||
|
||||
@ -36,7 +36,7 @@ async fn main() -> io::Result<()> {
|
||||
);
|
||||
ok::<_, Error>(Response::ok().set_body(body))
|
||||
})
|
||||
.rustls_021(rustls_config())
|
||||
.rustls_0_22(rustls_config())
|
||||
})?
|
||||
.run()
|
||||
.await
|
||||
@ -51,16 +51,18 @@ fn rustls_config() -> rustls::ServerConfig {
|
||||
let key_file = &mut io::BufReader::new(key_file.as_bytes());
|
||||
|
||||
let cert_chain = rustls_pemfile::certs(cert_file)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(rustls::Certificate)
|
||||
.collect();
|
||||
let mut keys = rustls_pemfile::pkcs8_private_keys(key_file).unwrap();
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.unwrap();
|
||||
let mut keys = rustls_pemfile::pkcs8_private_keys(key_file)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.unwrap();
|
||||
|
||||
let mut config = rustls::ServerConfig::builder()
|
||||
.with_safe_defaults()
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(cert_chain, rustls::PrivateKey(keys.remove(0)))
|
||||
.with_single_cert(
|
||||
cert_chain,
|
||||
rustls::pki_types::PrivateKeyDer::Pkcs8(keys.remove(0)),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
const H1_ALPN: &[u8] = b"http/1.1";
|
||||
|
@ -1,7 +1,7 @@
|
||||
//! Sets up a WebSocket server over TCP and TLS.
|
||||
//! Sends a heartbeat message every 4 seconds but does not respond to any incoming frames.
|
||||
|
||||
extern crate tls_rustls_021 as rustls;
|
||||
extern crate tls_rustls_022 as rustls;
|
||||
|
||||
use std::{
|
||||
io,
|
||||
@ -30,7 +30,7 @@ async fn main() -> io::Result<()> {
|
||||
.bind("tls", ("127.0.0.1", 8443), || {
|
||||
HttpService::build()
|
||||
.finish(handler)
|
||||
.rustls_021(tls_config())
|
||||
.rustls_0_22(tls_config())
|
||||
})?
|
||||
.run()
|
||||
.await
|
||||
@ -85,7 +85,6 @@ impl Stream for Heartbeat {
|
||||
fn tls_config() -> rustls::ServerConfig {
|
||||
use std::io::BufReader;
|
||||
|
||||
use rustls::{Certificate, PrivateKey};
|
||||
use rustls_pemfile::{certs, pkcs8_private_keys};
|
||||
|
||||
let cert = rcgen::generate_simple_self_signed(vec!["localhost".to_owned()]).unwrap();
|
||||
@ -95,17 +94,17 @@ fn tls_config() -> rustls::ServerConfig {
|
||||
let cert_file = &mut BufReader::new(cert_file.as_bytes());
|
||||
let key_file = &mut BufReader::new(key_file.as_bytes());
|
||||
|
||||
let cert_chain = certs(cert_file)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(Certificate)
|
||||
.collect();
|
||||
let mut keys = pkcs8_private_keys(key_file).unwrap();
|
||||
let cert_chain = certs(cert_file).collect::<Result<Vec<_>, _>>().unwrap();
|
||||
let mut keys = pkcs8_private_keys(key_file)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.unwrap();
|
||||
|
||||
let mut config = rustls::ServerConfig::builder()
|
||||
.with_safe_defaults()
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(cert_chain, PrivateKey(keys.remove(0)))
|
||||
.with_single_cert(
|
||||
cert_chain,
|
||||
rustls::pki_types::PrivateKeyDer::Pkcs8(keys.remove(0)),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
config.alpn_protocols.push(b"http/1.1".to_vec());
|
||||
|
@ -191,7 +191,7 @@ impl ContentDecoder {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
Err(err) => Err(err),
|
||||
},
|
||||
|
||||
#[cfg(feature = "compress-gzip")]
|
||||
@ -205,7 +205,7 @@ impl ContentDecoder {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
Err(err) => Err(err),
|
||||
},
|
||||
|
||||
#[cfg(feature = "compress-gzip")]
|
||||
@ -218,7 +218,7 @@ impl ContentDecoder {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
Err(err) => Err(err),
|
||||
},
|
||||
|
||||
#[cfg(feature = "compress-zstd")]
|
||||
@ -231,7 +231,7 @@ impl ContentDecoder {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
Err(err) => Err(err),
|
||||
},
|
||||
}
|
||||
}
|
||||
@ -250,7 +250,7 @@ impl ContentDecoder {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
Err(err) => Err(err),
|
||||
},
|
||||
|
||||
#[cfg(feature = "compress-gzip")]
|
||||
@ -265,7 +265,7 @@ impl ContentDecoder {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
Err(err) => Err(err),
|
||||
},
|
||||
|
||||
#[cfg(feature = "compress-gzip")]
|
||||
@ -280,7 +280,7 @@ impl ContentDecoder {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
Err(err) => Err(err),
|
||||
},
|
||||
|
||||
#[cfg(feature = "compress-zstd")]
|
||||
@ -295,7 +295,7 @@ impl ContentDecoder {
|
||||
Ok(None)
|
||||
}
|
||||
}
|
||||
Err(e) => Err(e),
|
||||
Err(err) => Err(err),
|
||||
},
|
||||
}
|
||||
}
|
||||
|
@ -50,10 +50,21 @@ impl<B: MessageBody> Encoder<B> {
|
||||
}
|
||||
}
|
||||
|
||||
fn empty() -> Self {
|
||||
Encoder {
|
||||
body: EncoderBody::Full { body: Bytes::new() },
|
||||
encoder: None,
|
||||
fut: None,
|
||||
eof: true,
|
||||
}
|
||||
}
|
||||
|
||||
pub fn response(encoding: ContentEncoding, head: &mut ResponseHead, body: B) -> Self {
|
||||
// no need to compress an empty body
|
||||
if matches!(body.size(), BodySize::None) {
|
||||
return Self::none();
|
||||
// no need to compress empty bodies
|
||||
match body.size() {
|
||||
BodySize::None => return Self::none(),
|
||||
BodySize::Sized(0) => return Self::empty(),
|
||||
_ => {}
|
||||
}
|
||||
|
||||
let should_encode = !(head.headers().contains_key(&CONTENT_ENCODING)
|
||||
|
@ -532,7 +532,7 @@ impl Decoder for PayloadDecoder {
|
||||
*state = match state.step(src, size, &mut buf) {
|
||||
Poll::Pending => return Ok(None),
|
||||
Poll::Ready(Ok(state)) => state,
|
||||
Poll::Ready(Err(e)) => return Err(e),
|
||||
Poll::Ready(Err(err)) => return Err(err),
|
||||
};
|
||||
|
||||
if *state == ChunkedState::End {
|
||||
|
@ -153,7 +153,7 @@ mod openssl {
|
||||
}
|
||||
|
||||
#[cfg(feature = "rustls-0_20")]
|
||||
mod rustls_020 {
|
||||
mod rustls_0_20 {
|
||||
use std::io;
|
||||
|
||||
use actix_service::ServiceFactoryExt as _;
|
||||
@ -214,7 +214,7 @@ mod rustls_020 {
|
||||
}
|
||||
|
||||
#[cfg(feature = "rustls-0_21")]
|
||||
mod rustls_021 {
|
||||
mod rustls_0_21 {
|
||||
use std::io;
|
||||
|
||||
use actix_service::ServiceFactoryExt as _;
|
||||
@ -274,6 +274,67 @@ mod rustls_021 {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rustls-0_22")]
|
||||
mod rustls_0_22 {
|
||||
use std::io;
|
||||
|
||||
use actix_service::ServiceFactoryExt as _;
|
||||
use actix_tls::accept::{
|
||||
rustls_0_22::{reexports::ServerConfig, Acceptor, TlsStream},
|
||||
TlsError,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
impl<S, B, X, U> H1Service<TlsStream<TcpStream>, S, B, X, U>
|
||||
where
|
||||
S: ServiceFactory<Request, Config = ()>,
|
||||
S::Future: 'static,
|
||||
S::Error: Into<Response<BoxBody>>,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>>,
|
||||
|
||||
B: MessageBody,
|
||||
|
||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||
X::Future: 'static,
|
||||
X::Error: Into<Response<BoxBody>>,
|
||||
X::InitError: fmt::Debug,
|
||||
|
||||
U: ServiceFactory<
|
||||
(Request, Framed<TlsStream<TcpStream>, Codec>),
|
||||
Config = (),
|
||||
Response = (),
|
||||
>,
|
||||
U::Future: 'static,
|
||||
U::Error: fmt::Display + Into<Response<BoxBody>>,
|
||||
U::InitError: fmt::Debug,
|
||||
{
|
||||
/// Create Rustls v0.22 based service.
|
||||
pub fn rustls_0_22(
|
||||
self,
|
||||
config: ServerConfig,
|
||||
) -> impl ServiceFactory<
|
||||
TcpStream,
|
||||
Config = (),
|
||||
Response = (),
|
||||
Error = TlsError<io::Error, DispatchError>,
|
||||
InitError = (),
|
||||
> {
|
||||
Acceptor::new(config)
|
||||
.map_init_err(|_| {
|
||||
unreachable!("TLS acceptor service factory does not error on init")
|
||||
})
|
||||
.map_err(TlsError::into_service_error)
|
||||
.map(|io: TlsStream<TcpStream>| {
|
||||
let peer_addr = io.get_ref().0.peer_addr().ok();
|
||||
(io, peer_addr)
|
||||
})
|
||||
.and_then(self.map_err(TlsError::Service))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, B, X, U> H1Service<T, S, B, X, U>
|
||||
where
|
||||
S: ServiceFactory<Request, Config = ()>,
|
||||
|
@ -141,7 +141,7 @@ mod openssl {
|
||||
}
|
||||
|
||||
#[cfg(feature = "rustls-0_20")]
|
||||
mod rustls_020 {
|
||||
mod rustls_0_20 {
|
||||
use std::io;
|
||||
|
||||
use actix_service::ServiceFactoryExt as _;
|
||||
@ -192,7 +192,7 @@ mod rustls_020 {
|
||||
}
|
||||
|
||||
#[cfg(feature = "rustls-0_21")]
|
||||
mod rustls_021 {
|
||||
mod rustls_0_21 {
|
||||
use std::io;
|
||||
|
||||
use actix_service::ServiceFactoryExt as _;
|
||||
@ -242,6 +242,57 @@ mod rustls_021 {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rustls-0_22")]
|
||||
mod rustls_0_22 {
|
||||
use std::io;
|
||||
|
||||
use actix_service::ServiceFactoryExt as _;
|
||||
use actix_tls::accept::{
|
||||
rustls_0_22::{reexports::ServerConfig, Acceptor, TlsStream},
|
||||
TlsError,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
impl<S, B> H2Service<TlsStream<TcpStream>, S, B>
|
||||
where
|
||||
S: ServiceFactory<Request, Config = ()>,
|
||||
S::Future: 'static,
|
||||
S::Error: Into<Response<BoxBody>> + 'static,
|
||||
S::Response: Into<Response<B>> + 'static,
|
||||
<S::Service as Service<Request>>::Future: 'static,
|
||||
|
||||
B: MessageBody + 'static,
|
||||
{
|
||||
/// Create Rustls v0.22 based service.
|
||||
pub fn rustls_0_22(
|
||||
self,
|
||||
mut config: ServerConfig,
|
||||
) -> impl ServiceFactory<
|
||||
TcpStream,
|
||||
Config = (),
|
||||
Response = (),
|
||||
Error = TlsError<io::Error, DispatchError>,
|
||||
InitError = S::InitError,
|
||||
> {
|
||||
let mut protos = vec![b"h2".to_vec()];
|
||||
protos.extend_from_slice(&config.alpn_protocols);
|
||||
config.alpn_protocols = protos;
|
||||
|
||||
Acceptor::new(config)
|
||||
.map_init_err(|_| {
|
||||
unreachable!("TLS acceptor service factory does not error on init")
|
||||
})
|
||||
.map_err(TlsError::into_service_error)
|
||||
.map(|io: TlsStream<TcpStream>| {
|
||||
let peer_addr = io.get_ref().0.peer_addr().ok();
|
||||
(io, peer_addr)
|
||||
})
|
||||
.and_then(self.map_err(TlsError::Service))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, B> ServiceFactory<(T, Option<net::SocketAddr>)> for H2Service<T, S, B>
|
||||
where
|
||||
T: AsyncRead + AsyncWrite + Unpin + 'static,
|
||||
|
@ -636,10 +636,24 @@ impl<'a> IntoIterator for &'a HeaderMap {
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert `http::HeaderMap` to our `HeaderMap`.
|
||||
/// Convert a `http::HeaderMap` to our `HeaderMap`.
|
||||
impl From<http::HeaderMap> for HeaderMap {
|
||||
fn from(mut map: http::HeaderMap) -> HeaderMap {
|
||||
HeaderMap::from_drain(map.drain())
|
||||
fn from(mut map: http::HeaderMap) -> Self {
|
||||
Self::from_drain(map.drain())
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert our `HeaderMap` to a `http::HeaderMap`.
|
||||
impl From<HeaderMap> for http::HeaderMap {
|
||||
fn from(map: HeaderMap) -> Self {
|
||||
Self::from_iter(map)
|
||||
}
|
||||
}
|
||||
|
||||
/// Convert our `&HeaderMap` to a `http::HeaderMap`.
|
||||
impl From<&HeaderMap> for http::HeaderMap {
|
||||
fn from(map: &HeaderMap) -> Self {
|
||||
map.to_owned().into()
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -1,6 +1,7 @@
|
||||
//! HTTP primitives for the Actix ecosystem.
|
||||
//! HTTP types and services for the Actix ecosystem.
|
||||
//!
|
||||
//! ## Crate Features
|
||||
//!
|
||||
//! | Feature | Functionality |
|
||||
//! | ------------------- | ------------------------------------------- |
|
||||
//! | `http2` | HTTP/2 support via [h2]. |
|
||||
@ -21,8 +22,7 @@
|
||||
#![allow(
|
||||
clippy::type_complexity,
|
||||
clippy::too_many_arguments,
|
||||
clippy::borrow_interior_mutable_const,
|
||||
clippy::uninlined_format_args
|
||||
clippy::borrow_interior_mutable_const
|
||||
)]
|
||||
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
|
||||
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
|
||||
@ -58,7 +58,12 @@ pub mod ws;
|
||||
|
||||
#[allow(deprecated)]
|
||||
pub use self::payload::PayloadStream;
|
||||
#[cfg(any(feature = "openssl", feature = "rustls-0_20", feature = "rustls-0_21"))]
|
||||
#[cfg(any(
|
||||
feature = "openssl",
|
||||
feature = "rustls-0_20",
|
||||
feature = "rustls-0_21",
|
||||
feature = "rustls-0_22",
|
||||
))]
|
||||
pub use self::service::TlsAcceptorConfig;
|
||||
pub use self::{
|
||||
builder::HttpServiceBuilder,
|
||||
|
@ -16,7 +16,10 @@ pub struct RequestHead {
|
||||
pub uri: Uri,
|
||||
pub version: Version,
|
||||
pub headers: HeaderMap,
|
||||
|
||||
/// Will only be None when called in unit tests unless set manually.
|
||||
pub peer_addr: Option<net::SocketAddr>,
|
||||
|
||||
flags: Flags,
|
||||
}
|
||||
|
||||
|
@ -173,7 +173,7 @@ impl<P> Request<P> {
|
||||
/// Peer address is the directly connected peer's socket address. If a proxy is used in front of
|
||||
/// the Actix Web server, then it would be address of this proxy.
|
||||
///
|
||||
/// Will only return None when called in unit tests.
|
||||
/// Will only return None when called in unit tests unless set manually.
|
||||
#[inline]
|
||||
pub fn peer_addr(&self) -> Option<net::SocketAddr> {
|
||||
self.head().peer_addr
|
||||
|
@ -93,7 +93,7 @@ impl ResponseBuilder {
|
||||
Ok((key, value)) => {
|
||||
parts.headers.insert(key, value);
|
||||
}
|
||||
Err(e) => self.err = Some(e.into()),
|
||||
Err(err) => self.err = Some(err.into()),
|
||||
};
|
||||
}
|
||||
|
||||
@ -119,7 +119,7 @@ impl ResponseBuilder {
|
||||
if let Some(parts) = self.inner() {
|
||||
match header.try_into_pair() {
|
||||
Ok((key, value)) => parts.headers.append(key, value),
|
||||
Err(e) => self.err = Some(e.into()),
|
||||
Err(err) => self.err = Some(err.into()),
|
||||
};
|
||||
}
|
||||
|
||||
@ -193,7 +193,7 @@ impl ResponseBuilder {
|
||||
Ok(value) => {
|
||||
parts.headers.insert(header::CONTENT_TYPE, value);
|
||||
}
|
||||
Err(e) => self.err = Some(e.into()),
|
||||
Err(err) => self.err = Some(err.into()),
|
||||
};
|
||||
}
|
||||
self
|
||||
|
@ -241,13 +241,23 @@ where
|
||||
}
|
||||
|
||||
/// Configuration options used when accepting TLS connection.
|
||||
#[cfg(any(feature = "openssl", feature = "rustls-0_20", feature = "rustls-0_21"))]
|
||||
#[cfg(any(
|
||||
feature = "openssl",
|
||||
feature = "rustls-0_20",
|
||||
feature = "rustls-0_21",
|
||||
feature = "rustls-0_22",
|
||||
))]
|
||||
#[derive(Debug, Default)]
|
||||
pub struct TlsAcceptorConfig {
|
||||
pub(crate) handshake_timeout: Option<std::time::Duration>,
|
||||
}
|
||||
|
||||
#[cfg(any(feature = "openssl", feature = "rustls-0_20", feature = "rustls-0_21"))]
|
||||
#[cfg(any(
|
||||
feature = "openssl",
|
||||
feature = "rustls-0_20",
|
||||
feature = "rustls-0_21",
|
||||
feature = "rustls-0_22",
|
||||
))]
|
||||
impl TlsAcceptorConfig {
|
||||
/// Set TLS handshake timeout duration.
|
||||
pub fn handshake_timeout(self, dur: std::time::Duration) -> Self {
|
||||
@ -353,12 +363,12 @@ mod openssl {
|
||||
}
|
||||
|
||||
#[cfg(feature = "rustls-0_20")]
|
||||
mod rustls_020 {
|
||||
mod rustls_0_20 {
|
||||
use std::io;
|
||||
|
||||
use actix_service::ServiceFactoryExt as _;
|
||||
use actix_tls::accept::{
|
||||
rustls::{reexports::ServerConfig, Acceptor, TlsStream},
|
||||
rustls_0_20::{reexports::ServerConfig, Acceptor, TlsStream},
|
||||
TlsError,
|
||||
};
|
||||
|
||||
@ -389,7 +399,7 @@ mod rustls_020 {
|
||||
U::Error: fmt::Display + Into<Response<BoxBody>>,
|
||||
U::InitError: fmt::Debug,
|
||||
{
|
||||
/// Create Rustls based service.
|
||||
/// Create Rustls v0.20 based service.
|
||||
pub fn rustls(
|
||||
self,
|
||||
config: ServerConfig,
|
||||
@ -403,7 +413,7 @@ mod rustls_020 {
|
||||
self.rustls_with_config(config, TlsAcceptorConfig::default())
|
||||
}
|
||||
|
||||
/// Create Rustls based service with custom TLS acceptor configuration.
|
||||
/// Create Rustls v0.20 based service with custom TLS acceptor configuration.
|
||||
pub fn rustls_with_config(
|
||||
self,
|
||||
mut config: ServerConfig,
|
||||
@ -449,7 +459,7 @@ mod rustls_020 {
|
||||
}
|
||||
|
||||
#[cfg(feature = "rustls-0_21")]
|
||||
mod rustls_021 {
|
||||
mod rustls_0_21 {
|
||||
use std::io;
|
||||
|
||||
use actix_service::ServiceFactoryExt as _;
|
||||
@ -485,7 +495,7 @@ mod rustls_021 {
|
||||
U::Error: fmt::Display + Into<Response<BoxBody>>,
|
||||
U::InitError: fmt::Debug,
|
||||
{
|
||||
/// Create Rustls based service.
|
||||
/// Create Rustls v0.21 based service.
|
||||
pub fn rustls_021(
|
||||
self,
|
||||
config: ServerConfig,
|
||||
@ -499,7 +509,7 @@ mod rustls_021 {
|
||||
self.rustls_021_with_config(config, TlsAcceptorConfig::default())
|
||||
}
|
||||
|
||||
/// Create Rustls based service with custom TLS acceptor configuration.
|
||||
/// Create Rustls v0.21 based service with custom TLS acceptor configuration.
|
||||
pub fn rustls_021_with_config(
|
||||
self,
|
||||
mut config: ServerConfig,
|
||||
@ -544,6 +554,102 @@ mod rustls_021 {
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "rustls-0_22")]
|
||||
mod rustls_0_22 {
|
||||
use std::io;
|
||||
|
||||
use actix_service::ServiceFactoryExt as _;
|
||||
use actix_tls::accept::{
|
||||
rustls_0_22::{reexports::ServerConfig, Acceptor, TlsStream},
|
||||
TlsError,
|
||||
};
|
||||
|
||||
use super::*;
|
||||
|
||||
impl<S, B, X, U> HttpService<TlsStream<TcpStream>, S, B, X, U>
|
||||
where
|
||||
S: ServiceFactory<Request, Config = ()>,
|
||||
S::Future: 'static,
|
||||
S::Error: Into<Response<BoxBody>> + 'static,
|
||||
S::InitError: fmt::Debug,
|
||||
S::Response: Into<Response<B>> + 'static,
|
||||
<S::Service as Service<Request>>::Future: 'static,
|
||||
|
||||
B: MessageBody + 'static,
|
||||
|
||||
X: ServiceFactory<Request, Config = (), Response = Request>,
|
||||
X::Future: 'static,
|
||||
X::Error: Into<Response<BoxBody>>,
|
||||
X::InitError: fmt::Debug,
|
||||
|
||||
U: ServiceFactory<
|
||||
(Request, Framed<TlsStream<TcpStream>, h1::Codec>),
|
||||
Config = (),
|
||||
Response = (),
|
||||
>,
|
||||
U::Future: 'static,
|
||||
U::Error: fmt::Display + Into<Response<BoxBody>>,
|
||||
U::InitError: fmt::Debug,
|
||||
{
|
||||
/// Create Rustls v0.22 based service.
|
||||
pub fn rustls_0_22(
|
||||
self,
|
||||
config: ServerConfig,
|
||||
) -> impl ServiceFactory<
|
||||
TcpStream,
|
||||
Config = (),
|
||||
Response = (),
|
||||
Error = TlsError<io::Error, DispatchError>,
|
||||
InitError = (),
|
||||
> {
|
||||
self.rustls_0_22_with_config(config, TlsAcceptorConfig::default())
|
||||
}
|
||||
|
||||
/// Create Rustls v0.22 based service with custom TLS acceptor configuration.
|
||||
pub fn rustls_0_22_with_config(
|
||||
self,
|
||||
mut config: ServerConfig,
|
||||
tls_acceptor_config: TlsAcceptorConfig,
|
||||
) -> impl ServiceFactory<
|
||||
TcpStream,
|
||||
Config = (),
|
||||
Response = (),
|
||||
Error = TlsError<io::Error, DispatchError>,
|
||||
InitError = (),
|
||||
> {
|
||||
let mut protos = vec![b"h2".to_vec(), b"http/1.1".to_vec()];
|
||||
protos.extend_from_slice(&config.alpn_protocols);
|
||||
config.alpn_protocols = protos;
|
||||
|
||||
let mut acceptor = Acceptor::new(config);
|
||||
|
||||
if let Some(handshake_timeout) = tls_acceptor_config.handshake_timeout {
|
||||
acceptor.set_handshake_timeout(handshake_timeout);
|
||||
}
|
||||
|
||||
acceptor
|
||||
.map_init_err(|_| {
|
||||
unreachable!("TLS acceptor service factory does not error on init")
|
||||
})
|
||||
.map_err(TlsError::into_service_error)
|
||||
.and_then(|io: TlsStream<TcpStream>| async {
|
||||
let proto = if let Some(protos) = io.get_ref().1.alpn_protocol() {
|
||||
if protos.windows(2).any(|window| window == b"h2") {
|
||||
Protocol::Http2
|
||||
} else {
|
||||
Protocol::Http1
|
||||
}
|
||||
} else {
|
||||
Protocol::Http1
|
||||
};
|
||||
let peer_addr = io.get_ref().0.peer_addr().ok();
|
||||
Ok((io, proto, peer_addr))
|
||||
})
|
||||
.and_then(self.map_err(TlsError::Service))
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl<T, S, B, X, U> ServiceFactory<(T, Protocol, Option<net::SocketAddr>)>
|
||||
for HttpService<T, S, B, X, U>
|
||||
where
|
||||
|
@ -296,7 +296,7 @@ impl Decoder for Codec {
|
||||
}
|
||||
}
|
||||
Ok(None) => Ok(None),
|
||||
Err(e) => Err(e),
|
||||
Err(err) => Err(err),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -1,5 +1,4 @@
|
||||
#![cfg(feature = "openssl")]
|
||||
#![allow(clippy::uninlined_format_args)]
|
||||
|
||||
extern crate tls_openssl as openssl;
|
||||
|
||||
|
@ -1,6 +1,6 @@
|
||||
#![cfg(feature = "rustls-0_21")]
|
||||
#![cfg(feature = "rustls-0_22")]
|
||||
|
||||
extern crate tls_rustls_021 as rustls;
|
||||
extern crate tls_rustls_022 as rustls;
|
||||
|
||||
use std::{
|
||||
convert::Infallible,
|
||||
@ -20,13 +20,13 @@ use actix_http::{
|
||||
use actix_http_test::test_server;
|
||||
use actix_rt::pin;
|
||||
use actix_service::{fn_factory_with_config, fn_service};
|
||||
use actix_tls::connect::rustls_0_21::webpki_roots_cert_store;
|
||||
use actix_tls::connect::rustls_0_22::webpki_roots_cert_store;
|
||||
use actix_utils::future::{err, ok, poll_fn};
|
||||
use bytes::{Bytes, BytesMut};
|
||||
use derive_more::{Display, Error};
|
||||
use futures_core::{ready, Stream};
|
||||
use futures_util::stream::once;
|
||||
use rustls::{Certificate, PrivateKey, ServerConfig as RustlsServerConfig, ServerName};
|
||||
use rustls::{pki_types::ServerName, ServerConfig as RustlsServerConfig};
|
||||
use rustls_pemfile::{certs, pkcs8_private_keys};
|
||||
|
||||
async fn load_body<S>(stream: S) -> Result<BytesMut, PayloadError>
|
||||
@ -59,17 +59,17 @@ fn tls_config() -> RustlsServerConfig {
|
||||
let cert_file = &mut BufReader::new(cert_file.as_bytes());
|
||||
let key_file = &mut BufReader::new(key_file.as_bytes());
|
||||
|
||||
let cert_chain = certs(cert_file)
|
||||
.unwrap()
|
||||
.into_iter()
|
||||
.map(Certificate)
|
||||
.collect();
|
||||
let mut keys = pkcs8_private_keys(key_file).unwrap();
|
||||
let cert_chain = certs(cert_file).collect::<Result<Vec<_>, _>>().unwrap();
|
||||
let mut keys = pkcs8_private_keys(key_file)
|
||||
.collect::<Result<Vec<_>, _>>()
|
||||
.unwrap();
|
||||
|
||||
let mut config = RustlsServerConfig::builder()
|
||||
.with_safe_defaults()
|
||||
.with_no_client_auth()
|
||||
.with_single_cert(cert_chain, PrivateKey(keys.remove(0)))
|
||||
.with_single_cert(
|
||||
cert_chain,
|
||||
rustls::pki_types::PrivateKeyDer::Pkcs8(keys.remove(0)),
|
||||
)
|
||||
.unwrap();
|
||||
|
||||
config.alpn_protocols.push(HTTP1_1_ALPN_PROTOCOL.to_vec());
|
||||
@ -83,7 +83,6 @@ pub fn get_negotiated_alpn_protocol(
|
||||
client_alpn_protocol: &[u8],
|
||||
) -> Option<Vec<u8>> {
|
||||
let mut config = rustls::ClientConfig::builder()
|
||||
.with_safe_defaults()
|
||||
.with_root_certificates(webpki_roots_cert_store())
|
||||
.with_no_client_auth();
|
||||
|
||||
@ -109,7 +108,7 @@ async fn h1() -> io::Result<()> {
|
||||
let srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.h1(|_| ok::<_, Error>(Response::ok()))
|
||||
.rustls_021(tls_config())
|
||||
.rustls_0_22(tls_config())
|
||||
})
|
||||
.await;
|
||||
|
||||
@ -123,7 +122,7 @@ async fn h2() -> io::Result<()> {
|
||||
let srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.h2(|_| ok::<_, Error>(Response::ok()))
|
||||
.rustls_021(tls_config())
|
||||
.rustls_0_22(tls_config())
|
||||
})
|
||||
.await;
|
||||
|
||||
@ -141,7 +140,7 @@ async fn h1_1() -> io::Result<()> {
|
||||
assert_eq!(req.version(), Version::HTTP_11);
|
||||
ok::<_, Error>(Response::ok())
|
||||
})
|
||||
.rustls_021(tls_config())
|
||||
.rustls_0_22(tls_config())
|
||||
})
|
||||
.await;
|
||||
|
||||
@ -159,7 +158,7 @@ async fn h2_1() -> io::Result<()> {
|
||||
assert_eq!(req.version(), Version::HTTP_2);
|
||||
ok::<_, Error>(Response::ok())
|
||||
})
|
||||
.rustls_021_with_config(
|
||||
.rustls_0_22_with_config(
|
||||
tls_config(),
|
||||
TlsAcceptorConfig::default().handshake_timeout(Duration::from_secs(5)),
|
||||
)
|
||||
@ -180,7 +179,7 @@ async fn h2_body1() -> io::Result<()> {
|
||||
let body = load_body(req.take_payload()).await?;
|
||||
Ok::<_, Error>(Response::ok().set_body(body))
|
||||
})
|
||||
.rustls_021(tls_config())
|
||||
.rustls_0_22(tls_config())
|
||||
})
|
||||
.await;
|
||||
|
||||
@ -206,7 +205,7 @@ async fn h2_content_length() {
|
||||
];
|
||||
ok::<_, Infallible>(Response::new(statuses[indx]))
|
||||
})
|
||||
.rustls_021(tls_config())
|
||||
.rustls_0_22(tls_config())
|
||||
})
|
||||
.await;
|
||||
|
||||
@ -278,7 +277,7 @@ async fn h2_headers() {
|
||||
}
|
||||
ok::<_, Infallible>(config.body(data.clone()))
|
||||
})
|
||||
.rustls_021(tls_config())
|
||||
.rustls_0_22(tls_config())
|
||||
})
|
||||
.await;
|
||||
|
||||
@ -317,7 +316,7 @@ async fn h2_body2() {
|
||||
let mut srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.h2(|_| ok::<_, Infallible>(Response::ok().set_body(STR)))
|
||||
.rustls_021(tls_config())
|
||||
.rustls_0_22(tls_config())
|
||||
})
|
||||
.await;
|
||||
|
||||
@ -334,7 +333,7 @@ async fn h2_head_empty() {
|
||||
let mut srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.finish(|_| ok::<_, Infallible>(Response::ok().set_body(STR)))
|
||||
.rustls_021(tls_config())
|
||||
.rustls_0_22(tls_config())
|
||||
})
|
||||
.await;
|
||||
|
||||
@ -360,7 +359,7 @@ async fn h2_head_binary() {
|
||||
let mut srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.h2(|_| ok::<_, Infallible>(Response::ok().set_body(STR)))
|
||||
.rustls_021(tls_config())
|
||||
.rustls_0_22(tls_config())
|
||||
})
|
||||
.await;
|
||||
|
||||
@ -385,7 +384,7 @@ async fn h2_head_binary2() {
|
||||
let srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.h2(|_| ok::<_, Infallible>(Response::ok().set_body(STR)))
|
||||
.rustls_021(tls_config())
|
||||
.rustls_0_22(tls_config())
|
||||
})
|
||||
.await;
|
||||
|
||||
@ -411,7 +410,7 @@ async fn h2_body_length() {
|
||||
Response::ok().set_body(SizedStream::new(STR.len() as u64, body)),
|
||||
)
|
||||
})
|
||||
.rustls_021(tls_config())
|
||||
.rustls_0_22(tls_config())
|
||||
})
|
||||
.await;
|
||||
|
||||
@ -435,7 +434,7 @@ async fn h2_body_chunked_explicit() {
|
||||
.body(BodyStream::new(body)),
|
||||
)
|
||||
})
|
||||
.rustls_021(tls_config())
|
||||
.rustls_0_22(tls_config())
|
||||
})
|
||||
.await;
|
||||
|
||||
@ -464,7 +463,7 @@ async fn h2_response_http_error_handling() {
|
||||
)
|
||||
}))
|
||||
}))
|
||||
.rustls_021(tls_config())
|
||||
.rustls_0_22(tls_config())
|
||||
})
|
||||
.await;
|
||||
|
||||
@ -494,7 +493,7 @@ async fn h2_service_error() {
|
||||
let mut srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.h2(|_| err::<Response<BoxBody>, _>(BadRequest))
|
||||
.rustls_021(tls_config())
|
||||
.rustls_0_22(tls_config())
|
||||
})
|
||||
.await;
|
||||
|
||||
@ -511,7 +510,7 @@ async fn h1_service_error() {
|
||||
let mut srv = test_server(move || {
|
||||
HttpService::build()
|
||||
.h1(|_| err::<Response<BoxBody>, _>(BadRequest))
|
||||
.rustls_021(tls_config())
|
||||
.rustls_0_22(tls_config())
|
||||
})
|
||||
.await;
|
||||
|
||||
@ -534,7 +533,7 @@ async fn alpn_h1() -> io::Result<()> {
|
||||
config.alpn_protocols.push(CUSTOM_ALPN_PROTOCOL.to_vec());
|
||||
HttpService::build()
|
||||
.h1(|_| ok::<_, Error>(Response::ok()))
|
||||
.rustls_021(config)
|
||||
.rustls_0_22(config)
|
||||
})
|
||||
.await;
|
||||
|
||||
@ -556,7 +555,7 @@ async fn alpn_h2() -> io::Result<()> {
|
||||
config.alpn_protocols.push(CUSTOM_ALPN_PROTOCOL.to_vec());
|
||||
HttpService::build()
|
||||
.h2(|_| ok::<_, Error>(Response::ok()))
|
||||
.rustls_021(config)
|
||||
.rustls_0_22(config)
|
||||
})
|
||||
.await;
|
||||
|
||||
@ -582,7 +581,7 @@ async fn alpn_h2_1() -> io::Result<()> {
|
||||
config.alpn_protocols.push(CUSTOM_ALPN_PROTOCOL.to_vec());
|
||||
HttpService::build()
|
||||
.finish(|_| ok::<_, Error>(Response::ok()))
|
||||
.rustls_021(config)
|
||||
.rustls_0_22(config)
|
||||
})
|
||||
.await;
|
||||
|
||||
|
@ -147,7 +147,7 @@ async fn chunked_payload() {
|
||||
.take_payload()
|
||||
.map(|res| match res {
|
||||
Ok(pl) => pl,
|
||||
Err(e) => panic!("Error reading payload: {}", e),
|
||||
Err(err) => panic!("Error reading payload: {err}"),
|
||||
})
|
||||
.fold(0usize, |acc, chunk| ready(acc + chunk.len()))
|
||||
.map(|req_size| {
|
||||
|
@ -1,5 +1,3 @@
|
||||
#![allow(clippy::uninlined_format_args)]
|
||||
|
||||
use std::{
|
||||
cell::Cell,
|
||||
convert::Infallible,
|
||||
|
@ -5,7 +5,7 @@ authors = ["Jacob Halsey <jacob@jhalsey.com>"]
|
||||
description = "Multipart form derive macro for Actix Web"
|
||||
keywords = ["http", "web", "framework", "async", "futures"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-web.git"
|
||||
repository = "https://github.com/actix/actix-web"
|
||||
license = "MIT OR Apache-2.0"
|
||||
edition = "2021"
|
||||
|
||||
|
@ -1,16 +1,20 @@
|
||||
# actix-multipart-derive
|
||||
# `actix-multipart-derive`
|
||||
|
||||
> The derive macro implementation for actix-multipart-derive.
|
||||
|
||||
<!-- prettier-ignore-start -->
|
||||
|
||||
[](https://crates.io/crates/actix-multipart-derive)
|
||||
[](https://docs.rs/actix-multipart-derive/0.5.0)
|
||||
[](https://docs.rs/actix-multipart-derive/0.6.1)
|
||||

|
||||

|
||||
<br />
|
||||
[](https://deps.rs/crate/actix-multipart-derive/0.5.0)
|
||||
[](https://deps.rs/crate/actix-multipart-derive/0.6.1)
|
||||
[](https://crates.io/crates/actix-multipart-derive)
|
||||
[](https://discord.gg/NWpN5mmg3x)
|
||||
|
||||
<!-- prettier-ignore-end -->
|
||||
|
||||
## Documentation & Resources
|
||||
|
||||
- [API Documentation](https://docs.rs/actix-multipart-derive)
|
||||
|
@ -8,7 +8,7 @@ authors = [
|
||||
description = "Multipart form support for Actix Web"
|
||||
keywords = ["http", "web", "framework", "async", "futures"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-web.git"
|
||||
repository = "https://github.com/actix/actix-web"
|
||||
license = "MIT OR Apache-2.0"
|
||||
edition = "2021"
|
||||
|
||||
|
@ -1,7 +1,9 @@
|
||||
# actix-multipart
|
||||
# `actix-multipart`
|
||||
|
||||
> Multipart form support for Actix Web.
|
||||
|
||||
<!-- prettier-ignore-start -->
|
||||
|
||||
[](https://crates.io/crates/actix-multipart)
|
||||
[](https://docs.rs/actix-multipart/0.6.1)
|
||||

|
||||
@ -11,6 +13,8 @@
|
||||
[](https://crates.io/crates/actix-multipart)
|
||||
[](https://discord.gg/NWpN5mmg3x)
|
||||
|
||||
<!-- prettier-ignore-end -->
|
||||
|
||||
## Documentation & Resources
|
||||
|
||||
- [API Documentation](https://docs.rs/actix-multipart)
|
||||
|
@ -2,7 +2,7 @@
|
||||
|
||||
#![deny(rust_2018_idioms, nonstandard_style)]
|
||||
#![warn(future_incompatible)]
|
||||
#![allow(clippy::borrow_interior_mutable_const, clippy::uninlined_format_args)]
|
||||
#![allow(clippy::borrow_interior_mutable_const)]
|
||||
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
|
||||
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||
|
@ -2,6 +2,8 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
## 0.5.2
|
||||
|
||||
- Minimum supported Rust version (MSRV) is now 1.68 due to transitive `time` dependency.
|
||||
|
||||
## 0.5.1
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-router"
|
||||
version = "0.5.1"
|
||||
version = "0.5.2"
|
||||
authors = [
|
||||
"Nikolay Kim <fafhrd91@gmail.com>",
|
||||
"Ali MJ Al-Nasrawy <alimjalnasrawy@gmail.com>",
|
||||
@ -8,7 +8,7 @@ authors = [
|
||||
]
|
||||
description = "Resource path matching and router"
|
||||
keywords = ["actix", "router", "routing"]
|
||||
repository = "https://github.com/actix/actix-web.git"
|
||||
repository = "https://github.com/actix/actix-web"
|
||||
license = "MIT OR Apache-2.0"
|
||||
edition = "2021"
|
||||
|
||||
|
20
actix-router/README.md
Normal file
20
actix-router/README.md
Normal file
@ -0,0 +1,20 @@
|
||||
# `actix-router`
|
||||
|
||||
<!-- prettier-ignore-start -->
|
||||
|
||||
[](https://crates.io/crates/actix-router)
|
||||
[](https://docs.rs/actix-router/0.5.2)
|
||||

|
||||

|
||||
<br />
|
||||
[](https://deps.rs/crate/actix-router/0.5.2)
|
||||
[](https://crates.io/crates/actix-router)
|
||||
[](https://discord.gg/NWpN5mmg3x)
|
||||
|
||||
<!-- prettier-ignore-end -->
|
||||
|
||||
<!-- cargo-rdme start -->
|
||||
|
||||
Resource path matching and router.
|
||||
|
||||
<!-- cargo-rdme end -->
|
@ -1,5 +1,3 @@
|
||||
#![allow(clippy::uninlined_format_args)]
|
||||
|
||||
use std::{borrow::Cow, fmt::Write as _};
|
||||
|
||||
use criterion::{black_box, criterion_group, criterion_main, Criterion};
|
||||
|
@ -2,7 +2,6 @@
|
||||
|
||||
#![deny(rust_2018_idioms, nonstandard_style)]
|
||||
#![warn(future_incompatible)]
|
||||
#![allow(clippy::uninlined_format_args)]
|
||||
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
|
||||
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||
|
@ -3,7 +3,7 @@ use std::{
|
||||
ops::{DerefMut, Index},
|
||||
};
|
||||
|
||||
use serde::de;
|
||||
use serde::{de, Deserialize};
|
||||
|
||||
use crate::{de::PathDeserializer, Resource, ResourcePath};
|
||||
|
||||
@ -24,8 +24,13 @@ impl Default for PathItem {
|
||||
/// If resource path contains variable patterns, `Path` stores them.
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct Path<T> {
|
||||
/// Full path representation.
|
||||
path: T,
|
||||
|
||||
/// Number of characters in `path` that have been processed into `segments`.
|
||||
pub(crate) skip: u16,
|
||||
|
||||
/// List of processed dynamic segments; name->value pairs.
|
||||
pub(crate) segments: Vec<(Cow<'static, str>, PathItem)>,
|
||||
}
|
||||
|
||||
@ -83,8 +88,8 @@ impl<T: ResourcePath> Path<T> {
|
||||
/// Set new path.
|
||||
#[inline]
|
||||
pub fn set(&mut self, path: T) {
|
||||
self.skip = 0;
|
||||
self.path = path;
|
||||
self.skip = 0;
|
||||
self.segments.clear();
|
||||
}
|
||||
|
||||
@ -103,7 +108,7 @@ impl<T: ResourcePath> Path<T> {
|
||||
|
||||
pub(crate) fn add(&mut self, name: impl Into<Cow<'static, str>>, value: PathItem) {
|
||||
match value {
|
||||
PathItem::Static(s) => self.segments.push((name.into(), PathItem::Static(s))),
|
||||
PathItem::Static(seg) => self.segments.push((name.into(), PathItem::Static(seg))),
|
||||
PathItem::Segment(begin, end) => self.segments.push((
|
||||
name.into(),
|
||||
PathItem::Segment(self.skip + begin, self.skip + end),
|
||||
@ -168,9 +173,13 @@ impl<T: ResourcePath> Path<T> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Try to deserialize matching parameters to a specified type `U`
|
||||
pub fn load<'de, U: serde::Deserialize<'de>>(&'de self) -> Result<U, de::value::Error> {
|
||||
de::Deserialize::deserialize(PathDeserializer::new(self))
|
||||
/// Deserializes matching parameters to a specified type `U`.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns error when dynamic path segments cannot be deserialized into a `U` type.
|
||||
pub fn load<'de, U: Deserialize<'de>>(&'de self) -> Result<U, de::value::Error> {
|
||||
Deserialize::deserialize(PathDeserializer::new(self))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -193,8 +193,8 @@ const REGEX_FLAGS: &str = "(?s-m)";
|
||||
/// # Trailing Slashes
|
||||
/// It should be noted that this library takes no steps to normalize intra-path or trailing slashes.
|
||||
/// As such, all resource definitions implicitly expect a pre-processing step to normalize paths if
|
||||
/// they you wish to accommodate "recoverable" path errors. Below are several examples of
|
||||
/// resource-path pairs that would not be compatible.
|
||||
/// you wish to accommodate "recoverable" path errors. Below are several examples of resource-path
|
||||
/// pairs that would not be compatible.
|
||||
///
|
||||
/// ## Examples
|
||||
/// ```
|
||||
|
@ -97,6 +97,7 @@ impl<T, U> RouterBuilder<T, U> {
|
||||
ctx: U,
|
||||
) -> (&mut ResourceDef, &mut T, &mut U) {
|
||||
self.routes.push((rdef, val, ctx));
|
||||
#[allow(clippy::map_identity)] // map is used to distribute &mut-ness to tuple elements
|
||||
self.routes
|
||||
.last_mut()
|
||||
.map(|(rdef, val, ctx)| (rdef, val, ctx))
|
||||
@ -186,11 +187,11 @@ mod tests {
|
||||
assert_eq!(path.get("file").unwrap(), "file");
|
||||
assert_eq!(path.get("ext").unwrap(), "gz");
|
||||
|
||||
let mut path = Path::new("/vtest/ttt/index.html");
|
||||
let mut path = Path::new("/v2/ttt/index.html");
|
||||
let (h, info) = router.recognize_mut(&mut path).unwrap();
|
||||
assert_eq!(*h, 14);
|
||||
assert_eq!(info, ResourceId(4));
|
||||
assert_eq!(path.get("val").unwrap(), "test");
|
||||
assert_eq!(path.get("val").unwrap(), "2");
|
||||
assert_eq!(path.get("val2").unwrap(), "ttt");
|
||||
|
||||
let mut path = Path::new("/v/blah-blah/index.html");
|
||||
|
@ -2,6 +2,12 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
## 0.1.3
|
||||
|
||||
- Add `TestServerConfig::rustls_0_22()` method for Rustls v0.22 support behind new `rustls-0_22` crate feature.
|
||||
|
||||
## 0.1.2
|
||||
|
||||
- Add `TestServerConfig::rustls_021()` method for Rustls v0.21 support behind new `rustls-0_21` crate feature.
|
||||
- Add `TestServerConfig::workers()` method.
|
||||
- Add `rustls-0_20` crate feature, which the existing `rustls` feature now aliases.
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-test"
|
||||
version = "0.1.1"
|
||||
version = "0.1.3"
|
||||
authors = [
|
||||
"Nikolay Kim <fafhrd91@gmail.com>",
|
||||
"Rob Ede <robjtede@icloud.com>",
|
||||
@ -8,7 +8,7 @@ authors = [
|
||||
description = "Integration testing tools for Actix Web applications"
|
||||
keywords = ["http", "web", "framework", "async", "futures"]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-web.git"
|
||||
repository = "https://github.com/actix/actix-web"
|
||||
categories = [
|
||||
"network-programming",
|
||||
"asynchronous",
|
||||
@ -27,19 +27,21 @@ rustls = ["rustls-0_20"]
|
||||
rustls-0_20 = ["tls-rustls-0_20", "actix-http/rustls-0_20", "awc/rustls-0_20"]
|
||||
# TLS via Rustls v0.21
|
||||
rustls-0_21 = ["tls-rustls-0_21", "actix-http/rustls-0_21", "awc/rustls-0_21"]
|
||||
# TLS via Rustls v0.22
|
||||
rustls-0_22 = ["tls-rustls-0_22", "actix-http/rustls-0_22", "awc/rustls-0_22-webpki-roots"]
|
||||
|
||||
# TLS via OpenSSL
|
||||
openssl = ["tls-openssl", "actix-http/openssl", "awc/openssl"]
|
||||
|
||||
[dependencies]
|
||||
actix-codec = "0.5"
|
||||
actix-http = "3"
|
||||
actix-http = "3.6"
|
||||
actix-http-test = "3"
|
||||
actix-rt = "2.1"
|
||||
actix-service = "2"
|
||||
actix-utils = "3"
|
||||
actix-web = { version = "4", default-features = false, features = ["cookies"] }
|
||||
awc = { version = "3", default-features = false, features = ["cookies"] }
|
||||
actix-web = { version = "4.5", default-features = false, features = ["cookies"] }
|
||||
awc = { version = "3.4", default-features = false, features = ["cookies"] }
|
||||
|
||||
futures-core = { version = "0.3.17", default-features = false, features = ["std"] }
|
||||
futures-util = { version = "0.3.17", default-features = false, features = [] }
|
||||
@ -50,4 +52,5 @@ serde_urlencoded = "0.7"
|
||||
tls-openssl = { package = "openssl", version = "0.10.55", optional = true }
|
||||
tls-rustls-0_20 = { package = "rustls", version = "0.20", optional = true }
|
||||
tls-rustls-0_21 = { package = "rustls", version = "0.21", optional = true }
|
||||
tls-rustls-0_22 = { package = "rustls", version = "0.22", optional = true }
|
||||
tokio = { version = "1.24.2", features = ["sync"] }
|
||||
|
@ -143,6 +143,8 @@ where
|
||||
StreamType::Rustls020(_) => true,
|
||||
#[cfg(feature = "rustls-0_21")]
|
||||
StreamType::Rustls021(_) => true,
|
||||
#[cfg(feature = "rustls-0_22")]
|
||||
StreamType::Rustls022(_) => true,
|
||||
};
|
||||
|
||||
// run server in separate orphaned thread
|
||||
@ -327,6 +329,48 @@ where
|
||||
.rustls_021(config.clone())
|
||||
}),
|
||||
},
|
||||
#[cfg(feature = "rustls-0_22")]
|
||||
StreamType::Rustls022(config) => match cfg.tp {
|
||||
HttpVer::Http1 => builder.listen("test", tcp, move || {
|
||||
let app_cfg =
|
||||
AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);
|
||||
|
||||
let fac = factory()
|
||||
.into_factory()
|
||||
.map_err(|err| err.into().error_response());
|
||||
|
||||
HttpService::build()
|
||||
.client_request_timeout(timeout)
|
||||
.h1(map_config(fac, move |_| app_cfg.clone()))
|
||||
.rustls_0_22(config.clone())
|
||||
}),
|
||||
HttpVer::Http2 => builder.listen("test", tcp, move || {
|
||||
let app_cfg =
|
||||
AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);
|
||||
|
||||
let fac = factory()
|
||||
.into_factory()
|
||||
.map_err(|err| err.into().error_response());
|
||||
|
||||
HttpService::build()
|
||||
.client_request_timeout(timeout)
|
||||
.h2(map_config(fac, move |_| app_cfg.clone()))
|
||||
.rustls_0_22(config.clone())
|
||||
}),
|
||||
HttpVer::Both => builder.listen("test", tcp, move || {
|
||||
let app_cfg =
|
||||
AppConfig::__priv_test_new(false, local_addr.to_string(), local_addr);
|
||||
|
||||
let fac = factory()
|
||||
.into_factory()
|
||||
.map_err(|err| err.into().error_response());
|
||||
|
||||
HttpService::build()
|
||||
.client_request_timeout(timeout)
|
||||
.finish(map_config(fac, move |_| app_cfg.clone()))
|
||||
.rustls_0_22(config.clone())
|
||||
}),
|
||||
},
|
||||
}
|
||||
.expect("test server could not be created");
|
||||
|
||||
@ -401,6 +445,8 @@ enum StreamType {
|
||||
Rustls020(tls_rustls_0_20::ServerConfig),
|
||||
#[cfg(feature = "rustls-0_21")]
|
||||
Rustls021(tls_rustls_0_21::ServerConfig),
|
||||
#[cfg(feature = "rustls-0_22")]
|
||||
Rustls022(tls_rustls_0_22::ServerConfig),
|
||||
}
|
||||
|
||||
/// Create default test server config.
|
||||
@ -424,7 +470,7 @@ impl Default for TestServerConfig {
|
||||
}
|
||||
|
||||
impl TestServerConfig {
|
||||
/// Create default server configuration
|
||||
/// Constructs default server configuration.
|
||||
pub(crate) fn new() -> TestServerConfig {
|
||||
TestServerConfig {
|
||||
tp: HttpVer::Both,
|
||||
@ -435,40 +481,63 @@ impl TestServerConfig {
|
||||
}
|
||||
}
|
||||
|
||||
/// Accept HTTP/1.1 only.
|
||||
/// Accepts HTTP/1.1 only.
|
||||
pub fn h1(mut self) -> Self {
|
||||
self.tp = HttpVer::Http1;
|
||||
self
|
||||
}
|
||||
|
||||
/// Accept HTTP/2 only.
|
||||
/// Accepts HTTP/2 only.
|
||||
pub fn h2(mut self) -> Self {
|
||||
self.tp = HttpVer::Http2;
|
||||
self
|
||||
}
|
||||
|
||||
/// Accept secure connections via OpenSSL.
|
||||
/// Accepts secure connections via OpenSSL.
|
||||
#[cfg(feature = "openssl")]
|
||||
pub fn openssl(mut self, acceptor: openssl::ssl::SslAcceptor) -> Self {
|
||||
self.stream = StreamType::Openssl(acceptor);
|
||||
self
|
||||
}
|
||||
|
||||
/// Accept secure connections via Rustls.
|
||||
#[doc(hidden)]
|
||||
#[deprecated(note = "Renamed to `rustls_0_20()`.")]
|
||||
#[cfg(feature = "rustls-0_20")]
|
||||
pub fn rustls(mut self, config: tls_rustls_0_20::ServerConfig) -> Self {
|
||||
self.stream = StreamType::Rustls020(config);
|
||||
self
|
||||
}
|
||||
|
||||
/// Accept secure connections via Rustls.
|
||||
/// Accepts secure connections via Rustls v0.20.
|
||||
#[cfg(feature = "rustls-0_20")]
|
||||
pub fn rustls_0_20(mut self, config: tls_rustls_0_20::ServerConfig) -> Self {
|
||||
self.stream = StreamType::Rustls020(config);
|
||||
self
|
||||
}
|
||||
|
||||
#[doc(hidden)]
|
||||
#[deprecated(note = "Renamed to `rustls_0_21()`.")]
|
||||
#[cfg(feature = "rustls-0_21")]
|
||||
pub fn rustls_021(mut self, config: tls_rustls_0_21::ServerConfig) -> Self {
|
||||
self.stream = StreamType::Rustls021(config);
|
||||
self
|
||||
}
|
||||
|
||||
/// Set client timeout for first request.
|
||||
/// Accepts secure connections via Rustls v0.21.
|
||||
#[cfg(feature = "rustls-0_21")]
|
||||
pub fn rustls_0_21(mut self, config: tls_rustls_0_21::ServerConfig) -> Self {
|
||||
self.stream = StreamType::Rustls021(config);
|
||||
self
|
||||
}
|
||||
|
||||
/// Accepts secure connections via Rustls v0.22.
|
||||
#[cfg(feature = "rustls-0_22")]
|
||||
pub fn rustls_0_22(mut self, config: tls_rustls_0_22::ServerConfig) -> Self {
|
||||
self.stream = StreamType::Rustls022(config);
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets client timeout for first request.
|
||||
pub fn client_request_timeout(mut self, dur: Duration) -> Self {
|
||||
self.client_request_timeout = dur;
|
||||
self
|
||||
|
@ -2,6 +2,8 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
## 4.3.0
|
||||
|
||||
- Minimum supported Rust version (MSRV) is now 1.68 due to transitive `time` dependency.
|
||||
|
||||
## 4.2.0
|
||||
|
@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "actix-web-actors"
|
||||
version = "4.2.0"
|
||||
version = "4.3.0"
|
||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
||||
description = "Actix actors support for Actix Web"
|
||||
keywords = ["actix", "http", "web", "framework", "async"]
|
||||
|
@ -1,16 +1,20 @@
|
||||
# actix-web-actors
|
||||
# `actix-web-actors`
|
||||
|
||||
> Actix actors support for Actix Web.
|
||||
|
||||
<!-- prettier-ignore-start -->
|
||||
|
||||
[](https://crates.io/crates/actix-web-actors)
|
||||
[](https://docs.rs/actix-web-actors/4.2.0)
|
||||
[](https://docs.rs/actix-web-actors/4.3.0)
|
||||

|
||||

|
||||
<br />
|
||||
[](https://deps.rs/crate/actix-web-actors/4.2.0)
|
||||
[](https://deps.rs/crate/actix-web-actors/4.3.0)
|
||||
[](https://crates.io/crates/actix-web-actors)
|
||||
[](https://discord.gg/NWpN5mmg3x)
|
||||
|
||||
<!-- prettier-ignore-end -->
|
||||
|
||||
## Documentation & Resources
|
||||
|
||||
- [API Documentation](https://docs.rs/actix-web-actors)
|
||||
|
@ -57,7 +57,6 @@
|
||||
|
||||
#![deny(rust_2018_idioms, nonstandard_style)]
|
||||
#![warn(future_incompatible)]
|
||||
#![allow(clippy::uninlined_format_args)]
|
||||
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
|
||||
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||
|
@ -775,10 +775,10 @@ where
|
||||
break;
|
||||
}
|
||||
Poll::Pending => break,
|
||||
Poll::Ready(Some(Err(e))) => {
|
||||
Poll::Ready(Some(Err(err))) => {
|
||||
return Poll::Ready(Some(Err(ProtocolError::Io(io::Error::new(
|
||||
io::ErrorKind::Other,
|
||||
format!("{}", e),
|
||||
format!("{err}"),
|
||||
)))));
|
||||
}
|
||||
}
|
||||
|
@ -2,6 +2,12 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
## 4.2.2
|
||||
|
||||
- Fix regression when declaring `wrap` attribute using an expression.
|
||||
|
||||
## 4.2.1
|
||||
|
||||
- Update `syn` dependency to `2`.
|
||||
- Minimum supported Rust version (MSRV) is now 1.68 due to transitive `time` dependency.
|
||||
|
||||
|
@ -1,9 +1,9 @@
|
||||
[package]
|
||||
name = "actix-web-codegen"
|
||||
version = "4.2.0"
|
||||
version = "4.2.2"
|
||||
description = "Routing and runtime macros for Actix Web"
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-web.git"
|
||||
repository = "https://github.com/actix/actix-web"
|
||||
authors = [
|
||||
"Nikolay Kim <fafhrd91@gmail.com>",
|
||||
"Rob Ede <robjtede@icloud.com>",
|
||||
|
@ -1,16 +1,20 @@
|
||||
# actix-web-codegen
|
||||
# `actix-web-codegen`
|
||||
|
||||
> Routing and runtime macros for Actix Web.
|
||||
|
||||
<!-- prettier-ignore-start -->
|
||||
|
||||
[](https://crates.io/crates/actix-web-codegen)
|
||||
[](https://docs.rs/actix-web-codegen/4.2.0)
|
||||
[](https://docs.rs/actix-web-codegen/4.2.2)
|
||||

|
||||

|
||||
<br />
|
||||
[](https://deps.rs/crate/actix-web-codegen/4.2.0)
|
||||
[](https://deps.rs/crate/actix-web-codegen/4.2.2)
|
||||
[](https://crates.io/crates/actix-web-codegen)
|
||||
[](https://discord.gg/NWpN5mmg3x)
|
||||
|
||||
<!-- prettier-ignore-end -->
|
||||
|
||||
## Documentation & Resources
|
||||
|
||||
- [API Documentation](https://docs.rs/actix-web-codegen)
|
||||
|
@ -224,7 +224,7 @@ struct Args {
|
||||
path: syn::LitStr,
|
||||
resource_name: Option<syn::LitStr>,
|
||||
guards: Vec<Path>,
|
||||
wrappers: Vec<syn::Type>,
|
||||
wrappers: Vec<syn::Expr>,
|
||||
methods: HashSet<MethodTypeExt>,
|
||||
}
|
||||
|
||||
@ -251,7 +251,7 @@ impl Args {
|
||||
} else {
|
||||
return Err(syn::Error::new_spanned(
|
||||
nv.value,
|
||||
"Attribute name expects literal string!",
|
||||
"Attribute name expects literal string",
|
||||
));
|
||||
}
|
||||
} else if nv.path.is_ident("guard") {
|
||||
@ -264,7 +264,7 @@ impl Args {
|
||||
} else {
|
||||
return Err(syn::Error::new_spanned(
|
||||
nv.value,
|
||||
"Attribute guard expects literal string!",
|
||||
"Attribute guard expects literal string",
|
||||
));
|
||||
}
|
||||
} else if nv.path.is_ident("wrap") {
|
||||
@ -283,9 +283,9 @@ impl Args {
|
||||
} else if nv.path.is_ident("method") {
|
||||
if !is_route_macro {
|
||||
return Err(syn::Error::new_spanned(
|
||||
&nv,
|
||||
"HTTP method forbidden here. To handle multiple methods, use `route` instead",
|
||||
));
|
||||
&nv,
|
||||
"HTTP method forbidden here; to handle multiple methods, use `route` instead",
|
||||
));
|
||||
} else if let syn::Expr::Lit(syn::ExprLit {
|
||||
lit: syn::Lit::Str(lit),
|
||||
..
|
||||
@ -300,13 +300,13 @@ impl Args {
|
||||
} else {
|
||||
return Err(syn::Error::new_spanned(
|
||||
nv.value,
|
||||
"Attribute method expects literal string!",
|
||||
"Attribute method expects literal string",
|
||||
));
|
||||
}
|
||||
} else {
|
||||
return Err(syn::Error::new_spanned(
|
||||
nv.path,
|
||||
"Unknown attribute key is specified. Allowed: guard, method and wrap",
|
||||
"Unknown attribute key is specified; allowed: guard, method and wrap",
|
||||
));
|
||||
}
|
||||
}
|
||||
|
@ -212,6 +212,19 @@ async fn get_wrap(_: web::Path<String>) -> impl Responder {
|
||||
HttpResponse::Ok()
|
||||
}
|
||||
|
||||
/// Using expression, not just path to type, in wrap attribute.
|
||||
///
|
||||
/// Regression from <https://github.com/actix/actix-web/issues/3118>.
|
||||
#[route(
|
||||
"/catalog",
|
||||
method = "GET",
|
||||
method = "HEAD",
|
||||
wrap = "actix_web::middleware::Compress::default()"
|
||||
)]
|
||||
async fn get_catalog() -> impl Responder {
|
||||
HttpResponse::Ok().body("123123123")
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_params() {
|
||||
let srv = actix_test::start(|| {
|
||||
|
@ -38,7 +38,7 @@ error: Multiple paths specified! There should be only one.
|
||||
|
|
||||
= note: this error originates in the attribute macro `delete` (in Nightly builds, run with -Z macro-backtrace for more info)
|
||||
|
||||
error: HTTP method forbidden here. To handle multiple methods, use `route` instead
|
||||
error: HTTP method forbidden here; to handle multiple methods, use `route` instead
|
||||
--> $DIR/simple-fail.rs:25:19
|
||||
|
|
||||
25 | #[delete("/five", method="GET")]
|
||||
|
@ -2,6 +2,24 @@
|
||||
|
||||
## Unreleased
|
||||
|
||||
## 4.5.0
|
||||
|
||||
- Add `rustls-0_22` crate feature.
|
||||
- Add `HttpServer::{bind_rustls_0_22, listen_rustls_0_22}()` builder methods.
|
||||
|
||||
## 4.4.1
|
||||
|
||||
### Changed
|
||||
|
||||
- Updated `zstd` dependency to `0.13`.
|
||||
- Compression middleware now prefers brotli over zstd over gzip.
|
||||
|
||||
### Fixed
|
||||
|
||||
- Fix validation of `Json` extractor when `JsonConfig::validate_content_type()` is set to false.
|
||||
|
||||
## 4.4.0
|
||||
|
||||
### Added
|
||||
|
||||
- Add `HttpServer::{bind, listen}_auto_h2c()` methods behind new `http2` crate feature.
|
||||
|
@ -1,11 +1,11 @@
|
||||
[package]
|
||||
name = "actix-web"
|
||||
version = "4.3.1"
|
||||
version = "4.5.0"
|
||||
description = "Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust"
|
||||
authors = [
|
||||
"Nikolay Kim <fafhrd91@gmail.com>",
|
||||
"Rob Ede <robjtede@icloud.com>",
|
||||
]
|
||||
description = "Actix Web is a powerful, pragmatic, and extremely fast web framework for Rust"
|
||||
keywords = ["actix", "http", "web", "framework", "async"]
|
||||
categories = [
|
||||
"network-programming",
|
||||
@ -14,15 +14,26 @@ categories = [
|
||||
"web-programming::websocket"
|
||||
]
|
||||
homepage = "https://actix.rs"
|
||||
repository = "https://github.com/actix/actix-web.git"
|
||||
license = "MIT OR Apache-2.0"
|
||||
repository = "https://github.com/actix/actix-web"
|
||||
license.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[package.metadata.docs.rs]
|
||||
# features that docs.rs will build with
|
||||
features = ["macros", "openssl", "rustls-0_20", "rustls-0_21", "compress-brotli", "compress-gzip", "compress-zstd", "cookies", "secure-cookies"]
|
||||
rustdoc-args = ["--cfg", "docsrs"]
|
||||
features = [
|
||||
"macros",
|
||||
"openssl",
|
||||
"rustls-0_20",
|
||||
"rustls-0_21",
|
||||
"rustls-0_22",
|
||||
"compress-brotli",
|
||||
"compress-gzip",
|
||||
"compress-zstd",
|
||||
"cookies",
|
||||
"secure-cookies",
|
||||
]
|
||||
|
||||
|
||||
[lib]
|
||||
name = "actix_web"
|
||||
@ -58,6 +69,8 @@ rustls = ["rustls-0_20"]
|
||||
rustls-0_20 = ["http2", "actix-http/rustls-0_20", "actix-tls/accept", "actix-tls/rustls-0_20"]
|
||||
# TLS via Rustls v0.21
|
||||
rustls-0_21 = ["http2", "actix-http/rustls-0_21", "actix-tls/accept", "actix-tls/rustls-0_21"]
|
||||
# TLS via Rustls v0.22
|
||||
rustls-0_22 = ["http2", "actix-http/rustls-0_22", "actix-tls/accept", "actix-tls/rustls-0_22"]
|
||||
|
||||
# Internal (PRIVATE!) features used to aid testing and checking feature status.
|
||||
# Don't rely on these whatsoever. They may disappear at anytime.
|
||||
@ -73,9 +86,9 @@ actix-rt = { version = "2.6", default-features = false }
|
||||
actix-server = "2"
|
||||
actix-service = "2"
|
||||
actix-utils = "3"
|
||||
actix-tls = { version = "3.1", default-features = false, optional = true }
|
||||
actix-tls = { version = "3.3", default-features = false, optional = true }
|
||||
|
||||
actix-http = { version = "3.3", features = ["ws"] }
|
||||
actix-http = { version = "3.6", features = ["ws"] }
|
||||
actix-router = "0.5"
|
||||
actix-web-codegen = { version = "4.2", optional = true }
|
||||
|
||||
@ -122,7 +135,7 @@ static_assertions = "1"
|
||||
tls-openssl = { package = "openssl", version = "0.10.55" }
|
||||
tls-rustls = { package = "rustls", version = "0.21" }
|
||||
tokio = { version = "1.24.2", features = ["rt-multi-thread", "macros"] }
|
||||
zstd = "0.12"
|
||||
zstd = "0.13"
|
||||
|
||||
[[test]]
|
||||
name = "test_server"
|
||||
|
@ -372,13 +372,13 @@ You may need to review the [guidance on shared mutable state](https://docs.rs/ac
|
||||
HttpServer::new(|| {
|
||||
- App::new()
|
||||
- .data(MyState::default())
|
||||
- .service(hander)
|
||||
- .service(handler)
|
||||
|
||||
+ let my_state: Data<MyState> = Data::new(MyState::default());
|
||||
+
|
||||
+ App::new()
|
||||
+ .app_data(my_state)
|
||||
+ .service(hander)
|
||||
+ .service(handler)
|
||||
})
|
||||
```
|
||||
|
||||
|
@ -8,10 +8,10 @@
|
||||
<!-- prettier-ignore-start -->
|
||||
|
||||
[](https://crates.io/crates/actix-web)
|
||||
[](https://docs.rs/actix-web/4.3.1)
|
||||
[](https://docs.rs/actix-web/4.5.0)
|
||||

|
||||

|
||||
[](https://deps.rs/crate/actix-web/4.3.1)
|
||||
[](https://deps.rs/crate/actix-web/4.5.0)
|
||||
<br />
|
||||
[](https://github.com/actix/actix-web/actions/workflows/ci.yml)
|
||||
[](https://codecov.io/gh/actix/actix-web)
|
||||
|
@ -1,5 +1,3 @@
|
||||
#![allow(clippy::uninlined_format_args)]
|
||||
|
||||
use actix_web::{web, App, HttpResponse};
|
||||
use awc::Client;
|
||||
use criterion::{criterion_group, criterion_main, Criterion};
|
||||
|
@ -1,5 +1,3 @@
|
||||
#![allow(clippy::uninlined_format_args)]
|
||||
|
||||
use actix_web::{middleware, rt, web, App, HttpRequest, HttpServer};
|
||||
|
||||
async fn index(req: HttpRequest) -> &'static str {
|
||||
|
@ -1,5 +1,3 @@
|
||||
#![allow(clippy::uninlined_format_args)]
|
||||
|
||||
use actix_web::{get, web, HttpRequest};
|
||||
#[cfg(unix)]
|
||||
use actix_web::{middleware, App, Error, HttpResponse, HttpServer};
|
||||
|
@ -129,6 +129,8 @@ where
|
||||
///
|
||||
/// Data items are constructed during application initialization, before the server starts
|
||||
/// accepting requests.
|
||||
///
|
||||
/// The returned data value `D` is wrapped as [`Data<D>`].
|
||||
pub fn data_factory<F, Out, D, E>(mut self, data: F) -> Self
|
||||
where
|
||||
F: Fn() -> Out + 'static,
|
||||
@ -141,8 +143,8 @@ where
|
||||
let fut = data();
|
||||
async move {
|
||||
match fut.await {
|
||||
Err(e) => {
|
||||
log::error!("Can not construct data instance: {:?}", e);
|
||||
Err(err) => {
|
||||
log::error!("Can not construct data instance: {err:?}");
|
||||
Err(())
|
||||
}
|
||||
Ok(data) => {
|
||||
|
@ -32,8 +32,8 @@ pub(crate) type FnDataFactory =
|
||||
/// Since the Actix Web router layers application data, the returned object will reference the
|
||||
/// "closest" instance of the type. For example, if an `App` stores a `u32`, a nested `Scope`
|
||||
/// also stores a `u32`, and the delegated request handler falls within that `Scope`, then
|
||||
/// extracting a `web::<Data<u32>>` for that handler will return the `Scope`'s instance.
|
||||
/// However, using the same router set up and a request that does not get captured by the `Scope`,
|
||||
/// extracting a `web::Data<u32>` for that handler will return the `Scope`'s instance. However,
|
||||
/// using the same router set up and a request that does not get captured by the `Scope`,
|
||||
/// `web::<Data<u32>>` would return the `App`'s instance.
|
||||
///
|
||||
/// If route data is not set for a handler, using `Data<T>` extractor would cause a `500 Internal
|
||||
@ -69,7 +69,7 @@ pub(crate) type FnDataFactory =
|
||||
/// HttpResponse::Ok()
|
||||
/// }
|
||||
///
|
||||
/// /// Alteratively, use the `HttpRequest::app_data` method to access data in a handler.
|
||||
/// /// Alternatively, use the `HttpRequest::app_data` method to access data in a handler.
|
||||
/// async fn index_alt(req: HttpRequest) -> impl Responder {
|
||||
/// let data = req.app_data::<Data<Mutex<MyData>>>().unwrap();
|
||||
/// let mut my_data = data.lock().unwrap();
|
||||
|
@ -175,8 +175,8 @@ where
|
||||
let res = ready!(this.fut.poll(cx));
|
||||
match res {
|
||||
Ok(t) => Poll::Ready(Ok(Some(t))),
|
||||
Err(e) => {
|
||||
log::debug!("Error for Option<T> extractor: {}", e.into());
|
||||
Err(err) => {
|
||||
log::debug!("Error for Option<T> extractor: {}", err.into());
|
||||
Poll::Ready(Ok(None))
|
||||
}
|
||||
}
|
||||
@ -217,8 +217,8 @@ where
|
||||
/// /// extract `Thing` from request
|
||||
/// async fn index(supplied_thing: Result<Thing>) -> String {
|
||||
/// match supplied_thing {
|
||||
/// Ok(thing) => format!("Got thing: {:?}", thing),
|
||||
/// Err(e) => format!("Error extracting thing: {}", e)
|
||||
/// Ok(thing) => format!("Got thing: {thing:?}"),
|
||||
/// Err(err) => format!("Error extracting thing: {err}"),
|
||||
/// }
|
||||
/// }
|
||||
///
|
||||
@ -355,7 +355,7 @@ mod tuple_from_req {
|
||||
Poll::Ready(Ok(output)) => {
|
||||
let _ = this.$T.as_mut().project_replace(ExtractFuture::Done { output });
|
||||
},
|
||||
Poll::Ready(Err(e)) => return Poll::Ready(Err(e.into())),
|
||||
Poll::Ready(Err(err)) => return Poll::Ready(Err(err.into())),
|
||||
Poll::Pending => ready = false,
|
||||
},
|
||||
ExtractProj::Done { .. } => {},
|
||||
|
@ -20,7 +20,7 @@ use crate::http::header::Accept;
|
||||
pub struct Acceptable {
|
||||
mime: mime::Mime,
|
||||
|
||||
/// Wether to match `*/*` mime type.
|
||||
/// Whether to match `*/*` mime type.
|
||||
///
|
||||
/// Defaults to false because it's not very useful otherwise.
|
||||
match_star_star: bool,
|
||||
|
@ -2,7 +2,7 @@ use actix_http::{header, uri::Uri, RequestHead};
|
||||
|
||||
use super::{Guard, GuardContext};
|
||||
|
||||
/// Creates a guard that matches requests targetting a specific host.
|
||||
/// Creates a guard that matches requests targeting a specific host.
|
||||
///
|
||||
/// # Matching Host
|
||||
/// This guard will:
|
||||
|
@ -10,10 +10,12 @@ use crate::{
|
||||
/// The interface for request handlers.
|
||||
///
|
||||
/// # What Is A Request Handler
|
||||
///
|
||||
/// In short, a handler is just an async function that receives request-based arguments, in any
|
||||
/// order, and returns something that can be converted to a response.
|
||||
///
|
||||
/// In particular, a request handler has three requirements:
|
||||
///
|
||||
/// 1. It is an async function (or a function/closure that returns an appropriate future);
|
||||
/// 1. The function parameters (up to 12) implement [`FromRequest`];
|
||||
/// 1. The async function (or future) resolves to a type that can be converted into an
|
||||
@ -21,11 +23,15 @@ use crate::{
|
||||
///
|
||||
///
|
||||
/// # Compiler Errors
|
||||
///
|
||||
/// If you get the error `the trait Handler<_> is not implemented`, then your handler does not
|
||||
/// fulfill the _first_ of the above requirements. Missing other requirements manifest as errors on
|
||||
/// implementing [`FromRequest`] and [`Responder`], respectively.
|
||||
/// fulfill the _first_ of the above requirements. (It could also mean that you're attempting to use
|
||||
/// a macro-routed handler in a manual routing context like `web::get().to(handler)`, which is not
|
||||
/// supported). Breaking the other requirements manifests as errors on implementing [`FromRequest`]
|
||||
/// and [`Responder`], respectively.
|
||||
///
|
||||
/// # How Do Handlers Receive Variable Numbers Of Arguments
|
||||
///
|
||||
/// Rest assured there is no macro magic here; it's just traits.
|
||||
///
|
||||
/// The first thing to note is that [`FromRequest`] is implemented for tuples (up to 12 in length).
|
||||
@ -40,6 +46,7 @@ use crate::{
|
||||
/// destructures the tuple into its component types and calls your handler function with them.
|
||||
///
|
||||
/// In pseudo-code the process looks something like this:
|
||||
///
|
||||
/// ```ignore
|
||||
/// async fn my_handler(body: String, state: web::Data<MyState>) -> impl Responder {
|
||||
/// ...
|
||||
|
@ -149,7 +149,7 @@ impl AcceptEncoding {
|
||||
|
||||
/// Extracts the most preferable encoding, accounting for [q-factor weighting].
|
||||
///
|
||||
/// If no q-factors are provided, the first encoding is chosen. Note that items without
|
||||
/// If no q-factors are provided, we prefer brotli > zstd > gzip. Note that items without
|
||||
/// q-factors are given the maximum preference value.
|
||||
///
|
||||
/// As per the spec, returns [`Preference::Any`] if acceptable list is empty. Though, if this is
|
||||
@ -167,6 +167,7 @@ impl AcceptEncoding {
|
||||
|
||||
let mut max_item = None;
|
||||
let mut max_pref = Quality::ZERO;
|
||||
let mut max_rank = 0;
|
||||
|
||||
// uses manual max lookup loop since we want the first occurrence in the case of same
|
||||
// preference but `Iterator::max_by_key` would give us the last occurrence
|
||||
@ -174,9 +175,13 @@ impl AcceptEncoding {
|
||||
for pref in &self.0 {
|
||||
// only change if strictly greater
|
||||
// equal items, even while unsorted, still have higher preference if they appear first
|
||||
if pref.quality > max_pref {
|
||||
|
||||
let rank = encoding_rank(pref);
|
||||
|
||||
if (pref.quality, rank) > (max_pref, max_rank) {
|
||||
max_pref = pref.quality;
|
||||
max_item = Some(pref.item.clone());
|
||||
max_rank = rank;
|
||||
}
|
||||
}
|
||||
|
||||
@ -203,6 +208,8 @@ impl AcceptEncoding {
|
||||
/// Returns a sorted list of encodings from highest to lowest precedence, accounting
|
||||
/// for [q-factor weighting].
|
||||
///
|
||||
/// If no q-factors are provided, we prefer brotli > zstd > gzip.
|
||||
///
|
||||
/// [q-factor weighting]: https://datatracker.ietf.org/doc/html/rfc7231#section-5.3.2
|
||||
pub fn ranked(&self) -> Vec<Preference<Encoding>> {
|
||||
self.ranked_items().map(|q| q.item).collect()
|
||||
@ -210,21 +217,44 @@ impl AcceptEncoding {
|
||||
|
||||
fn ranked_items(&self) -> impl Iterator<Item = QualityItem<Preference<Encoding>>> {
|
||||
if self.0.is_empty() {
|
||||
return vec![].into_iter();
|
||||
return Vec::new().into_iter();
|
||||
}
|
||||
|
||||
let mut types = self.0.clone();
|
||||
|
||||
// use stable sort so items with equal q-factor retain listed order
|
||||
types.sort_by(|a, b| {
|
||||
// sort by q-factor descending
|
||||
b.quality.cmp(&a.quality)
|
||||
// sort by q-factor descending then server ranking descending
|
||||
|
||||
b.quality
|
||||
.cmp(&a.quality)
|
||||
.then(encoding_rank(b).cmp(&encoding_rank(a)))
|
||||
});
|
||||
|
||||
types.into_iter()
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns server-defined encoding ranking.
|
||||
fn encoding_rank(qv: &QualityItem<Preference<Encoding>>) -> u8 {
|
||||
// ensure that q=0 items are never sorted above identity encoding
|
||||
// invariant: sorting methods calling this fn use first-on-equal approach
|
||||
if qv.quality == Quality::ZERO {
|
||||
return 0;
|
||||
}
|
||||
|
||||
match qv.item {
|
||||
Preference::Specific(Encoding::Known(ContentEncoding::Brotli)) => 5,
|
||||
Preference::Specific(Encoding::Known(ContentEncoding::Zstd)) => 4,
|
||||
Preference::Specific(Encoding::Known(ContentEncoding::Gzip)) => 3,
|
||||
Preference::Specific(Encoding::Known(ContentEncoding::Deflate)) => 2,
|
||||
Preference::Any => 0,
|
||||
Preference::Specific(Encoding::Known(ContentEncoding::Identity)) => 0,
|
||||
Preference::Specific(Encoding::Known(_)) => 1,
|
||||
Preference::Specific(Encoding::Unknown(_)) => 1,
|
||||
}
|
||||
}
|
||||
|
||||
/// Returns true if "identity" is an acceptable encoding.
|
||||
///
|
||||
/// Internal algorithm relies on item list being in descending order of quality.
|
||||
@ -377,11 +407,11 @@ mod tests {
|
||||
);
|
||||
assert_eq!(
|
||||
test.negotiate([Encoding::gzip(), Encoding::brotli(), Encoding::identity()].iter()),
|
||||
Some(Encoding::gzip())
|
||||
Some(Encoding::brotli())
|
||||
);
|
||||
assert_eq!(
|
||||
test.negotiate([Encoding::brotli(), Encoding::gzip(), Encoding::identity()].iter()),
|
||||
Some(Encoding::gzip())
|
||||
Some(Encoding::brotli())
|
||||
);
|
||||
}
|
||||
|
||||
@ -398,6 +428,9 @@ mod tests {
|
||||
|
||||
let test = accept_encoding!("br", "gzip", "*");
|
||||
assert_eq!(test.ranked(), vec![enc("br"), enc("gzip"), enc("*")]);
|
||||
|
||||
let test = accept_encoding!("gzip", "br", "*");
|
||||
assert_eq!(test.ranked(), vec![enc("br"), enc("gzip"), enc("*")]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@ -420,5 +453,8 @@ mod tests {
|
||||
|
||||
let test = accept_encoding!("br", "gzip", "*");
|
||||
assert_eq!(test.preference().unwrap(), enc("br"));
|
||||
|
||||
let test = accept_encoding!("gzip", "br", "*");
|
||||
assert_eq!(test.preference().unwrap(), enc("br"));
|
||||
}
|
||||
}
|
||||
|
@ -69,7 +69,6 @@
|
||||
|
||||
#![deny(rust_2018_idioms, nonstandard_style)]
|
||||
#![warn(future_incompatible)]
|
||||
#![allow(clippy::uninlined_format_args)]
|
||||
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
|
||||
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
|
||||
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||
|
@ -373,7 +373,7 @@ mod tests {
|
||||
.default_service(web::to(move || {
|
||||
HttpResponse::Ok()
|
||||
.insert_header((header::VARY, "x-test"))
|
||||
.finish()
|
||||
.body(TEXT_DATA)
|
||||
}))
|
||||
})
|
||||
.await;
|
||||
@ -429,4 +429,47 @@ mod tests {
|
||||
assert_successful_identity_res_with_content_type(&res, "image/jpeg");
|
||||
assert_eq!(test::read_body(res).await, TEXT_DATA.as_bytes());
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn prevents_compression_empty() {
|
||||
let app = test::init_service({
|
||||
App::new()
|
||||
.wrap(Compress::default())
|
||||
.default_service(web::to(move || HttpResponse::Ok().finish()))
|
||||
})
|
||||
.await;
|
||||
|
||||
let req = test::TestRequest::default()
|
||||
.insert_header((header::ACCEPT_ENCODING, "gzip"))
|
||||
.to_request();
|
||||
let res = test::call_service(&app, req).await;
|
||||
assert_eq!(res.status(), StatusCode::OK);
|
||||
assert!(!res.headers().contains_key(header::CONTENT_ENCODING));
|
||||
assert!(test::read_body(res).await.is_empty());
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(feature = "compress-brotli")]
|
||||
#[cfg(test)]
|
||||
mod tests_brotli {
|
||||
use super::*;
|
||||
use crate::{test, web, App};
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn prevents_compression_empty() {
|
||||
let app = test::init_service({
|
||||
App::new()
|
||||
.wrap(Compress::default())
|
||||
.default_service(web::to(move || HttpResponse::Ok().finish()))
|
||||
})
|
||||
.await;
|
||||
|
||||
let req = test::TestRequest::default()
|
||||
.insert_header((header::ACCEPT_ENCODING, "br"))
|
||||
.to_request();
|
||||
let res = test::call_service(&app, req).await;
|
||||
assert_eq!(res.status(), StatusCode::OK);
|
||||
assert!(!res.headers().contains_key(header::CONTENT_ENCODING));
|
||||
assert!(test::read_body(res).await.is_empty());
|
||||
}
|
||||
}
|
||||
|
@ -356,7 +356,7 @@ where
|
||||
|
||||
let res = match ready!(this.fut.poll(cx)) {
|
||||
Ok(res) => res,
|
||||
Err(e) => return Poll::Ready(Err(e)),
|
||||
Err(err) => return Poll::Ready(Err(err)),
|
||||
};
|
||||
|
||||
if let Some(error) = res.response().error() {
|
||||
|
@ -72,7 +72,7 @@
|
||||
//! processes the request as well and passes it to `MiddlewareA`, which then passes it to the
|
||||
//! [`Service`]. In the [`Service`], the extractors will run first. They don't pass the request on,
|
||||
//! but only view it (see [`FromRequest`]). After the [`Service`] responds to the request, the
|
||||
//! response it passed back through `MiddlewareA`, `MiddlewareB`, and `MiddlewareC`.
|
||||
//! response is passed back through `MiddlewareA`, `MiddlewareB`, and `MiddlewareC`.
|
||||
//!
|
||||
//! As you register middleware using [`wrap`][crate::App::wrap] and [`wrap_fn`][crate::App::wrap_fn]
|
||||
//! in the [`App`] builder, imagine wrapping layers around an inner [`App`]. The first middleware
|
||||
|
@ -171,7 +171,7 @@ impl Responder for Redirect {
|
||||
} else {
|
||||
log::error!(
|
||||
"redirect target location can not be converted to header value: {:?}",
|
||||
self.to
|
||||
self.to,
|
||||
);
|
||||
}
|
||||
|
||||
|
@ -64,7 +64,7 @@ impl HttpResponseBuilder {
|
||||
Ok((key, value)) => {
|
||||
parts.headers.insert(key, value);
|
||||
}
|
||||
Err(e) => self.error = Some(e.into()),
|
||||
Err(err) => self.error = Some(err.into()),
|
||||
};
|
||||
}
|
||||
|
||||
@ -86,7 +86,7 @@ impl HttpResponseBuilder {
|
||||
if let Some(parts) = self.inner() {
|
||||
match header.try_into_pair() {
|
||||
Ok((key, value)) => parts.headers.append(key, value),
|
||||
Err(e) => self.error = Some(e.into()),
|
||||
Err(err) => self.error = Some(err.into()),
|
||||
};
|
||||
}
|
||||
|
||||
@ -210,7 +210,7 @@ impl HttpResponseBuilder {
|
||||
Ok(value) => {
|
||||
parts.headers.insert(header::CONTENT_TYPE, value);
|
||||
}
|
||||
Err(e) => self.error = Some(e.into()),
|
||||
Err(err) => self.error = Some(err.into()),
|
||||
};
|
||||
}
|
||||
self
|
||||
|
@ -5,8 +5,6 @@ mod responder;
|
||||
#[allow(clippy::module_inception)]
|
||||
mod response;
|
||||
|
||||
#[cfg(feature = "cookies")]
|
||||
pub use self::response::CookieIter;
|
||||
pub use self::{
|
||||
builder::HttpResponseBuilder, customize_responder::CustomizeResponder, responder::Responder,
|
||||
response::HttpResponse,
|
||||
|
@ -5,6 +5,7 @@
|
||||
//! architecture in [`actix-rt`]'s docs.
|
||||
//!
|
||||
//! # Running Actix Web Without Macros
|
||||
//!
|
||||
//! ```no_run
|
||||
//! use actix_web::{middleware, rt, web, App, HttpRequest, HttpServer};
|
||||
//!
|
||||
@ -25,6 +26,7 @@
|
||||
//! ```
|
||||
//!
|
||||
//! # Running Actix Web Using `#[tokio::main]`
|
||||
//!
|
||||
//! If you need to run something that uses Tokio's work stealing functionality alongside Actix Web,
|
||||
//! you can run Actix Web under `#[tokio::main]`. The [`Server`](crate::dev::Server) object returned
|
||||
//! from [`HttpServer::run`](crate::HttpServer::run) can also be [`spawn`]ed, if preferred.
|
||||
@ -32,6 +34,10 @@
|
||||
//! Note that `actix` actor support (and therefore WebSocket support through `actix-web-actors`)
|
||||
//! still require `#[actix_web::main]` since they require a [`System`] to be set up.
|
||||
//!
|
||||
//! Also note that calls to this module's [`spawn()`] re-export require an `#[actix_web::main]`
|
||||
//! runtime (or a manually configured `LocalSet`) since it makes calls into to the current thread's
|
||||
//! `LocalSet`, which `#[tokio::main]` does not set up.
|
||||
//!
|
||||
//! ```no_run
|
||||
//! use actix_web::{get, middleware, rt, web, App, HttpRequest, HttpServer};
|
||||
//!
|
||||
|
@ -99,6 +99,12 @@ where
|
||||
B: MessageBody + 'static,
|
||||
{
|
||||
/// Create new HTTP server with application factory
|
||||
///
|
||||
/// # Worker Count
|
||||
///
|
||||
/// The `factory` will be instantiated multiple times in most configurations. See
|
||||
/// [`bind()`](Self::bind()) docs for more on how worker count and bind address resolution
|
||||
/// causes multiple server factory instantiations.
|
||||
pub fn new(factory: F) -> Self {
|
||||
HttpServer {
|
||||
factory,
|
||||
@ -119,7 +125,18 @@ where
|
||||
|
||||
/// Sets number of workers to start (per bind address).
|
||||
///
|
||||
/// By default, the number of available physical CPUs is used as the worker count.
|
||||
/// The default worker count is the determined by [`std::thread::available_parallelism()`]. See
|
||||
/// its documentation to determine what behavior you should expect when server is run.
|
||||
///
|
||||
/// Note that the server factory passed to [`new`](Self::new()) will be instantiated **at least
|
||||
/// once per worker**. See [`bind()`](Self::bind()) docs for more on how worker count and bind
|
||||
/// address resolution causes multiple server factory instantiations.
|
||||
///
|
||||
/// `num` must be greater than 0.
|
||||
///
|
||||
/// # Panics
|
||||
///
|
||||
/// Panics if `num` is 0.
|
||||
pub fn workers(mut self, num: usize) -> Self {
|
||||
self.builder = self.builder.workers(num);
|
||||
self
|
||||
@ -319,23 +336,41 @@ where
|
||||
/// Resolves socket address(es) and binds server to created listener(s).
|
||||
///
|
||||
/// # Hostname Resolution
|
||||
/// When `addr` includes a hostname, it is possible for this method to bind to both the IPv4 and
|
||||
/// IPv6 addresses that result from a DNS lookup. You can test this by passing `localhost:8080`
|
||||
/// and noting that the server binds to `127.0.0.1:8080` _and_ `[::1]:8080`. To bind additional
|
||||
/// addresses, call this method multiple times.
|
||||
///
|
||||
/// When `addrs` includes a hostname, it is possible for this method to bind to both the IPv4
|
||||
/// and IPv6 addresses that result from a DNS lookup. You can test this by passing
|
||||
/// `localhost:8080` and noting that the server binds to `127.0.0.1:8080` _and_ `[::1]:8080`. To
|
||||
/// bind additional addresses, call this method multiple times.
|
||||
///
|
||||
/// Note that, if a DNS lookup is required, resolving hostnames is a blocking operation.
|
||||
///
|
||||
/// # Worker Count
|
||||
///
|
||||
/// The `factory` will be instantiated multiple times in most scenarios. The number of
|
||||
/// instantiations is number of [`workers`](Self::workers()) × number of sockets resolved by
|
||||
/// `addrs`.
|
||||
///
|
||||
/// For example, if you've manually set [`workers`](Self::workers()) to 2, and use `127.0.0.1`
|
||||
/// as the bind `addrs`, then `factory` will be instantiated twice. However, using `localhost`
|
||||
/// as the bind `addrs` can often resolve to both `127.0.0.1` (IPv4) _and_ `::1` (IPv6), causing
|
||||
/// the `factory` to be instantiated 4 times (2 workers × 2 bind addresses).
|
||||
///
|
||||
/// Using a bind address of `0.0.0.0`, which signals to use all interfaces, may also multiple
|
||||
/// the number of instantiations in a similar way.
|
||||
///
|
||||
/// # Typical Usage
|
||||
///
|
||||
/// In general, use `127.0.0.1:<port>` when testing locally and `0.0.0.0:<port>` when deploying
|
||||
/// (with or without a reverse proxy or load balancer) so that the server is accessible.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns an `io::Error` if:
|
||||
/// - `addrs` cannot be resolved into one or more socket addresses;
|
||||
/// - all the resolved socket addresses are already bound.
|
||||
///
|
||||
/// # Example
|
||||
///
|
||||
/// ```
|
||||
/// # use actix_web::{App, HttpServer};
|
||||
/// # fn inner() -> std::io::Result<()> {
|
||||
@ -356,6 +391,8 @@ where
|
||||
|
||||
/// Resolves socket address(es) and binds server to created listener(s) for plaintext HTTP/1.x
|
||||
/// or HTTP/2 connections.
|
||||
///
|
||||
/// See [`bind()`](Self::bind()) for more details on `addrs` argument.
|
||||
#[cfg(feature = "http2")]
|
||||
pub fn bind_auto_h2c<A: net::ToSocketAddrs>(mut self, addrs: A) -> io::Result<Self> {
|
||||
let sockets = bind_addrs(addrs, self.backlog)?;
|
||||
@ -370,7 +407,7 @@ where
|
||||
/// Resolves socket address(es) and binds server to created listener(s) for TLS connections
|
||||
/// using Rustls v0.20.
|
||||
///
|
||||
/// See [`bind()`](Self::bind) for more details on `addrs` argument.
|
||||
/// See [`bind()`](Self::bind()) for more details on `addrs` argument.
|
||||
///
|
||||
/// ALPN protocols "h2" and "http/1.1" are added to any configured ones.
|
||||
#[cfg(feature = "rustls-0_20")]
|
||||
@ -389,7 +426,7 @@ where
|
||||
/// Resolves socket address(es) and binds server to created listener(s) for TLS connections
|
||||
/// using Rustls v0.21.
|
||||
///
|
||||
/// See [`bind()`](Self::bind) for more details on `addrs` argument.
|
||||
/// See [`bind()`](Self::bind()) for more details on `addrs` argument.
|
||||
///
|
||||
/// ALPN protocols "h2" and "http/1.1" are added to any configured ones.
|
||||
#[cfg(feature = "rustls-0_21")]
|
||||
@ -405,10 +442,29 @@ where
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Resolves socket address(es) and binds server to created listener(s) for TLS connections
|
||||
/// using Rustls v0.22.
|
||||
///
|
||||
/// See [`bind()`](Self::bind()) for more details on `addrs` argument.
|
||||
///
|
||||
/// ALPN protocols "h2" and "http/1.1" are added to any configured ones.
|
||||
#[cfg(feature = "rustls-0_22")]
|
||||
pub fn bind_rustls_0_22<A: net::ToSocketAddrs>(
|
||||
mut self,
|
||||
addrs: A,
|
||||
config: actix_tls::accept::rustls_0_22::reexports::ServerConfig,
|
||||
) -> io::Result<Self> {
|
||||
let sockets = bind_addrs(addrs, self.backlog)?;
|
||||
for lst in sockets {
|
||||
self = self.listen_rustls_0_22_inner(lst, config.clone())?;
|
||||
}
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Resolves socket address(es) and binds server to created listener(s) for TLS connections
|
||||
/// using OpenSSL.
|
||||
///
|
||||
/// See [`bind()`](Self::bind) for more details on `addrs` argument.
|
||||
/// See [`bind()`](Self::bind()) for more details on `addrs` argument.
|
||||
///
|
||||
/// ALPN protocols "h2" and "http/1.1" are added to any configured ones.
|
||||
#[cfg(feature = "openssl")]
|
||||
@ -648,6 +704,72 @@ where
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Binds to existing listener for accepting incoming TLS connection requests using Rustls
|
||||
/// v0.22.
|
||||
///
|
||||
/// See [`listen()`](Self::listen) for more details on the `lst` argument.
|
||||
///
|
||||
/// ALPN protocols "h2" and "http/1.1" are added to any configured ones.
|
||||
#[cfg(feature = "rustls-0_22")]
|
||||
pub fn listen_rustls_0_22(
|
||||
self,
|
||||
lst: net::TcpListener,
|
||||
config: actix_tls::accept::rustls_0_22::reexports::ServerConfig,
|
||||
) -> io::Result<Self> {
|
||||
self.listen_rustls_0_22_inner(lst, config)
|
||||
}
|
||||
|
||||
#[cfg(feature = "rustls-0_22")]
|
||||
fn listen_rustls_0_22_inner(
|
||||
mut self,
|
||||
lst: net::TcpListener,
|
||||
config: actix_tls::accept::rustls_0_22::reexports::ServerConfig,
|
||||
) -> io::Result<Self> {
|
||||
let factory = self.factory.clone();
|
||||
let cfg = self.config.clone();
|
||||
let addr = lst.local_addr().unwrap();
|
||||
self.sockets.push(Socket {
|
||||
addr,
|
||||
scheme: "https",
|
||||
});
|
||||
|
||||
let on_connect_fn = self.on_connect_fn.clone();
|
||||
|
||||
self.builder =
|
||||
self.builder
|
||||
.listen(format!("actix-web-service-{}", addr), lst, move || {
|
||||
let c = cfg.lock().unwrap();
|
||||
let host = c.host.clone().unwrap_or_else(|| format!("{}", addr));
|
||||
|
||||
let svc = HttpService::build()
|
||||
.keep_alive(c.keep_alive)
|
||||
.client_request_timeout(c.client_request_timeout)
|
||||
.client_disconnect_timeout(c.client_disconnect_timeout);
|
||||
|
||||
let svc = if let Some(handler) = on_connect_fn.clone() {
|
||||
svc.on_connect_ext(move |io: &_, ext: _| (handler)(io as &dyn Any, ext))
|
||||
} else {
|
||||
svc
|
||||
};
|
||||
|
||||
let fac = factory()
|
||||
.into_factory()
|
||||
.map_err(|err| err.into().error_response());
|
||||
|
||||
let acceptor_config = match c.tls_handshake_timeout {
|
||||
Some(dur) => TlsAcceptorConfig::default().handshake_timeout(dur),
|
||||
None => TlsAcceptorConfig::default(),
|
||||
};
|
||||
|
||||
svc.finish(map_config(fac, move |_| {
|
||||
AppConfig::new(true, host.clone(), addr)
|
||||
}))
|
||||
.rustls_0_22_with_config(config.clone(), acceptor_config)
|
||||
})?;
|
||||
|
||||
Ok(self)
|
||||
}
|
||||
|
||||
/// Binds to existing listener for accepting incoming TLS connection requests using OpenSSL.
|
||||
///
|
||||
/// See [`listen()`](Self::listen) for more details on the `lst` argument.
|
||||
@ -853,7 +975,7 @@ fn bind_addrs(addrs: impl net::ToSocketAddrs, backlog: u32) -> io::Result<Vec<ne
|
||||
success = true;
|
||||
sockets.push(lst);
|
||||
}
|
||||
Err(e) => err = Some(e),
|
||||
Err(error) => err = Some(error),
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -221,12 +221,9 @@ impl ServiceRequest {
|
||||
|
||||
/// Returns peer's socket address.
|
||||
///
|
||||
/// Peer address is the directly connected peer's socket address. If a proxy is used in front of
|
||||
/// the Actix Web server, then it would be address of this proxy.
|
||||
/// See [`HttpRequest::peer_addr`] for more details.
|
||||
///
|
||||
/// To get client connection information `ConnectionInfo` should be used.
|
||||
///
|
||||
/// Will only return None when called in unit tests.
|
||||
/// [`HttpRequest::peer_addr`]: crate::HttpRequest::peer_addr
|
||||
#[inline]
|
||||
pub fn peer_addr(&self) -> Option<net::SocketAddr> {
|
||||
self.head().peer_addr
|
||||
|
@ -86,76 +86,77 @@ impl Default for TestRequest {
|
||||
|
||||
#[allow(clippy::wrong_self_convention)]
|
||||
impl TestRequest {
|
||||
/// Create TestRequest and set request uri
|
||||
pub fn with_uri(path: &str) -> TestRequest {
|
||||
TestRequest::default().uri(path)
|
||||
/// Constructs test request and sets request URI.
|
||||
pub fn with_uri(uri: &str) -> TestRequest {
|
||||
TestRequest::default().uri(uri)
|
||||
}
|
||||
|
||||
/// Create TestRequest and set method to `Method::GET`
|
||||
/// Constructs test request with GET method.
|
||||
pub fn get() -> TestRequest {
|
||||
TestRequest::default().method(Method::GET)
|
||||
}
|
||||
|
||||
/// Create TestRequest and set method to `Method::POST`
|
||||
/// Constructs test request with POST method.
|
||||
pub fn post() -> TestRequest {
|
||||
TestRequest::default().method(Method::POST)
|
||||
}
|
||||
|
||||
/// Create TestRequest and set method to `Method::PUT`
|
||||
/// Constructs test request with PUT method.
|
||||
pub fn put() -> TestRequest {
|
||||
TestRequest::default().method(Method::PUT)
|
||||
}
|
||||
|
||||
/// Create TestRequest and set method to `Method::PATCH`
|
||||
/// Constructs test request with PATCH method.
|
||||
pub fn patch() -> TestRequest {
|
||||
TestRequest::default().method(Method::PATCH)
|
||||
}
|
||||
|
||||
/// Create TestRequest and set method to `Method::DELETE`
|
||||
/// Constructs test request with DELETE method.
|
||||
pub fn delete() -> TestRequest {
|
||||
TestRequest::default().method(Method::DELETE)
|
||||
}
|
||||
|
||||
/// Set HTTP version of this request
|
||||
/// Sets HTTP version of this request.
|
||||
pub fn version(mut self, ver: Version) -> Self {
|
||||
self.req.version(ver);
|
||||
self
|
||||
}
|
||||
|
||||
/// Set HTTP method of this request
|
||||
/// Sets method of this request.
|
||||
pub fn method(mut self, meth: Method) -> Self {
|
||||
self.req.method(meth);
|
||||
self
|
||||
}
|
||||
|
||||
/// Set HTTP URI of this request
|
||||
/// Sets URI of this request.
|
||||
pub fn uri(mut self, path: &str) -> Self {
|
||||
self.req.uri(path);
|
||||
self
|
||||
}
|
||||
|
||||
/// Insert a header, replacing any that were set with an equivalent field name.
|
||||
/// Inserts a header, replacing any that were set with an equivalent field name.
|
||||
pub fn insert_header(mut self, header: impl TryIntoHeaderPair) -> Self {
|
||||
self.req.insert_header(header);
|
||||
self
|
||||
}
|
||||
|
||||
/// Append a header, keeping any that were set with an equivalent field name.
|
||||
/// Appends a header, keeping any that were set with an equivalent field name.
|
||||
pub fn append_header(mut self, header: impl TryIntoHeaderPair) -> Self {
|
||||
self.req.append_header(header);
|
||||
self
|
||||
}
|
||||
|
||||
/// Set cookie for this request.
|
||||
/// Sets cookie for this request.
|
||||
#[cfg(feature = "cookies")]
|
||||
pub fn cookie(mut self, cookie: Cookie<'_>) -> Self {
|
||||
self.cookies.add(cookie.into_owned());
|
||||
self
|
||||
}
|
||||
|
||||
/// Set request path pattern parameter.
|
||||
/// Sets request path pattern parameter.
|
||||
///
|
||||
/// # Examples
|
||||
///
|
||||
/// ```
|
||||
/// use actix_web::test::TestRequest;
|
||||
///
|
||||
@ -171,19 +172,19 @@ impl TestRequest {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set peer addr.
|
||||
/// Sets peer address.
|
||||
pub fn peer_addr(mut self, addr: SocketAddr) -> Self {
|
||||
self.peer_addr = Some(addr);
|
||||
self
|
||||
}
|
||||
|
||||
/// Set request payload.
|
||||
/// Sets request payload.
|
||||
pub fn set_payload(mut self, data: impl Into<Bytes>) -> Self {
|
||||
self.req.set_payload(data);
|
||||
self
|
||||
}
|
||||
|
||||
/// Serialize `data` to a URL encoded form and set it as the request payload.
|
||||
/// Serializes `data` to a URL encoded form and set it as the request payload.
|
||||
///
|
||||
/// The `Content-Type` header is set to `application/x-www-form-urlencoded`.
|
||||
pub fn set_form(mut self, data: impl Serialize) -> Self {
|
||||
@ -194,7 +195,7 @@ impl TestRequest {
|
||||
self
|
||||
}
|
||||
|
||||
/// Serialize `data` to JSON and set it as the request payload.
|
||||
/// Serializes `data` to JSON and set it as the request payload.
|
||||
///
|
||||
/// The `Content-Type` header is set to `application/json`.
|
||||
pub fn set_json(mut self, data: impl Serialize) -> Self {
|
||||
@ -204,27 +205,33 @@ impl TestRequest {
|
||||
self
|
||||
}
|
||||
|
||||
/// Set application data. This is equivalent of `App::data()` method
|
||||
/// for testing purpose.
|
||||
pub fn data<T: 'static>(mut self, data: T) -> Self {
|
||||
self.app_data.insert(Data::new(data));
|
||||
self
|
||||
}
|
||||
|
||||
/// Set application data. This is equivalent of `App::app_data()` method
|
||||
/// for testing purpose.
|
||||
/// Inserts application data.
|
||||
///
|
||||
/// This is equivalent of `App::app_data()` method for testing purpose.
|
||||
pub fn app_data<T: 'static>(mut self, data: T) -> Self {
|
||||
self.app_data.insert(data);
|
||||
self
|
||||
}
|
||||
|
||||
/// Inserts application data.
|
||||
///
|
||||
/// This is equivalent of `App::data()` method for testing purpose.
|
||||
#[doc(hidden)]
|
||||
pub fn data<T: 'static>(mut self, data: T) -> Self {
|
||||
self.app_data.insert(Data::new(data));
|
||||
self
|
||||
}
|
||||
|
||||
/// Sets resource map.
|
||||
#[cfg(test)]
|
||||
/// Set request config
|
||||
pub(crate) fn rmap(mut self, rmap: ResourceMap) -> Self {
|
||||
self.rmap = rmap;
|
||||
self
|
||||
}
|
||||
|
||||
/// Finalizes test request.
|
||||
///
|
||||
/// This request builder will be useless after calling `finish()`.
|
||||
fn finish(&mut self) -> Request {
|
||||
// mut used when cookie feature is enabled
|
||||
#[allow(unused_mut)]
|
||||
@ -251,14 +258,14 @@ impl TestRequest {
|
||||
req
|
||||
}
|
||||
|
||||
/// Complete request creation and generate `Request` instance
|
||||
/// Finalizes request creation and returns `Request` instance.
|
||||
pub fn to_request(mut self) -> Request {
|
||||
let mut req = self.finish();
|
||||
req.head_mut().peer_addr = self.peer_addr;
|
||||
req
|
||||
}
|
||||
|
||||
/// Complete request creation and generate `ServiceRequest` instance
|
||||
/// Finalizes request creation and returns `ServiceRequest` instance.
|
||||
pub fn to_srv_request(mut self) -> ServiceRequest {
|
||||
let (mut head, payload) = self.finish().into_parts();
|
||||
head.peer_addr = self.peer_addr;
|
||||
@ -279,12 +286,12 @@ impl TestRequest {
|
||||
)
|
||||
}
|
||||
|
||||
/// Complete request creation and generate `ServiceResponse` instance
|
||||
/// Finalizes request creation and returns `ServiceResponse` instance.
|
||||
pub fn to_srv_response<B>(self, res: HttpResponse<B>) -> ServiceResponse<B> {
|
||||
self.to_srv_request().into_response(res)
|
||||
}
|
||||
|
||||
/// Complete request creation and generate `HttpRequest` instance
|
||||
/// Finalizes request creation and returns `HttpRequest` instance.
|
||||
pub fn to_http_request(mut self) -> HttpRequest {
|
||||
let (mut head, _) = self.finish().into_parts();
|
||||
head.peer_addr = self.peer_addr;
|
||||
@ -302,7 +309,7 @@ impl TestRequest {
|
||||
)
|
||||
}
|
||||
|
||||
/// Complete request creation and generate `HttpRequest` and `Payload` instances
|
||||
/// Finalizes request creation and returns `HttpRequest` and `Payload` pair.
|
||||
pub fn to_http_parts(mut self) -> (HttpRequest, Payload) {
|
||||
let (mut head, payload) = self.finish().into_parts();
|
||||
head.peer_addr = self.peer_addr;
|
||||
@ -322,7 +329,7 @@ impl TestRequest {
|
||||
(req, payload)
|
||||
}
|
||||
|
||||
/// Complete request creation, calls service and waits for response future completion.
|
||||
/// Finalizes request creation, calls service, and waits for response future completion.
|
||||
pub async fn send_request<S, B, E>(self, app: &S) -> S::Response
|
||||
where
|
||||
S: Service<Request, Response = ServiceResponse<B>, Error = E>,
|
||||
|
@ -2,7 +2,7 @@
|
||||
|
||||
use std::{fmt, ops};
|
||||
|
||||
use actix_utils::future::{err, ok, Ready};
|
||||
use actix_utils::future::{ready, Ready};
|
||||
|
||||
use crate::{
|
||||
dev::Payload, error::ParseError, extract::FromRequest, http::header::Header as ParseHeader,
|
||||
@ -66,8 +66,8 @@ where
|
||||
#[inline]
|
||||
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
||||
match ParseHeader::parse(req) {
|
||||
Ok(header) => ok(Header(header)),
|
||||
Err(e) => err(e),
|
||||
Ok(header) => ready(Ok(Header(header))),
|
||||
Err(err) => ready(Err(err)),
|
||||
}
|
||||
}
|
||||
}
|
||||
|
@ -328,14 +328,19 @@ impl<T: DeserializeOwned> JsonBody<T> {
|
||||
ctype_required: bool,
|
||||
) -> Self {
|
||||
// check content-type
|
||||
let can_parse_json = if let Ok(Some(mime)) = req.mime_type() {
|
||||
mime.subtype() == mime::JSON
|
||||
|| mime.suffix() == Some(mime::JSON)
|
||||
|| ctype_fn.map_or(false, |predicate| predicate(mime))
|
||||
} else {
|
||||
// if `ctype_required` is false, assume payload is
|
||||
// json even when content-type header is missing
|
||||
!ctype_required
|
||||
let can_parse_json = match (ctype_required, req.mime_type()) {
|
||||
(true, Ok(Some(mime))) => {
|
||||
mime.subtype() == mime::JSON
|
||||
|| mime.suffix() == Some(mime::JSON)
|
||||
|| ctype_fn.map_or(false, |predicate| predicate(mime))
|
||||
}
|
||||
|
||||
// if content-type is expected but not parsable as mime type, bail
|
||||
(true, _) => false,
|
||||
|
||||
// if content-type validation is disabled, assume payload is JSON
|
||||
// even when content-type header is missing or invalid mime type
|
||||
(false, _) => true,
|
||||
};
|
||||
|
||||
if !can_parse_json {
|
||||
@ -725,6 +730,25 @@ mod tests {
|
||||
assert!(s.is_ok())
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_json_ignoring_content_type() {
|
||||
let (req, mut pl) = TestRequest::default()
|
||||
.insert_header((
|
||||
header::CONTENT_LENGTH,
|
||||
header::HeaderValue::from_static("16"),
|
||||
))
|
||||
.insert_header((
|
||||
header::CONTENT_TYPE,
|
||||
header::HeaderValue::from_static("invalid/value"),
|
||||
))
|
||||
.set_payload(Bytes::from_static(b"{\"name\": \"test\"}"))
|
||||
.app_data(JsonConfig::default().content_type_required(false))
|
||||
.to_http_parts();
|
||||
|
||||
let s = Json::<MyObject>::from_request(&req, &mut pl).await;
|
||||
assert!(s.is_ok());
|
||||
}
|
||||
|
||||
#[actix_rt::test]
|
||||
async fn test_with_config_in_data_wrapper() {
|
||||
let (req, mut pl) = TestRequest::default()
|
||||
|
@ -96,7 +96,7 @@ async fn negotiate_encoding_gzip() {
|
||||
|
||||
let req = srv
|
||||
.post("/static")
|
||||
.insert_header((header::ACCEPT_ENCODING, "gzip,br,zstd"))
|
||||
.insert_header((header::ACCEPT_ENCODING, "gzip, br;q=0.8, zstd;q=0.5"))
|
||||
.send();
|
||||
|
||||
let mut res = req.await.unwrap();
|
||||
@ -109,7 +109,7 @@ async fn negotiate_encoding_gzip() {
|
||||
let mut res = srv
|
||||
.post("/static")
|
||||
.no_decompress()
|
||||
.insert_header((header::ACCEPT_ENCODING, "gzip,br,zstd"))
|
||||
.insert_header((header::ACCEPT_ENCODING, "gzip, br;q=0.8, zstd;q=0.5"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
@ -123,9 +123,11 @@ async fn negotiate_encoding_gzip() {
|
||||
async fn negotiate_encoding_br() {
|
||||
let srv = test_server!();
|
||||
|
||||
// check that brotli content-encoding header is returned
|
||||
|
||||
let req = srv
|
||||
.post("/static")
|
||||
.insert_header((header::ACCEPT_ENCODING, "br,zstd,gzip"))
|
||||
.insert_header((header::ACCEPT_ENCODING, "br, zstd, gzip"))
|
||||
.send();
|
||||
|
||||
let mut res = req.await.unwrap();
|
||||
@ -135,10 +137,26 @@ async fn negotiate_encoding_br() {
|
||||
let bytes = res.body().await.unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(LOREM));
|
||||
|
||||
// check that brotli is preferred even when later in (q-less) list
|
||||
|
||||
let req = srv
|
||||
.post("/static")
|
||||
.insert_header((header::ACCEPT_ENCODING, "gzip, zstd, br"))
|
||||
.send();
|
||||
|
||||
let mut res = req.await.unwrap();
|
||||
assert_eq!(res.status(), StatusCode::OK);
|
||||
assert_eq!(res.headers().get(header::CONTENT_ENCODING).unwrap(), "br");
|
||||
|
||||
let bytes = res.body().await.unwrap();
|
||||
assert_eq!(bytes, Bytes::from_static(LOREM));
|
||||
|
||||
// check that returned content is actually brotli encoded
|
||||
|
||||
let mut res = srv
|
||||
.post("/static")
|
||||
.no_decompress()
|
||||
.insert_header((header::ACCEPT_ENCODING, "br,zstd,gzip"))
|
||||
.insert_header((header::ACCEPT_ENCODING, "br, zstd, gzip"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
@ -154,7 +172,7 @@ async fn negotiate_encoding_zstd() {
|
||||
|
||||
let req = srv
|
||||
.post("/static")
|
||||
.insert_header((header::ACCEPT_ENCODING, "zstd,gzip,br"))
|
||||
.insert_header((header::ACCEPT_ENCODING, "zstd, gzip, br;q=0.8"))
|
||||
.send();
|
||||
|
||||
let mut res = req.await.unwrap();
|
||||
@ -167,7 +185,7 @@ async fn negotiate_encoding_zstd() {
|
||||
let mut res = srv
|
||||
.post("/static")
|
||||
.no_decompress()
|
||||
.insert_header((header::ACCEPT_ENCODING, "zstd,gzip,br"))
|
||||
.insert_header((header::ACCEPT_ENCODING, "zstd, gzip, br;q=0.8"))
|
||||
.send()
|
||||
.await
|
||||
.unwrap();
|
||||
@ -207,7 +225,7 @@ async fn gzip_no_decompress() {
|
||||
// don't decompress response body
|
||||
.no_decompress()
|
||||
// signal that we want a compressed body
|
||||
.insert_header((header::ACCEPT_ENCODING, "gzip,br,zstd"))
|
||||
.insert_header((header::ACCEPT_ENCODING, "gzip, br;q=0.8, zstd;q=0.5"))
|
||||
.send();
|
||||
|
||||
let mut res = req.await.unwrap();
|
||||
|
@ -1,5 +1,3 @@
|
||||
#![allow(clippy::uninlined_format_args)]
|
||||
|
||||
#[cfg(feature = "openssl")]
|
||||
extern crate tls_openssl as openssl;
|
||||
|
||||
|
@ -743,7 +743,7 @@ mod plus_rustls {
|
||||
.map(char::from)
|
||||
.collect::<String>();
|
||||
|
||||
let srv = actix_test::start_with(actix_test::config().rustls_021(tls_config()), || {
|
||||
let srv = actix_test::start_with(actix_test::config().rustls_0_21(tls_config()), || {
|
||||
App::new().service(web::resource("/").route(web::to(|bytes: Bytes| async {
|
||||
// echo decompressed request body back in response
|
||||
HttpResponse::Ok()
|
||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user