mirror of
https://github.com/actix/actix-extras.git
synced 2025-04-22 18:04:52 +02:00
Compare commits
337 Commits
session-v0
...
master
Author | SHA1 | Date | |
---|---|---|---|
|
c04cc19e73 | ||
|
6a13b3b182 | ||
|
d994912ac2 | ||
|
5f6f20cf37 | ||
|
5145924410 | ||
|
b20dec36ac | ||
|
f6e45d487b | ||
|
c53e198ea7 | ||
|
4d9984ee76 | ||
|
9a08090709 | ||
|
7d3348bb29 | ||
|
c0fa63af39 | ||
|
0b5e2b3647 | ||
|
b95595b9cd | ||
|
4b3f87e915 | ||
|
144c7f92b9 | ||
|
c71b9dd443 | ||
|
282d56e96b | ||
|
d514ad3af5 | ||
|
109e6a4793 | ||
|
bb0c7f21d9 | ||
|
3f7a479a76 | ||
|
fc4b656c3b | ||
|
0f35de7da1 | ||
|
8294fcc645 | ||
|
3de6b03711 | ||
|
64931189c7 | ||
|
265b213123 | ||
|
695369f02f | ||
|
87d9e51112 | ||
|
8c11d37dda | ||
|
d97b36652a | ||
|
98847b9279 | ||
|
cd1b77134e | ||
|
105932706d | ||
|
18f94fa8b5 | ||
|
66b82f0f30 | ||
|
d67abde5f3 | ||
|
3eafe7f5ce | ||
|
3b5f7ae68c | ||
|
036af488fd | ||
|
77406cbb71 | ||
|
2ede588693 | ||
|
21680e0ebe | ||
|
370f9d3033 | ||
|
8f4fb348b3 | ||
|
ff4b173716 | ||
|
49aacfce9f | ||
|
dd20ebb6cb | ||
|
a3211b73d3 | ||
|
a89d3a58bc | ||
|
3c640ec120 | ||
|
26ccf8b200 | ||
|
dd1421f1a0 | ||
|
4eb779be77 | ||
|
48646d1bd3 | ||
|
275675e1c2 | ||
|
50d2fee4e2 | ||
|
0c0d13be12 | ||
|
d10b71fe06 | ||
|
f2339971cd | ||
|
517e72f248 | ||
|
504e89403b | ||
|
31b1dc5aa8 | ||
|
d7daf441d1 | ||
|
2de4b1886c | ||
|
caa5dbc5b3 | ||
|
c259e715f8 | ||
|
d8a86751f0 | ||
|
cac93d2bc7 | ||
|
95f4e0f692 | ||
|
24f3985eab | ||
|
b0d2947a4a | ||
|
0802eff40d | ||
|
2a6a36af23 | ||
|
3ebdc6192c | ||
|
87cf947a45 | ||
|
f063bec5ba | ||
|
45e9e00285 | ||
|
6934db623b | ||
|
1a658a98e1 | ||
|
2a092a19a8 | ||
|
032aeb6fdb | ||
|
52e58610e4 | ||
|
023158cfa8 | ||
|
14c605fae2 | ||
|
d94c023bf9 | ||
|
7e21fd753e | ||
|
e7ee2a06ab | ||
|
8aa2c959c4 | ||
|
2f1d1daee8 | ||
|
d15572b501 | ||
|
b9e47d61c3 | ||
|
515a727ca3 | ||
|
20234ec555 | ||
|
e4bb5ed355 | ||
|
5368569d00 | ||
|
21b9408a23 | ||
|
5879740322 | ||
|
4adc9f8884 | ||
|
abf75eeb06 | ||
|
433c926503 | ||
|
8ebb12b75a | ||
|
931c4eea4d | ||
|
8195484415 | ||
|
3ae4ef2706 | ||
|
65c698cd7f | ||
|
f2ef72d056 | ||
|
e4ee236341 | ||
|
41ae57d414 | ||
|
1b82024499 | ||
|
6b04450703 | ||
|
c0c7588a57 | ||
|
b918084a53 | ||
|
b762b41360 | ||
|
da53492c8c | ||
|
2c81bc093b | ||
|
a2ef65715b | ||
|
9beb348d45 | ||
|
66544952b6 | ||
|
9ddb95b74a | ||
|
f450e3fb85 | ||
|
31951dcc9b | ||
|
dfc6fe1986 | ||
|
122fba0580 | ||
|
f250348e57 | ||
|
e6f99e915d | ||
|
9d68074bf1 | ||
|
bbb4ed047c | ||
|
39291c86b7 | ||
|
db2193b8c5 | ||
|
f0c33a970f | ||
|
74c8545363 | ||
|
9112cf9f23 | ||
|
563d6e0b20 | ||
|
a71c7f6a90 | ||
|
a5f5e31a82 | ||
|
5414e2655b | ||
|
daffc24245 | ||
|
2e0cbb8bbb | ||
|
7fe13e142e | ||
|
8ddbf26cc1 | ||
|
b9769edca1 | ||
|
e3027549c5 | ||
|
1934457e48 | ||
|
254d4084a9 | ||
|
a9e615bac4 | ||
|
1e70159e08 | ||
|
89bf63e1ef | ||
|
8b4e8ea34e | ||
|
5ceb3c72cd | ||
|
c62b271d9a | ||
|
320cbebc7e | ||
|
0c859a96c8 | ||
|
d55fc6d7f5 | ||
|
e2bf504055 | ||
|
77b8dcdf59 | ||
|
b694c9317a | ||
|
57eaad2ffe | ||
|
0cb0e28208 | ||
|
8049a75d9f | ||
|
0dd810e213 | ||
|
5bf831c27b | ||
|
a7e3503ad1 | ||
|
819f45106f | ||
|
4f76943423 | ||
|
2f30fd71a9 | ||
|
5198c68c06 | ||
|
2d4cf5f422 | ||
|
53dce5c34f | ||
|
8de686a711 | ||
|
50fd71d496 | ||
|
3c5478966f | ||
|
1e18d62852 | ||
|
7aeeb9a445 | ||
|
5b2085f414 | ||
|
6afca96ddf | ||
|
a48c2926f9 | ||
|
6d0ab96dfd | ||
|
a593a8dc90 | ||
|
4d79d263ef | ||
|
31540f8e4b | ||
|
11046d7663 | ||
|
73b2aac6d6 | ||
|
76d9313171 | ||
|
373a89a978 | ||
|
61f16c609a | ||
|
ecd2016c09 | ||
|
471f07e27f | ||
|
077c6edced | ||
|
fad631c448 | ||
|
20f72cab3e | ||
|
4bad825456 | ||
|
cb3eba93cc | ||
|
9d993c6c73 | ||
|
4761826616 | ||
|
ec340670a8 | ||
|
3a7834c3ba | ||
|
7db43782ce | ||
|
1ee1afb2a6 | ||
|
9e4754bbfa | ||
|
cd3e5f9772 | ||
|
45ee50f9cb | ||
|
1d6ef8938f | ||
|
316c0d238d | ||
|
5baa3c3d95 | ||
|
2dea1f2748 | ||
|
09ff35bd2d | ||
|
6caf37cedd | ||
|
bafd8179ff | ||
|
3fad53211a | ||
|
9a7113028e | ||
|
9e31f5b306 | ||
|
94f99e4843 | ||
|
600dda5ef3 | ||
|
2a074ddf18 | ||
|
9fc34a9c48 | ||
|
f942d8a191 | ||
|
b737452294 | ||
|
55ace79d64 | ||
|
c029287801 | ||
|
0d27e3a65a | ||
|
257871ca7a | ||
|
d921417726 | ||
|
70b46280ed | ||
|
55d70231cc | ||
|
aaedb9c625 | ||
|
75386f4a1d | ||
|
8a31f3020e | ||
|
8c93f5314b | ||
|
f37c93a2a8 | ||
|
111d95eaea | ||
|
8729f60f79 | ||
|
77ee27b4ae | ||
|
b948ac9f7a | ||
|
ad1f15eb18 | ||
|
8a9c604c03 | ||
|
218f18e69d | ||
|
2bc16eee18 | ||
|
713b157fd4 | ||
|
bf49b39740 | ||
|
441d604c00 | ||
|
1ed893a08c | ||
|
708aa945dc | ||
|
9be4f1ff73 | ||
|
f8a1165d10 | ||
|
d9175a0399 | ||
|
fe4d3d366d | ||
|
1036f54fd0 | ||
|
e9428ba261 | ||
|
779860b664 | ||
|
6848312467 | ||
|
8c509151f1 | ||
|
1774b8a36e | ||
|
9508be94d5 | ||
|
8e76c6c628 | ||
|
8fd166435f | ||
|
1ac325ab79 | ||
|
b95ce3a210 | ||
|
ac444ca798 | ||
|
fb8a814acb | ||
|
da0a806e8d | ||
|
d28ab6eaa1 | ||
|
a2c5cbd637 | ||
|
e6ef190510 | ||
|
3b5682c860 | ||
|
82a100d96c | ||
|
d98ebf2bdf | ||
|
1561bda822 | ||
|
339b81e843 | ||
|
eb3660a772 | ||
|
9a3b410409 | ||
|
32313c0af6 | ||
|
a623c50e9c | ||
|
7d932cd540 | ||
|
ffe122b76e | ||
|
1e682e7a59 | ||
|
e61dbae860 | ||
|
a325f5dd02 | ||
|
bad6159516 | ||
|
7c3c9357e0 | ||
|
bcb8dbe1fc | ||
|
983746f106 | ||
|
b054733854 | ||
|
ab3f591307 | ||
|
c08cd8a23a | ||
|
da32c1bb49 | ||
|
90766e5d68 | ||
|
f678842e46 | ||
|
e13b62fc6b | ||
|
6e79465362 | ||
|
cd9dc163e5 | ||
|
810a88a156 | ||
|
cfd16c5478 | ||
|
07c5176bd0 | ||
|
446c92c3d0 | ||
|
65a6252fec | ||
|
73732b0a62 | ||
|
ff06958b32 | ||
|
4d2f4d58b4 | ||
|
140453c649 | ||
|
fbae63d07f | ||
|
417c06b00e | ||
|
553c2bfb92 | ||
|
1089faaf93 | ||
|
1cc37c371e | ||
|
d853c115b6 | ||
|
603215095a | ||
|
d3fb564380 | ||
|
ee71d4cfa7 | ||
|
f39a64f526 | ||
|
d5dc087e93 | ||
|
169b262c66 | ||
|
d4384932ff | ||
|
4e1a95fc75 | ||
|
910f964100 | ||
|
3e002a677b | ||
|
ca9879425b | ||
|
ecd7756644 | ||
|
9bc014b96f | ||
|
e0ffd4e592 | ||
|
97ee544057 | ||
|
3b1c161547 | ||
|
1830f66dca | ||
|
c52ea7a5d2 | ||
|
b1cea64795 | ||
|
b8f4a658a9 | ||
|
69e4264e0c | ||
|
c2f068db66 | ||
|
d09299390a | ||
|
a42ca24327 | ||
|
3c48e00e7a | ||
|
7267a19b1d | ||
|
f6508f290c | ||
|
d11a272384 | ||
|
8fd1772d5e | ||
|
aebf9ccf58 |
@ -1,7 +1,7 @@
|
|||||||
[alias]
|
[alias]
|
||||||
lint = "clippy --workspace --tests --examples --bins -- -Dclippy::todo"
|
lint = "clippy --workspace --tests --examples --bins -- -Dclippy::todo"
|
||||||
ci-min = "hack check --workspace --no-default-features"
|
ci-min = "hack check --workspace --no-default-features"
|
||||||
ci-check-min-tests = "hack check --workspace --no-default-features --tests --examples"
|
ci-check-min-examples = "hack check --workspace --no-default-features --examples"
|
||||||
ci-check = "check --workspace --tests --examples --bins"
|
ci-check = "check --workspace --tests --examples --bins"
|
||||||
ci-test = "test --workspace --lib --tests --all-features --examples --bins --no-fail-fast"
|
ci-test = "test --workspace --lib --tests --all-features --examples --bins --no-fail-fast"
|
||||||
ci-doctest = "test --workspace --doc --all-features --no-fail-fast"
|
ci-doctest = "test --workspace --doc --all-features --no-fail-fast"
|
||||||
|
14
.github/ISSUE_TEMPLATE/bug_report.md
vendored
14
.github/ISSUE_TEMPLATE/bug_report.md
vendored
@ -3,35 +3,41 @@ name: bug report
|
|||||||
about: create a bug report
|
about: create a bug report
|
||||||
---
|
---
|
||||||
|
|
||||||
Your issue may already be reported!
|
Your issue may already be reported! Please search on the [actix-extras issue tracker](https://github.com/actix/actix-extras/issues) before creating one.
|
||||||
Please search on the [actix-extras issue tracker](https://github.com/actix/actix-extras/issues) before creating one.
|
|
||||||
|
|
||||||
## Expected Behavior
|
## Expected Behavior
|
||||||
|
|
||||||
<!--- If you're describing a bug, tell us what should happen -->
|
<!--- If you're describing a bug, tell us what should happen -->
|
||||||
<!--- If you're suggesting a change/improvement, tell us how it should work -->
|
<!--- If you're suggesting a change/improvement, tell us how it should work -->
|
||||||
|
|
||||||
## Current Behavior
|
## Current Behavior
|
||||||
|
|
||||||
<!--- If describing a bug, tell us what happens instead of the expected behavior -->
|
<!--- If describing a bug, tell us what happens instead of the expected behavior -->
|
||||||
<!--- If suggesting a change/improvement, explain the difference from current behavior -->
|
<!--- If suggesting a change/improvement, explain the difference from current behavior -->
|
||||||
|
|
||||||
## Possible Solution
|
## Possible Solution
|
||||||
|
|
||||||
<!--- Not obligatory, but suggest a fix/reason for the bug, -->
|
<!--- Not obligatory, but suggest a fix/reason for the bug, -->
|
||||||
<!--- or ideas how to implement the addition or change -->
|
<!--- or ideas how to implement the addition or change -->
|
||||||
|
|
||||||
## Steps to Reproduce (for bugs)
|
## Steps to Reproduce (for bugs)
|
||||||
|
|
||||||
<!--- Provide a link to a live example, or an unambiguous set of steps to -->
|
<!--- Provide a link to a live example, or an unambiguous set of steps to -->
|
||||||
<!--- reproduce this bug. Include code to reproduce, if relevant -->
|
<!--- reproduce this bug. Include code to reproduce, if relevant -->
|
||||||
|
|
||||||
1.
|
1.
|
||||||
2.
|
2.
|
||||||
3.
|
3.
|
||||||
4.
|
4.
|
||||||
|
|
||||||
## Context
|
## Context
|
||||||
|
|
||||||
<!--- How has this issue affected you? What are you trying to accomplish? -->
|
<!--- How has this issue affected you? What are you trying to accomplish? -->
|
||||||
<!--- Providing context helps us come up with a solution that is most useful in the real world -->
|
<!--- Providing context helps us come up with a solution that is most useful in the real world -->
|
||||||
|
|
||||||
## Your Environment
|
## Your Environment
|
||||||
|
|
||||||
<!--- Include as many relevant details about the environment you experienced the bug in -->
|
<!--- Include as many relevant details about the environment you experienced the bug in -->
|
||||||
|
|
||||||
* Rust Version (I.e, output of `rustc -V`):
|
- Rust version (output of `rustc -V`):
|
||||||
* Actix-* crate(s) Version:
|
- `actix-*` crate versions:
|
||||||
|
5
.github/ISSUE_TEMPLATE/config.yml
vendored
5
.github/ISSUE_TEMPLATE/config.yml
vendored
@ -1,5 +0,0 @@
|
|||||||
blank_issues_enabled: true
|
|
||||||
contact_links:
|
|
||||||
- name: Gitter channel (actix)
|
|
||||||
url: https://gitter.im/actix/actix
|
|
||||||
about: Please ask and answer questions about the actix project here.
|
|
9
.github/PULL_REQUEST_TEMPLATE.md
vendored
9
.github/PULL_REQUEST_TEMPLATE.md
vendored
@ -2,25 +2,26 @@
|
|||||||
<!-- Please fill out the following to make our reviews easy. -->
|
<!-- Please fill out the following to make our reviews easy. -->
|
||||||
|
|
||||||
## PR Type
|
## PR Type
|
||||||
|
|
||||||
<!-- What kind of change does this PR make? -->
|
<!-- What kind of change does this PR make? -->
|
||||||
<!-- Bug Fix / Feature / Refactor / Code Style / Other -->
|
<!-- Bug Fix / Feature / Refactor / Code Style / Other -->
|
||||||
|
|
||||||
INSERT_PR_TYPE
|
INSERT_PR_TYPE
|
||||||
|
|
||||||
|
|
||||||
## PR Checklist
|
## PR Checklist
|
||||||
|
|
||||||
<!-- Check your PR fulfills the following items. -->
|
<!-- Check your PR fulfills the following items. -->
|
||||||
<!-- For draft PRs check the boxes as you complete them. -->
|
<!-- For draft PRs check the boxes as you complete them. -->
|
||||||
|
|
||||||
- [ ] Tests for the changes have been added / updated.
|
- [ ] Tests for the changes have been added / updated.
|
||||||
- [ ] Documentation comments have been added / updated.
|
- [ ] Documentation comments have been added / updated.
|
||||||
- [ ] A changelog entry has been made for the appropriate packages.
|
- [ ] A changelog entry has been made for the appropriate packages.
|
||||||
- [ ] Format code with the latest stable rustfmt.
|
- [ ] Format code with the nightly rustfmt (`cargo +nightly fmt`).
|
||||||
|
|
||||||
|
|
||||||
## Overview
|
## Overview
|
||||||
|
|
||||||
<!-- Describe the current and new behavior. -->
|
<!-- Describe the current and new behavior. -->
|
||||||
<!-- Emphasize any breaking changes. -->
|
<!-- Emphasize any breaking changes. -->
|
||||||
|
|
||||||
|
|
||||||
<!-- If this PR fixes or closes an issue, reference it here. -->
|
<!-- If this PR fixes or closes an issue, reference it here. -->
|
||||||
<!-- Closes #000 -->
|
<!-- Closes #000 -->
|
||||||
|
10
.github/dependabot.yml
vendored
Normal file
10
.github/dependabot.yml
vendored
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
version: 2
|
||||||
|
updates:
|
||||||
|
- package-ecosystem: github-actions
|
||||||
|
directory: /
|
||||||
|
schedule:
|
||||||
|
interval: monthly
|
||||||
|
- package-ecosystem: cargo
|
||||||
|
directory: /
|
||||||
|
schedule:
|
||||||
|
interval: weekly
|
134
.github/workflows/ci-master.yml
vendored
134
.github/workflows/ci-master.yml
vendored
@ -1,134 +0,0 @@
|
|||||||
name: CI (master only)
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [master]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build_and_test_linux_nightly:
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
target:
|
|
||||||
- { name: Linux, os: ubuntu-latest, triple: x86_64-unknown-linux-gnu }
|
|
||||||
version:
|
|
||||||
- nightly
|
|
||||||
|
|
||||||
name: ${{ matrix.target.name }} / ${{ matrix.version }}
|
|
||||||
runs-on: ${{ matrix.target.os }}
|
|
||||||
|
|
||||||
services:
|
|
||||||
redis:
|
|
||||||
image: redis:5.0.7
|
|
||||||
ports:
|
|
||||||
- 6379:6379
|
|
||||||
options: --entrypoint redis-server
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v2
|
|
||||||
|
|
||||||
- name: Install ${{ matrix.version }}
|
|
||||||
uses: actions-rs/toolchain@v1
|
|
||||||
with:
|
|
||||||
toolchain: ${{ matrix.version }}-${{ matrix.target.triple }}
|
|
||||||
profile: minimal
|
|
||||||
override: true
|
|
||||||
|
|
||||||
- name: Generate Cargo.lock
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: generate-lockfile
|
|
||||||
- name: Cache Dependencies
|
|
||||||
uses: Swatinem/rust-cache@v1.2.0
|
|
||||||
|
|
||||||
- name: Install cargo-hack
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: install
|
|
||||||
args: cargo-hack
|
|
||||||
|
|
||||||
- name: check minimal
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with: { command: ci-min }
|
|
||||||
|
|
||||||
- name: check minimal + tests
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with: { command: ci-check-min-tests }
|
|
||||||
|
|
||||||
- name: check default
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with: { command: ci-check }
|
|
||||||
|
|
||||||
- name: tests
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
timeout-minutes: 40
|
|
||||||
with: { command: ci-test }
|
|
||||||
|
|
||||||
- name: Clear the cargo caches
|
|
||||||
run: |
|
|
||||||
cargo install cargo-cache --version 0.6.2 --no-default-features --features ci-autoclean
|
|
||||||
cargo-cache
|
|
||||||
|
|
||||||
build_and_test_other_nightly:
|
|
||||||
strategy:
|
|
||||||
fail-fast: false
|
|
||||||
matrix:
|
|
||||||
target:
|
|
||||||
- { name: macOS, os: macos-latest, triple: x86_64-apple-darwin }
|
|
||||||
- { name: Windows, os: windows-latest, triple: x86_64-pc-windows-msvc }
|
|
||||||
version:
|
|
||||||
- nightly
|
|
||||||
|
|
||||||
name: ${{ matrix.target.name }} / ${{ matrix.version }}
|
|
||||||
runs-on: ${{ matrix.target.os }}
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v2
|
|
||||||
|
|
||||||
- name: Install ${{ matrix.version }}
|
|
||||||
uses: actions-rs/toolchain@v1
|
|
||||||
with:
|
|
||||||
toolchain: ${{ matrix.version }}-${{ matrix.target.triple }}
|
|
||||||
profile: minimal
|
|
||||||
override: true
|
|
||||||
|
|
||||||
- name: Generate Cargo.lock
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: generate-lockfile
|
|
||||||
- name: Cache Dependencies
|
|
||||||
uses: Swatinem/rust-cache@v1.2.0
|
|
||||||
|
|
||||||
- name: Install cargo-hack
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: install
|
|
||||||
args: cargo-hack
|
|
||||||
|
|
||||||
- name: check minimal
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with: { command: ci-min }
|
|
||||||
|
|
||||||
- name: check minimal + tests
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with: { command: ci-check-min-tests }
|
|
||||||
|
|
||||||
- name: check default
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with: { command: ci-check }
|
|
||||||
|
|
||||||
- name: tests
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
timeout-minutes: 40
|
|
||||||
with:
|
|
||||||
command: ci-test
|
|
||||||
args: >-
|
|
||||||
--exclude=actix-redis
|
|
||||||
--exclude=actix-session
|
|
||||||
--exclude=actix-limitation
|
|
||||||
-- --nocapture
|
|
||||||
|
|
||||||
- name: Clear the cargo caches
|
|
||||||
run: |
|
|
||||||
cargo install cargo-cache --version 0.6.2 --no-default-features --features ci-autoclean
|
|
||||||
cargo-cache
|
|
107
.github/workflows/ci-post-merge.yml
vendored
Normal file
107
.github/workflows/ci-post-merge.yml
vendored
Normal file
@ -0,0 +1,107 @@
|
|||||||
|
name: CI (post-merge)
|
||||||
|
|
||||||
|
on:
|
||||||
|
push: { branches: [master] }
|
||||||
|
|
||||||
|
permissions: { contents: read }
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
|
jobs:
|
||||||
|
build_and_test_linux_nightly:
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
matrix:
|
||||||
|
target:
|
||||||
|
- { name: Linux, os: ubuntu-latest, triple: x86_64-unknown-linux-gnu }
|
||||||
|
|
||||||
|
name: ${{ matrix.target.name }} / nightly
|
||||||
|
runs-on: ${{ matrix.target.os }}
|
||||||
|
|
||||||
|
services:
|
||||||
|
redis:
|
||||||
|
image: redis:5.0.7
|
||||||
|
ports:
|
||||||
|
- 6379:6379
|
||||||
|
options: --entrypoint redis-server
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Install Rust (nightly)
|
||||||
|
uses: actions-rust-lang/setup-rust-toolchain@v1.11.0
|
||||||
|
with:
|
||||||
|
toolchain: nightly
|
||||||
|
|
||||||
|
- name: Install cargo-hack, cargo-ci-cache-clean
|
||||||
|
uses: taiki-e/install-action@v2.49.42
|
||||||
|
with:
|
||||||
|
tool: cargo-hack,cargo-ci-cache-clean
|
||||||
|
|
||||||
|
- name: check minimal
|
||||||
|
run: cargo ci-min
|
||||||
|
|
||||||
|
- name: check minimal + examples
|
||||||
|
run: cargo ci-check-min-examples
|
||||||
|
|
||||||
|
- name: check default
|
||||||
|
run: cargo ci-check
|
||||||
|
|
||||||
|
- name: tests
|
||||||
|
timeout-minutes: 40
|
||||||
|
run: cargo ci-test
|
||||||
|
|
||||||
|
- name: CI cache clean
|
||||||
|
run: cargo-ci-cache-clean
|
||||||
|
|
||||||
|
build_and_test_other_nightly:
|
||||||
|
strategy:
|
||||||
|
fail-fast: false
|
||||||
|
# prettier-ignore
|
||||||
|
matrix:
|
||||||
|
target:
|
||||||
|
- { name: macOS, os: macos-latest, triple: x86_64-apple-darwin }
|
||||||
|
- { name: Windows, os: windows-latest, triple: x86_64-pc-windows-msvc }
|
||||||
|
|
||||||
|
name: ${{ matrix.target.name }} / nightly
|
||||||
|
runs-on: ${{ matrix.target.os }}
|
||||||
|
|
||||||
|
steps:
|
||||||
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
|
- name: Install OpenSSL
|
||||||
|
if: matrix.target.os == 'windows-latest'
|
||||||
|
shell: bash
|
||||||
|
run: |
|
||||||
|
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 (nightly)
|
||||||
|
uses: actions-rust-lang/setup-rust-toolchain@v1.11.0
|
||||||
|
with:
|
||||||
|
toolchain: nightly
|
||||||
|
|
||||||
|
- name: Install cargo-hack and cargo-ci-cache-clean
|
||||||
|
uses: taiki-e/install-action@v2.49.42
|
||||||
|
with:
|
||||||
|
tool: cargo-hack,cargo-ci-cache-clean
|
||||||
|
|
||||||
|
- name: check minimal
|
||||||
|
run: cargo ci-min
|
||||||
|
|
||||||
|
- name: check minimal + examples
|
||||||
|
run: cargo ci-check-min-examples
|
||||||
|
|
||||||
|
- name: check default
|
||||||
|
run: cargo ci-check
|
||||||
|
|
||||||
|
- name: tests
|
||||||
|
timeout-minutes: 40
|
||||||
|
run: cargo ci-test --exclude=actix-session --exclude=actix-limitation -- --nocapture
|
||||||
|
|
||||||
|
- name: CI cache clean
|
||||||
|
run: cargo-ci-cache-clean
|
157
.github/workflows/ci.yml
vendored
157
.github/workflows/ci.yml
vendored
@ -3,9 +3,17 @@ name: CI
|
|||||||
on:
|
on:
|
||||||
pull_request:
|
pull_request:
|
||||||
types: [opened, synchronize, reopened]
|
types: [opened, synchronize, reopened]
|
||||||
|
merge_group:
|
||||||
|
types: [checks_requested]
|
||||||
push:
|
push:
|
||||||
branches: [master]
|
branches: [master]
|
||||||
|
|
||||||
|
permissions: { contents: read }
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
build_and_test_linux:
|
build_and_test_linux:
|
||||||
strategy:
|
strategy:
|
||||||
@ -14,10 +22,10 @@ jobs:
|
|||||||
target:
|
target:
|
||||||
- { name: Linux, os: ubuntu-latest, triple: x86_64-unknown-linux-gnu }
|
- { name: Linux, os: ubuntu-latest, triple: x86_64-unknown-linux-gnu }
|
||||||
version:
|
version:
|
||||||
- 1.54.0 # MSRV
|
- { name: msrv, version: 1.75.0 }
|
||||||
- stable
|
- { name: stable, version: stable }
|
||||||
|
|
||||||
name: ${{ matrix.target.name }} / ${{ matrix.version }}
|
name: ${{ matrix.target.name }} / ${{ matrix.version.name }}
|
||||||
runs-on: ${{ matrix.target.os }}
|
runs-on: ${{ matrix.target.os }}
|
||||||
|
|
||||||
services:
|
services:
|
||||||
@ -33,136 +41,113 @@ jobs:
|
|||||||
--entrypoint redis-server
|
--entrypoint redis-server
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Install ${{ matrix.version }}
|
- name: Install Rust (${{ matrix.version.name }})
|
||||||
uses: actions-rs/toolchain@v1
|
uses: actions-rust-lang/setup-rust-toolchain@v1.11.0
|
||||||
with:
|
with:
|
||||||
toolchain: ${{ matrix.version }}-${{ matrix.target.triple }}
|
toolchain: ${{ matrix.version.version }}
|
||||||
profile: minimal
|
|
||||||
override: true
|
|
||||||
|
|
||||||
- name: Generate Cargo.lock
|
- name: Install cargo-hack and cargo-ci-cache-clean, just
|
||||||
uses: actions-rs/cargo@v1
|
uses: taiki-e/install-action@v2.49.42
|
||||||
with:
|
with:
|
||||||
command: generate-lockfile
|
tool: cargo-hack,cargo-ci-cache-clean,just
|
||||||
- name: Cache Dependencies
|
|
||||||
uses: Swatinem/rust-cache@v1.2.0
|
|
||||||
|
|
||||||
- name: Install cargo-hack
|
- name: workaround MSRV issues
|
||||||
uses: actions-rs/cargo@v1
|
if: matrix.version.name == 'msrv'
|
||||||
with:
|
run: just downgrade-for-msrv
|
||||||
command: install
|
|
||||||
args: cargo-hack
|
|
||||||
|
|
||||||
- name: check minimal
|
- name: check minimal
|
||||||
uses: actions-rs/cargo@v1
|
run: cargo ci-min
|
||||||
with: { command: ci-min }
|
|
||||||
|
|
||||||
- name: check minimal + tests
|
- name: check minimal + examples
|
||||||
uses: actions-rs/cargo@v1
|
run: cargo ci-check-min-examples
|
||||||
with: { command: ci-check-min-tests }
|
|
||||||
|
|
||||||
- name: check default
|
- name: check default
|
||||||
uses: actions-rs/cargo@v1
|
run: cargo ci-check
|
||||||
with: { command: ci-check }
|
|
||||||
|
|
||||||
- name: tests
|
- name: tests
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
timeout-minutes: 40
|
timeout-minutes: 40
|
||||||
with: { command: ci-test }
|
run: cargo ci-test
|
||||||
|
|
||||||
- name: Clear the cargo caches
|
- name: CI cache clean
|
||||||
run: |
|
run: cargo-ci-cache-clean
|
||||||
cargo install cargo-cache --version 0.6.2 --no-default-features --features ci-autoclean
|
|
||||||
cargo-cache
|
|
||||||
|
|
||||||
build_and_test_other:
|
build_and_test_other:
|
||||||
strategy:
|
strategy:
|
||||||
fail-fast: false
|
fail-fast: false
|
||||||
matrix:
|
matrix:
|
||||||
|
# prettier-ignore
|
||||||
target:
|
target:
|
||||||
- { name: macOS, os: macos-latest, triple: x86_64-apple-darwin }
|
- { name: macOS, os: macos-latest, triple: x86_64-apple-darwin }
|
||||||
- { name: Windows, os: windows-latest, triple: x86_64-pc-windows-msvc }
|
- { name: Windows, os: windows-latest, triple: x86_64-pc-windows-msvc }
|
||||||
version:
|
version:
|
||||||
- 1.54.0 # MSRV
|
- { name: msrv, version: 1.75.0 }
|
||||||
- stable
|
- { name: stable, version: stable }
|
||||||
|
|
||||||
name: ${{ matrix.target.name }} / ${{ matrix.version }}
|
name: ${{ matrix.target.name }} / ${{ matrix.version.name }}
|
||||||
runs-on: ${{ matrix.target.os }}
|
runs-on: ${{ matrix.target.os }}
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Install ${{ matrix.version }}
|
- name: Install OpenSSL
|
||||||
uses: actions-rs/toolchain@v1
|
if: matrix.target.os == 'windows-latest'
|
||||||
with:
|
shell: bash
|
||||||
toolchain: ${{ matrix.version }}-${{ matrix.target.triple }}
|
run: |
|
||||||
profile: minimal
|
set -e
|
||||||
override: true
|
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: Generate Cargo.lock
|
- name: Install Rust (${{ matrix.version.name }})
|
||||||
uses: actions-rs/cargo@v1
|
uses: actions-rust-lang/setup-rust-toolchain@v1.11.0
|
||||||
with:
|
with:
|
||||||
command: generate-lockfile
|
toolchain: ${{ matrix.version.version }}
|
||||||
- name: Cache Dependencies
|
|
||||||
uses: Swatinem/rust-cache@v1.2.0
|
|
||||||
|
|
||||||
- name: Install cargo-hack
|
- name: Install cargo-hack, cargo-ci-cache-clean, just
|
||||||
uses: actions-rs/cargo@v1
|
uses: taiki-e/install-action@v2.49.42
|
||||||
with:
|
with:
|
||||||
command: install
|
tool: cargo-hack,cargo-ci-cache-clean,just
|
||||||
args: cargo-hack
|
|
||||||
|
- name: workaround MSRV issues
|
||||||
|
if: matrix.version.name == 'msrv'
|
||||||
|
run: just downgrade-for-msrv
|
||||||
|
|
||||||
- name: check minimal
|
- name: check minimal
|
||||||
uses: actions-rs/cargo@v1
|
run: cargo ci-min
|
||||||
with: { command: ci-min }
|
|
||||||
|
|
||||||
- name: check minimal + tests
|
- name: check minimal + examples
|
||||||
uses: actions-rs/cargo@v1
|
run: cargo ci-check-min-examples
|
||||||
with: { command: ci-check-min-tests }
|
|
||||||
|
|
||||||
- name: check default
|
- name: check default
|
||||||
uses: actions-rs/cargo@v1
|
run: cargo ci-check
|
||||||
with: { command: ci-check }
|
|
||||||
|
|
||||||
- name: tests
|
- name: tests
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
timeout-minutes: 40
|
timeout-minutes: 40
|
||||||
with:
|
run: cargo ci-test --exclude=actix-session --exclude=actix-limitation
|
||||||
command: ci-test
|
|
||||||
args: >-
|
|
||||||
--exclude=actix-redis
|
|
||||||
--exclude=actix-session
|
|
||||||
--exclude=actix-limitation
|
|
||||||
|
|
||||||
- name: Clear the cargo caches
|
- name: CI cache clean
|
||||||
run: |
|
run: cargo-ci-cache-clean
|
||||||
cargo install cargo-cache --version 0.6.2 --no-default-features --features ci-autoclean
|
|
||||||
cargo-cache
|
|
||||||
|
|
||||||
doc_tests:
|
doc_tests:
|
||||||
name: doc tests
|
name: Documentation Tests
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Install Rust (nightly)
|
- name: Install Rust (nightly)
|
||||||
uses: actions-rs/toolchain@v1
|
uses: actions-rust-lang/setup-rust-toolchain@v1.11.0
|
||||||
with:
|
with:
|
||||||
toolchain: nightly-x86_64-unknown-linux-gnu
|
toolchain: nightly
|
||||||
profile: minimal
|
|
||||||
override: true
|
|
||||||
|
|
||||||
- name: Generate Cargo.lock
|
- name: Install just
|
||||||
uses: actions-rs/cargo@v1
|
uses: taiki-e/install-action@v2.49.42
|
||||||
with: { command: generate-lockfile }
|
|
||||||
- name: Cache Dependencies
|
|
||||||
uses: Swatinem/rust-cache@v1.3.0
|
|
||||||
|
|
||||||
- name: doc tests
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
timeout-minutes: 40
|
|
||||||
with:
|
with:
|
||||||
command: ci-doctest
|
tool: just
|
||||||
args: -- --nocapture
|
|
||||||
|
- name: Test docs
|
||||||
|
run: just test-docs
|
||||||
|
|
||||||
|
- name: Build docs
|
||||||
|
run: just doc
|
||||||
|
43
.github/workflows/coverage.yml
vendored
43
.github/workflows/coverage.yml
vendored
@ -1,11 +1,15 @@
|
|||||||
# disabled because `cargo tarpaulin` currently segfaults
|
|
||||||
|
|
||||||
name: Coverage
|
name: Coverage
|
||||||
|
|
||||||
on:
|
on:
|
||||||
push:
|
push:
|
||||||
branches: [master]
|
branches: [master]
|
||||||
|
|
||||||
|
permissions: { contents: read }
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
coverage:
|
coverage:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
@ -18,25 +22,26 @@ jobs:
|
|||||||
options: --entrypoint redis-server
|
options: --entrypoint redis-server
|
||||||
|
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Install stable
|
- name: Install Rust
|
||||||
uses: actions-rs/toolchain@v1
|
uses: actions-rust-lang/setup-rust-toolchain@v1.11.0
|
||||||
with:
|
with:
|
||||||
toolchain: stable-x86_64-unknown-linux-gnu
|
toolchain: nightly
|
||||||
profile: minimal
|
components: llvm-tools-preview
|
||||||
override: true
|
|
||||||
|
|
||||||
- name: Generate Cargo.lock
|
- name: Install just, cargo-llvm-cov, cargo-nextest
|
||||||
uses: actions-rs/cargo@v1
|
uses: taiki-e/install-action@v2.49.42
|
||||||
with: { command: generate-lockfile }
|
with:
|
||||||
- name: Cache Dependencies
|
tool: just,cargo-llvm-cov,cargo-nextest
|
||||||
uses: Swatinem/rust-cache@v1.2.0
|
|
||||||
|
- name: Generate code coverage
|
||||||
|
run: just test-coverage-codecov
|
||||||
|
|
||||||
- name: Generate coverage file
|
|
||||||
run: |
|
|
||||||
cargo install cargo-tarpaulin --vers "^0.13"
|
|
||||||
cargo tarpaulin --workspace --out Xml --verbose
|
|
||||||
- name: Upload to Codecov
|
- name: Upload to Codecov
|
||||||
uses: codecov/codecov-action@v1
|
uses: codecov/codecov-action@v5.4.0
|
||||||
with: { file: cobertura.xml }
|
with:
|
||||||
|
files: codecov.json
|
||||||
|
fail_ci_if_error: true
|
||||||
|
env:
|
||||||
|
CODECOV_TOKEN: ${{ secrets.CODECOV_TOKEN }}
|
||||||
|
45
.github/workflows/lint.yml
vendored
45
.github/workflows/lint.yml
vendored
@ -1,39 +1,48 @@
|
|||||||
name: Lint
|
name: Lint
|
||||||
|
|
||||||
on:
|
on: [pull_request]
|
||||||
pull_request:
|
|
||||||
types: [opened, synchronize, reopened]
|
permissions:
|
||||||
|
contents: read
|
||||||
|
|
||||||
|
concurrency:
|
||||||
|
group: ${{ github.workflow }}-${{ github.ref }}
|
||||||
|
cancel-in-progress: true
|
||||||
|
|
||||||
jobs:
|
jobs:
|
||||||
fmt:
|
fmt:
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Install Rust
|
- name: Install Rust (nightly)
|
||||||
uses: actions-rs/toolchain@v1
|
uses: actions-rust-lang/setup-rust-toolchain@v1.11.0
|
||||||
with:
|
with:
|
||||||
toolchain: stable
|
toolchain: nightly
|
||||||
components: rustfmt
|
components: rustfmt
|
||||||
|
|
||||||
- name: Check with rustfmt
|
- name: Check with rustfmt
|
||||||
uses: actions-rs/cargo@v1
|
run: cargo fmt --all -- --check
|
||||||
with:
|
|
||||||
command: fmt
|
|
||||||
args: --all -- --check
|
|
||||||
|
|
||||||
clippy:
|
clippy:
|
||||||
|
permissions:
|
||||||
|
contents: read
|
||||||
|
checks: write # to add clippy checks to PR diffs
|
||||||
|
|
||||||
runs-on: ubuntu-latest
|
runs-on: ubuntu-latest
|
||||||
steps:
|
steps:
|
||||||
- uses: actions/checkout@v2
|
- uses: actions/checkout@v4
|
||||||
|
|
||||||
- name: Install Rust
|
- name: Install Rust
|
||||||
uses: actions-rs/toolchain@v1
|
uses: actions-rust-lang/setup-rust-toolchain@v1.11.0
|
||||||
with:
|
with:
|
||||||
toolchain: stable
|
|
||||||
components: clippy
|
components: clippy
|
||||||
override: true
|
|
||||||
- name: Check with Clippy
|
- name: Check with Clippy
|
||||||
uses: actions-rs/clippy-check@v1
|
uses: giraffate/clippy-action@v1.0.1
|
||||||
with:
|
with:
|
||||||
token: ${{ secrets.GITHUB_TOKEN }}
|
reporter: github-pr-check
|
||||||
args: --workspace --tests --all-features
|
github_token: ${{ secrets.GITHUB_TOKEN }}
|
||||||
|
clippy_flags: >-
|
||||||
|
--workspace --all-features --tests --examples --bins --
|
||||||
|
-A unknown_lints -D clippy::todo -D clippy::dbg_macro
|
||||||
|
35
.github/workflows/upload-doc.yml
vendored
35
.github/workflows/upload-doc.yml
vendored
@ -1,35 +0,0 @@
|
|||||||
name: Upload Documentation
|
|
||||||
|
|
||||||
on:
|
|
||||||
push:
|
|
||||||
branches: [master]
|
|
||||||
|
|
||||||
jobs:
|
|
||||||
build:
|
|
||||||
runs-on: ubuntu-latest
|
|
||||||
|
|
||||||
steps:
|
|
||||||
- uses: actions/checkout@v2
|
|
||||||
|
|
||||||
- name: Install Rust
|
|
||||||
uses: actions-rs/toolchain@v1
|
|
||||||
with:
|
|
||||||
toolchain: nightly-x86_64-unknown-linux-gnu
|
|
||||||
profile: minimal
|
|
||||||
override: true
|
|
||||||
|
|
||||||
- name: Build Docs
|
|
||||||
uses: actions-rs/cargo@v1
|
|
||||||
with:
|
|
||||||
command: doc
|
|
||||||
args: --workspace --all-features --no-deps
|
|
||||||
|
|
||||||
- name: Tweak HTML
|
|
||||||
run: echo '<meta http-equiv="refresh" content="0;url=actix_cors/index.html">' > target/doc/index.html
|
|
||||||
|
|
||||||
- name: Deploy to GitHub Pages
|
|
||||||
uses: JamesIves/github-pages-deploy-action@3.7.1
|
|
||||||
with:
|
|
||||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
|
||||||
BRANCH: gh-pages
|
|
||||||
FOLDER: target/doc
|
|
3
.gitignore
vendored
3
.gitignore
vendored
@ -1,6 +1,5 @@
|
|||||||
/target
|
/target
|
||||||
**/*.rs.bk
|
**/*.rs.bk
|
||||||
Cargo.lock
|
|
||||||
|
|
||||||
guide/build/
|
guide/build/
|
||||||
/gh-pages
|
/gh-pages
|
||||||
@ -12,3 +11,5 @@ guide/build/
|
|||||||
*.sock
|
*.sock
|
||||||
*~
|
*~
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|
||||||
|
Server.toml
|
||||||
|
5
.prettierrc.yml
Normal file
5
.prettierrc.yml
Normal file
@ -0,0 +1,5 @@
|
|||||||
|
overrides:
|
||||||
|
- files: "*.md"
|
||||||
|
options:
|
||||||
|
proseWrap: never
|
||||||
|
printWidth: 9999
|
3292
Cargo.lock
generated
Normal file
3292
Cargo.lock
generated
Normal file
File diff suppressed because it is too large
Load Diff
18
Cargo.toml
18
Cargo.toml
@ -5,21 +5,31 @@ members = [
|
|||||||
"actix-identity",
|
"actix-identity",
|
||||||
"actix-limitation",
|
"actix-limitation",
|
||||||
"actix-protobuf",
|
"actix-protobuf",
|
||||||
"actix-redis",
|
|
||||||
"actix-session",
|
"actix-session",
|
||||||
|
"actix-settings",
|
||||||
"actix-web-httpauth",
|
"actix-web-httpauth",
|
||||||
|
"actix-ws",
|
||||||
]
|
]
|
||||||
|
|
||||||
# TODO: move this example to examples repo
|
[workspace.package]
|
||||||
# "actix-protobuf/examples/prost-example",
|
repository = "https://github.com/actix/actix-extras"
|
||||||
|
homepage = "https://actix.rs"
|
||||||
|
license = "MIT OR Apache-2.0"
|
||||||
|
edition = "2021"
|
||||||
|
rust-version = "1.75"
|
||||||
|
|
||||||
|
[workspace.lints.rust]
|
||||||
|
rust-2018-idioms = { level = "deny" }
|
||||||
|
nonstandard-style = { level = "deny" }
|
||||||
|
future-incompatible = { level = "deny" }
|
||||||
|
|
||||||
[patch.crates-io]
|
[patch.crates-io]
|
||||||
actix-cors = { path = "./actix-cors" }
|
actix-cors = { path = "./actix-cors" }
|
||||||
actix-identity = { path = "./actix-identity" }
|
actix-identity = { path = "./actix-identity" }
|
||||||
actix-limitation = { path = "./actix-limitation" }
|
actix-limitation = { path = "./actix-limitation" }
|
||||||
actix-protobuf = { path = "./actix-protobuf" }
|
actix-protobuf = { path = "./actix-protobuf" }
|
||||||
actix-redis = { path = "./actix-redis" }
|
|
||||||
actix-session = { path = "./actix-session" }
|
actix-session = { path = "./actix-session" }
|
||||||
|
actix-settings = { path = "./actix-settings" }
|
||||||
actix-web-httpauth = { path = "./actix-web-httpauth" }
|
actix-web-httpauth = { path = "./actix-web-httpauth" }
|
||||||
|
|
||||||
# uncomment to quickly test against local actix-web repo
|
# uncomment to quickly test against local actix-web repo
|
||||||
|
@ -186,8 +186,7 @@
|
|||||||
same "printed page" as the copyright notice for easier
|
same "printed page" as the copyright notice for easier
|
||||||
identification within third-party archives.
|
identification within third-party archives.
|
||||||
|
|
||||||
Copyright 2017-NOW Nikolay Kim
|
Copyright 2017-NOW Actix team
|
||||||
Copyright 2017-NOW svartalf and Actix team
|
|
||||||
|
|
||||||
Licensed under the Apache License, Version 2.0 (the "License");
|
Licensed under the Apache License, Version 2.0 (the "License");
|
||||||
you may not use this file except in compliance with the License.
|
you may not use this file except in compliance with the License.
|
||||||
|
@ -1,5 +1,4 @@
|
|||||||
Copyright (c) 2017 Nikolay Kim
|
Copyright (c) 2023 Actix team
|
||||||
Copyright (c) 2017 svartalf and Actix team
|
|
||||||
|
|
||||||
Permission is hereby granted, free of charge, to any
|
Permission is hereby granted, free of charge, to any
|
||||||
person obtaining a copy of this software and associated
|
person obtaining a copy of this software and associated
|
||||||
|
102
README.md
102
README.md
@ -2,22 +2,27 @@
|
|||||||
|
|
||||||
> A collection of additional crates supporting [Actix Web].
|
> A collection of additional crates supporting [Actix Web].
|
||||||
|
|
||||||
|
<!-- prettier-ignore-start -->
|
||||||
|
|
||||||
[](https://github.com/actix/actix-extras/actions/workflows/ci.yml)
|
[](https://github.com/actix/actix-extras/actions/workflows/ci.yml)
|
||||||
[](https://codecov.io/gh/actix/actix-extras)
|
[](https://codecov.io/gh/actix/actix-extras)
|
||||||
[](https://discord.gg/5Ux4QGChWc)
|
[](https://discord.gg/5Ux4QGChWc)
|
||||||
[](https://deps.rs/repo/github/actix/actix-extras)
|
[](https://deps.rs/repo/github/actix/actix-extras)
|
||||||
|
|
||||||
|
<!-- prettier-ignore-end -->
|
||||||
|
|
||||||
## Crates by @actix
|
## Crates by @actix
|
||||||
|
|
||||||
| Crate | | |
|
| Crate | | |
|
||||||
| -------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
|
| -------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------- |
|
||||||
| [actix-cors] | [](https://crates.io/crates/actix-cors) [](https://deps.rs/crate/actix-cors/0.6.1) | Cross-origin resource sharing (CORS) for actix-web applications. |
|
| [actix-cors] | [](https://crates.io/crates/actix-cors) [](https://deps.rs/crate/actix-cors) | Cross-Origin Resource Sharing (CORS) controls. |
|
||||||
| [actix-identity] | [](https://crates.io/crates/actix-identity) [](https://deps.rs/crate/actix-identity/0.4.0) | Identity service for actix-web framework. |
|
| [actix-identity] | [](https://crates.io/crates/actix-identity) [](https://deps.rs/crate/actix-identity) | Identity management. |
|
||||||
| [actix-limitation] | [](https://crates.io/crates/actix-limitation) [](https://deps.rs/crate/actix-limitation/0.2.0) | Rate-limiting using a fixed window counter for arbitrary keys, backed by Redis. |
|
| [actix-limitation] | [](https://crates.io/crates/actix-limitation) [](https://deps.rs/crate/actix-limitation) | Rate-limiting using a fixed window counter for arbitrary keys, backed by Redis. |
|
||||||
| [actix-protobuf] | [](https://crates.io/crates/actix-protobuf) [](https://deps.rs/crate/actix-protobuf/0.7.0) | Protobuf support for actix-web framework. |
|
| [actix-protobuf] | [](https://crates.io/crates/actix-protobuf) [](https://deps.rs/crate/actix-protobuf) | Protobuf payload extractor. |
|
||||||
| [actix-redis] | [](https://crates.io/crates/actix-redis) [](https://deps.rs/crate/actix-redis/0.11.0) | Redis integration for actix framework. |
|
| [actix-session] | [](https://crates.io/crates/actix-session) [](https://deps.rs/crate/actix-session) | Session management. |
|
||||||
| [actix-session] | [](https://crates.io/crates/actix-session) [](https://deps.rs/crate/actix-session/0.6.0) | Session for actix-web framework. |
|
| [actix-settings] | [](https://crates.io/crates/actix-settings) [](https://deps.rs/crate/actix-settings) | Easily manage Actix Web's settings from a TOML file and environment variables. |
|
||||||
| [actix-web-httpauth] | [](https://crates.io/crates/actix-web-httpauth) [](https://deps.rs/crate/actix-web-httpauth/0.6.0) | HTTP authentication schemes for actix-web. |
|
| [actix-web-httpauth] | [](https://crates.io/crates/actix-web-httpauth) [](https://deps.rs/crate/actix-web-httpauth) | HTTP authentication schemes. |
|
||||||
|
| [actix-ws] | [][actix-ws] [](https://deps.rs/crate/actix-ws) | WebSockets for Actix Web, without actors. |
|
||||||
|
|
||||||
---
|
---
|
||||||
|
|
||||||
@ -26,41 +31,60 @@
|
|||||||
These crates are provided by the community.
|
These crates are provided by the community.
|
||||||
|
|
||||||
| Crate | | |
|
| Crate | | |
|
||||||
| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
|
| -------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
|
||||||
| [actix-form-data] | [](https://crates.io/crates/actix-form-data) [](https://deps.rs/crate/actix-form-data/0.6.2) | Rate-limiting backed by form-data. |
|
| [actix-web-lab] | [][actix-web-lab] [](https://deps.rs/crate/actix-web-lab) | Experimental extractors, middleware, and other extras for possible inclusion in Actix Web. |
|
||||||
| [actix-governor] | [](https://crates.io/crates/actix-governor) [](https://deps.rs/crate/actix-governor/0.3.0) | Rate-limiting backed by governor. |
|
| [actix-form-data] | [][actix-form-data] [](https://deps.rs/crate/actix-form-data) | Multipart form data from actix multipart streams. |
|
||||||
| [actix-casbin] | [](https://crates.io/crates/actix-casbin) [](https://deps.rs/crate/actix-casbin/0.4.2) | Authorization library that supports access control models like ACL, RBAC & ABAC. |
|
| [actix-governor] | [][actix-governor] [](https://deps.rs/crate/actix-governor) | Rate-limiting backed by governor. |
|
||||||
| [actix-ip-filter] | [](https://crates.io/crates/actix-ip-filter) [](https://deps.rs/crate/actix-ip-filter/0.3.1) | IP address filter. Supports glob patterns. |
|
| [actix-casbin] | [][actix-casbin] [](https://deps.rs/crate/actix-casbin) | Authorization library that supports access control models like ACL, RBAC & ABAC. |
|
||||||
| [actix-web-static-files] | [](https://crates.io/crates/actix-web-static-files) [](https://deps.rs/crate/actix-web-static-files/4.0.0) | Static files as embedded resources. |
|
| [actix-ip-filter] | [][actix-ip-filter] [](https://deps.rs/crate/actix-ip-filter) | IP address filter. Supports glob patterns. |
|
||||||
| [actix-web-grants] | [](https://crates.io/crates/actix-web-grants) [](https://deps.rs/crate/actix-web-grants/3.0.0-beta.6) | Extension for validating user authorities. |
|
| [actix-web-static-files] | [][actix-web-static-files] [](https://deps.rs/crate/actix-web-static-files) | Static files as embedded resources. |
|
||||||
| [aliri_actix] | [](https://crates.io/crates/aliri_actix) [](https://deps.rs/crate/aliri_actix/0.6.0) | Endpoint authorization and authentication using scoped OAuth2 JWT tokens. |
|
| [actix-web-grants] | [][actix-web-grants] [](https://deps.rs/crate/actix-web-grants) | Extension for validating user authorities. |
|
||||||
| [actix-web-flash-messages] | [](https://crates.io/crates/actix-web-flash-messages) [](https://deps.rs/crate/actix-web-flash-messages/0.3.2) | Support for flash messages/one-time notifications in `actix-web`. |
|
| [aliri_actix] | [][aliri_actix] [](https://deps.rs/crate/aliri_actix) | Endpoint authorization and authentication using scoped OAuth2 JWT tokens. |
|
||||||
| [awmp] | [](https://crates.io/crates/awmp) [](https://deps.rs/crate/awmp/0.8.1) | An easy to use wrapper around multipart fields for Actix Web. |
|
| [actix-web-flash-messages] | [][actix-web-flash-messages] [](https://deps.rs/crate/actix-web-flash-messages) | Support for flash messages/one-time notifications in `actix-web`. |
|
||||||
| [tracing-actix-web] | [](https://crates.io/crates/tracing-actix-web) [](https://deps.rs/crate/tracing-actix-web/0.5.1) | A middleware to collect telemetry data from applications built on top of the actix-web framework. |
|
| [awmp] | [][awmp] [](https://deps.rs/crate/awmp) | An easy to use wrapper around multipart fields for Actix Web. |
|
||||||
| [actix-ws] | [](https://crates.io/crates/actix-ws) [](https://deps.rs/crate/actix-ws/0.2.5) | A middleware to collect telemetry data from applications built on top of the actix-web framework. |
|
| [tracing-actix-web] | [][tracing-actix-web] [](https://deps.rs/crate/tracing-actix-web) | A middleware to collect telemetry data from applications built on top of the Actix Web framework. |
|
||||||
|
| [actix-hash] | [][actix-hash] [](https://deps.rs/crate/actix-hash) | Hashing utilities for Actix Web. |
|
||||||
|
| [actix-bincode] |  [](https://deps.rs/crate/actix-bincode) | Bincode payload extractor for Actix Web. |
|
||||||
|
| [sentinel-actix] |  [](https://deps.rs/crate/sentinel-actix) | General and flexible protection for Actix Web. |
|
||||||
|
| [actix-telepathy] |  [](https://deps.rs/crate/actix-telepathy) | Build distributed applications with `RemoteActors` and `RemoteMessages`. |
|
||||||
|
| [apistos] |  [](https://deps.rs/crate/apistos) | Automatic OpenAPI v3 documentation for Actix Web. |
|
||||||
|
| [actix-web-validation] |  [](https://deps.rs/crate/actix-web-validation) | Request validation for Actix Web. |
|
||||||
|
| [actix-jwt-cookies] |  [](https://deps.rs/repo/github/Necoo33/actix-jwt-cookies?path=%2F) | Store your data in encrypted cookies and get it elegantly. |
|
||||||
|
| [actix-ws-broadcaster] |  [](https://deps.rs/repo/github/Necoo33/actix-ws-broadcaster?path=%2F) | A broadcaster library for actix-ws that includes grouping and conditional broadcasting. |
|
||||||
|
|
||||||
To add a crate to this list, submit a pull request.
|
To add a crate to this list, submit a pull request.
|
||||||
|
|
||||||
<!-- REFERENCES -->
|
<!-- REFERENCES -->
|
||||||
|
|
||||||
[actix]: https://github.com/actix/actix
|
[actix]: https://github.com/actix/actix
|
||||||
[Actix Web]: https://github.com/actix/actix-web
|
[actix web]: https://github.com/actix/actix-web
|
||||||
[actix-extras]: https://github.com/actix/actix-extras
|
[actix-extras]: https://github.com/actix/actix-extras
|
||||||
[actix-cors]: actix-cors
|
[actix-cors]: ./actix-cors
|
||||||
[actix-identity]: actix-identity
|
[actix-identity]: ./actix-identity
|
||||||
[actix-limitation]: actix-limitation
|
[actix-limitation]: ./actix-limitation
|
||||||
[actix-protobuf]: actix-protobuf
|
[actix-protobuf]: ./actix-protobuf
|
||||||
[actix-redis]: actix-redis
|
[actix-session]: ./actix-session
|
||||||
[actix-session]: actix-session
|
[actix-settings]: ./actix-settings
|
||||||
[actix-web-httpauth]: actix-web-httpauth
|
[actix-web-httpauth]: ./actix-web-httpauth
|
||||||
[actix-form-data]: https://git.asonix.dog/asonix/actix-form-data
|
[actix-web-lab]: https://crates.io/crates/actix-web-lab
|
||||||
[actix-casbin]: https://github.com/casbin-rs/actix-casbin
|
[actix-multipart-extract]: https://crates.io/crates/actix-multipart-extract
|
||||||
[actix-ip-filter]: https://github.com/jhen0409/actix-ip-filter
|
[actix-form-data]: https://crates.io/crates/actix-form-data
|
||||||
[actix-web-static-files]: https://github.com/kilork/actix-web-static-files
|
[actix-casbin]: https://crates.io/crates/actix-casbin
|
||||||
[actix-web-grants]: https://github.com/DDtKey/actix-web-grants
|
[actix-ip-filter]: https://crates.io/crates/actix-ip-filter
|
||||||
[actix-web-flash-messages]: https://github.com/LukeMathWalker/actix-web-flash-messages
|
[actix-web-static-files]: https://crates.io/crates/actix-web-static-files
|
||||||
[actix-governor]: https://github.com/AaronErhardt/actix-governor
|
[actix-web-grants]: https://crates.io/crates/actix-web-grants
|
||||||
[aliri_actix]: https://github.com/neoeinstein/aliri
|
[actix-web-flash-messages]: https://crates.io/crates/actix-web-flash-messages
|
||||||
[awmp]: https://github.com/kardeiz/awmp
|
[actix-governor]: https://crates.io/crates/actix-governor
|
||||||
[tracing-actix-web]: https://github.com/LukeMathWalker/tracing-actix-web
|
[aliri_actix]: https://crates.io/crates/aliri_actix
|
||||||
[actix-ws]: https://git.asonix.dog/asonix/actix-actorless-websockets
|
[awmp]: https://crates.io/crates/awmp
|
||||||
|
[tracing-actix-web]: https://crates.io/crates/tracing-actix-web
|
||||||
|
[actix-ws]: https://crates.io/crates/actix-ws
|
||||||
|
[actix-hash]: https://crates.io/crates/actix-hash
|
||||||
|
[actix-bincode]: https://crates.io/crates/actix-bincode
|
||||||
|
[sentinel-actix]: https://crates.io/crates/sentinel-actix
|
||||||
|
[actix-telepathy]: https://crates.io/crates/actix-telepathy
|
||||||
|
[actix-web-validation]: https://crates.io/crates/actix-web-validation
|
||||||
|
[actix-telepathy]: https://crates.io/crates/actix-telepathy
|
||||||
|
[apistos]: https://crates.io/crates/apistos
|
||||||
|
[actix-jwt-cookies]: https://crates.io/crates/actix-jwt-cookies
|
||||||
|
[actix-ws-broadcaster]: https://crates.io/crates/actix-ws-broadcaster
|
||||||
|
@ -1,57 +1,88 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## Unreleased - 2021-xx-xx
|
## Unreleased
|
||||||
|
|
||||||
|
## 0.7.1
|
||||||
|
|
||||||
## 0.6.1 - 2022-03-07
|
- Implement `PartialEq` for `Cors` allowing for better testing.
|
||||||
- Do not consider requests without a `Access-Control-Request-Method` as preflight. [#226]
|
|
||||||
|
|
||||||
[#226]: https://github.com/actix/actix-extras/pull/226
|
## 0.7.0
|
||||||
|
|
||||||
|
- `Cors` is now marked `#[must_use]`.
|
||||||
|
- Default for `Cors::block_on_origin_mismatch` is now false.
|
||||||
|
- Minimum supported Rust version (MSRV) is now 1.75.
|
||||||
|
|
||||||
|
## 0.6.5
|
||||||
|
|
||||||
|
- Fix `Vary` header when Private Network Access is enabled.
|
||||||
|
- Minimum supported Rust version (MSRV) is now 1.68.
|
||||||
|
|
||||||
|
## 0.6.4
|
||||||
|
|
||||||
|
- Add `Cors::allow_private_network_access()` behind an unstable flag (`draft-private-network-access`).
|
||||||
|
|
||||||
|
## 0.6.3
|
||||||
|
|
||||||
|
- Add `Cors::block_on_origin_mismatch()` option for controlling if requests are pre-emptively rejected.
|
||||||
|
- Minimum supported Rust version (MSRV) is now 1.59 due to transitive `time` dependency.
|
||||||
|
|
||||||
|
## 0.6.2
|
||||||
|
|
||||||
|
- Fix `expose_any_header` to return list of response headers.
|
||||||
|
- Minimum supported Rust version (MSRV) is now 1.57 due to transitive `time` dependency.
|
||||||
|
|
||||||
|
## 0.6.1
|
||||||
|
|
||||||
|
- Do not consider requests without a `Access-Control-Request-Method` as preflight.
|
||||||
|
|
||||||
|
## 0.6.0
|
||||||
|
|
||||||
## 0.6.0 - 2022-02-25
|
|
||||||
- Update `actix-web` dependency to 4.0.
|
- Update `actix-web` dependency to 4.0.
|
||||||
|
|
||||||
## 0.6.0-beta.10 - 2022-02-07
|
<details>
|
||||||
|
<summary>0.6.0 pre-releases</summary>
|
||||||
|
|
||||||
|
## 0.6.0-beta.10
|
||||||
|
|
||||||
- Ensure that preflight responses contain a `Vary` header. [#224]
|
- Ensure that preflight responses contain a `Vary` header. [#224]
|
||||||
|
|
||||||
[#224]: https://github.com/actix/actix-extras/pull/224
|
[#224]: https://github.com/actix/actix-extras/pull/224
|
||||||
|
|
||||||
|
## 0.6.0-beta.9
|
||||||
|
|
||||||
## 0.6.0-beta.9 - 2022-02-07
|
|
||||||
- Relax body type bounds on middleware impl. [#223]
|
- Relax body type bounds on middleware impl. [#223]
|
||||||
- Update `actix-web` dependency to `4.0.0-rc.1`.
|
- Update `actix-web` dependency to `4.0.0-rc.1`.
|
||||||
|
|
||||||
[#223]: https://github.com/actix/actix-extras/pull/223
|
[#223]: https://github.com/actix/actix-extras/pull/223
|
||||||
|
|
||||||
|
## 0.6.0-beta.8
|
||||||
|
|
||||||
## 0.6.0-beta.8 - 2021-12-29
|
|
||||||
- Minimum supported Rust version (MSRV) is now 1.54.
|
- Minimum supported Rust version (MSRV) is now 1.54.
|
||||||
|
|
||||||
|
## 0.6.0-beta.7
|
||||||
|
|
||||||
## 0.6.0-beta.7 - 2021-12-18
|
|
||||||
- Update `actix-web` dependency to `4.0.0-beta.15`. [#216]
|
- Update `actix-web` dependency to `4.0.0-beta.15`. [#216]
|
||||||
|
|
||||||
[#216]: https://github.com/actix/actix-extras/pull/216
|
[#216]: https://github.com/actix/actix-extras/pull/216
|
||||||
|
|
||||||
|
## 0.6.0-beta.6
|
||||||
|
|
||||||
## 0.6.0-beta.6 - 2021-12-13
|
|
||||||
- Fix panic when wrapping routes with dynamic segments in their paths. [#213]
|
- Fix panic when wrapping routes with dynamic segments in their paths. [#213]
|
||||||
|
|
||||||
[#213]: https://github.com/actix/actix-extras/pull/213
|
[#213]: https://github.com/actix/actix-extras/pull/213
|
||||||
|
|
||||||
|
## 0.6.0-beta.5 _(YANKED)_
|
||||||
|
|
||||||
## 0.6.0-beta.5 - 2021-12-12 _(YANKED)_
|
|
||||||
- Update `actix-web` dependency to `4.0.0.beta-14`. [#209]
|
- Update `actix-web` dependency to `4.0.0.beta-14`. [#209]
|
||||||
|
|
||||||
[#209]: https://github.com/actix/actix-extras/pull/209
|
[#209]: https://github.com/actix/actix-extras/pull/209
|
||||||
|
|
||||||
|
## 0.6.0-beta.4
|
||||||
|
|
||||||
## 0.6.0-beta.4 - 2021-11-22
|
|
||||||
- No significant changes since `0.6.0-beta.3`.
|
- No significant changes since `0.6.0-beta.3`.
|
||||||
|
|
||||||
|
## 0.6.0-beta.3
|
||||||
|
|
||||||
## 0.6.0-beta.3 - 2021-10-21
|
|
||||||
- Make `Cors` middleware generic over body type [#195]
|
- Make `Cors` middleware generic over body type [#195]
|
||||||
- Fix `expose_any_header` behavior. [#204]
|
- Fix `expose_any_header` behavior. [#204]
|
||||||
- Update `actix-web` dependency to v4.0.0-beta.10. [#203]
|
- Update `actix-web` dependency to v4.0.0-beta.10. [#203]
|
||||||
@ -61,90 +92,90 @@
|
|||||||
[#203]: https://github.com/actix/actix-extras/pull/203
|
[#203]: https://github.com/actix/actix-extras/pull/203
|
||||||
[#204]: https://github.com/actix/actix-extras/pull/204
|
[#204]: https://github.com/actix/actix-extras/pull/204
|
||||||
|
|
||||||
|
## 0.6.0-beta.2
|
||||||
|
|
||||||
## 0.6.0-beta.2 - 2021-06-27
|
|
||||||
- No notable changes.
|
- No notable changes.
|
||||||
|
|
||||||
|
## 0.6.0-beta.1
|
||||||
|
|
||||||
## 0.6.0-beta.1 - 2021-04-02
|
|
||||||
- Update `actix-web` dependency to 4.0.0 beta.
|
- Update `actix-web` dependency to 4.0.0 beta.
|
||||||
- Minimum supported Rust version (MSRV) is now 1.46.0.
|
- Minimum supported Rust version (MSRV) is now 1.46.0.
|
||||||
|
|
||||||
|
</details>
|
||||||
|
|
||||||
|
## 0.5.4
|
||||||
|
|
||||||
## 0.5.4 - 2020-12-31
|
|
||||||
- Fix `expose_any_header` method, now set the correct field. [#143]
|
- Fix `expose_any_header` method, now set the correct field. [#143]
|
||||||
|
|
||||||
[#143]: https://github.com/actix/actix-extras/pull/143
|
[#143]: https://github.com/actix/actix-extras/pull/143
|
||||||
|
|
||||||
|
## 0.5.3
|
||||||
|
|
||||||
## 0.5.3 - 2020-11-19
|
|
||||||
- Fix version spec for `derive_more` dependency.
|
- Fix version spec for `derive_more` dependency.
|
||||||
|
|
||||||
|
## 0.5.2
|
||||||
|
|
||||||
## 0.5.2 - 2020-11-15
|
|
||||||
- Ensure `tinyvec` is using the correct features.
|
- Ensure `tinyvec` is using the correct features.
|
||||||
- Bump `futures-util` minimum version to `0.3.7` to avoid `RUSTSEC-2020-0059`.
|
- Bump `futures-util` minimum version to `0.3.7` to avoid `RUSTSEC-2020-0059`.
|
||||||
|
|
||||||
|
## 0.5.1
|
||||||
|
|
||||||
## 0.5.1 - 2020-11-05
|
|
||||||
- Fix `allow_any_header` method, now set the correct field. [#121]
|
- Fix `allow_any_header` method, now set the correct field. [#121]
|
||||||
|
|
||||||
[#121]: https://github.com/actix/actix-extras/pull/121
|
[#121]: https://github.com/actix/actix-extras/pull/121
|
||||||
|
|
||||||
|
## 0.5.0
|
||||||
|
|
||||||
## 0.5.0 - 2020-10-19
|
|
||||||
- Disallow `*` in `Cors::allowed_origin`. [#114].
|
- Disallow `*` in `Cors::allowed_origin`. [#114].
|
||||||
- Hide `CorsMiddleware` from docs. [#118].
|
- Hide `CorsMiddleware` from docs. [#118].
|
||||||
- `CorsFactory` is removed. [#119]
|
- `CorsFactory` is removed. [#119]
|
||||||
- The `impl Default` constructor is now overly-restrictive. [#119]
|
- The `impl Default` constructor is now overly-restrictive. [#119]
|
||||||
- Added `Cors::permissive()` constructor that allows anything. [#119]
|
- Added `Cors::permissive()` constructor that allows anything. [#119]
|
||||||
- Adds methods for each property to reset to a permissive state. (`allow_any_origin`,
|
- Adds methods for each property to reset to a permissive state. (`allow_any_origin`, `expose_any_header`, etc.) [#119]
|
||||||
`expose_any_header`, etc.) [#119]
|
|
||||||
- Errors are now propagated with `Transform::InitError` instead of panicking. [#119]
|
- Errors are now propagated with `Transform::InitError` instead of panicking. [#119]
|
||||||
- Fixes bug where allowed origin functions are not called if `allowed_origins` is All. [#119]
|
- Fixes bug where allowed origin functions are not called if `allowed_origins` is All. [#119]
|
||||||
- `AllOrSome` is no longer public. [#119]
|
- `AllOrSome` is no longer public. [#119]
|
||||||
- Functions used for `allowed_origin_fn` now receive the Origin HeaderValue as the
|
- Functions used for `allowed_origin_fn` now receive the Origin HeaderValue as the first parameter. [#120]
|
||||||
first parameter. [#120]
|
|
||||||
|
|
||||||
[#114]: https://github.com/actix/actix-extras/pull/114
|
[#114]: https://github.com/actix/actix-extras/pull/114
|
||||||
[#118]: https://github.com/actix/actix-extras/pull/118
|
[#118]: https://github.com/actix/actix-extras/pull/118
|
||||||
[#119]: https://github.com/actix/actix-extras/pull/119
|
[#119]: https://github.com/actix/actix-extras/pull/119
|
||||||
[#120]: https://github.com/actix/actix-extras/pull/120
|
[#120]: https://github.com/actix/actix-extras/pull/120
|
||||||
|
|
||||||
|
## 0.4.1
|
||||||
|
|
||||||
## 0.4.1 - 2020-10-07
|
|
||||||
- Allow closures to be used with `allowed_origin_fn`. [#110]
|
- Allow closures to be used with `allowed_origin_fn`. [#110]
|
||||||
|
|
||||||
[#110]: https://github.com/actix/actix-extras/pull/110
|
[#110]: https://github.com/actix/actix-extras/pull/110
|
||||||
|
|
||||||
|
## 0.4.0
|
||||||
|
|
||||||
## 0.4.0 - 2020-09-27
|
|
||||||
- Implement `allowed_origin_fn` builder method. [#93]
|
- Implement `allowed_origin_fn` builder method. [#93]
|
||||||
- Use `TryInto` instead of `TryFrom` where applicable. [#106]
|
- Use `TryInto` instead of `TryFrom` where applicable. [#106]
|
||||||
|
|
||||||
[#93]: https://github.com/actix/actix-extras/pull/93
|
[#93]: https://github.com/actix/actix-extras/pull/93
|
||||||
[#106]: https://github.com/actix/actix-extras/pull/106
|
[#106]: https://github.com/actix/actix-extras/pull/106
|
||||||
|
|
||||||
|
## 0.3.0
|
||||||
|
|
||||||
## 0.3.0 - 2020-09-11
|
|
||||||
- Update `actix-web` dependency to 3.0.0.
|
- Update `actix-web` dependency to 3.0.0.
|
||||||
- Minimum supported Rust version (MSRV) is now 1.42.0.
|
- Minimum supported Rust version (MSRV) is now 1.42.0.
|
||||||
- Implement the Debug trait on all public types.
|
- Implement the Debug trait on all public types.
|
||||||
|
|
||||||
|
## 0.3.0-alpha.1
|
||||||
|
|
||||||
## 0.3.0-alpha.1 - 2020-03-11
|
|
||||||
- Minimize `futures-*` dependencies
|
- Minimize `futures-*` dependencies
|
||||||
- Update `actix-web` dependency to 3.0.0-alpha.1
|
- Update `actix-web` dependency to 3.0.0-alpha.1
|
||||||
|
|
||||||
|
|
||||||
## 0.2.0 - 2019-12-20
|
## 0.2.0 - 2019-12-20
|
||||||
|
|
||||||
- Release
|
- Release
|
||||||
|
|
||||||
|
|
||||||
## 0.2.0-alpha.3 - 2019-12-07
|
## 0.2.0-alpha.3 - 2019-12-07
|
||||||
|
|
||||||
- Migrate to actix-web 2.0.0
|
- Migrate to actix-web 2.0.0
|
||||||
- Bump `derive_more` crate version to 0.99.0
|
- Bump `derive_more` crate version to 0.99.0
|
||||||
|
|
||||||
|
|
||||||
## 0.1.0 - 2019-06-15
|
## 0.1.0 - 2019-06-15
|
||||||
|
|
||||||
- Move cors middleware to separate crate
|
- Move cors middleware to separate crate
|
||||||
|
@ -1,32 +1,39 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-cors"
|
name = "actix-cors"
|
||||||
version = "0.6.1"
|
version = "0.7.1"
|
||||||
authors = [
|
authors = [
|
||||||
"Nikolay Kim <fafhrd91@gmail.com>",
|
"Nikolay Kim <fafhrd91@gmail.com>",
|
||||||
"Rob Ede <robjtede@icloud.com>",
|
"Rob Ede <robjtede@icloud.com>",
|
||||||
]
|
]
|
||||||
description = "Cross-Origin Resource Sharing (CORS) controls for Actix Web"
|
description = "Cross-Origin Resource Sharing (CORS) controls for Actix Web"
|
||||||
keywords = ["actix", "cors", "web", "security", "crossorigin"]
|
keywords = ["actix", "cors", "web", "security", "crossorigin"]
|
||||||
homepage = "https://actix.rs"
|
repository.workspace = true
|
||||||
repository = "https://github.com/actix/actix-extras.git"
|
homepage.workspace = true
|
||||||
license = "MIT OR Apache-2.0"
|
license.workspace = true
|
||||||
edition = "2018"
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
|
||||||
[lib]
|
[package.metadata.docs.rs]
|
||||||
name = "actix_cors"
|
rustdoc-args = ["--cfg", "docsrs"]
|
||||||
path = "src/lib.rs"
|
all-features = true
|
||||||
|
|
||||||
|
[features]
|
||||||
|
draft-private-network-access = []
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-utils = "3"
|
actix-utils = "3"
|
||||||
actix-web = { version = "4", default-features = false }
|
actix-web = { version = "4", default-features = false }
|
||||||
|
|
||||||
derive_more = "0.99.5"
|
derive_more = { version = "2", features = ["display", "error"] }
|
||||||
futures-util = { version = "0.3.7", default-features = false }
|
futures-util = { version = "0.3.17", default-features = false, features = ["std"] }
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
once_cell = "1"
|
once_cell = "1"
|
||||||
smallvec = "1.6.1"
|
smallvec = "1"
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-web = { version = "4", default_features = false, features = ["macros"] }
|
actix-web = { version = "4", default-features = false, features = ["macros"] }
|
||||||
env_logger = "0.9"
|
env_logger = "0.11"
|
||||||
regex = "1.4"
|
regex = "1.4"
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
|
@ -1,14 +1,72 @@
|
|||||||
# actix-cors
|
# actix-cors
|
||||||
|
|
||||||
> Cross-origin resource sharing (CORS) for Actix Web.
|
<!-- prettier-ignore-start -->
|
||||||
|
|
||||||
[](https://crates.io/crates/actix-cors)
|
[](https://crates.io/crates/actix-cors)
|
||||||
[](https://docs.rs/actix-cors/0.6.1)
|
[](https://docs.rs/actix-cors/0.7.1)
|
||||||

|

|
||||||
[](https://deps.rs/crate/actix-cors/0.6.1)
|

|
||||||
|
<br />
|
||||||
|
[](https://deps.rs/crate/actix-cors/0.7.1)
|
||||||
|
[](https://crates.io/crates/actix-cors)
|
||||||
|
[](https://discord.gg/NWpN5mmg3x)
|
||||||
|
|
||||||
|
<!-- prettier-ignore-end -->
|
||||||
|
|
||||||
|
<!-- cargo-rdme start -->
|
||||||
|
|
||||||
|
Cross-Origin Resource Sharing (CORS) controls for Actix Web.
|
||||||
|
|
||||||
|
This middleware can be applied to both applications and resources. Once built, a [`Cors`] builder can be used as an argument for Actix Web's `App::wrap()`, `Scope::wrap()`, or `Resource::wrap()` methods.
|
||||||
|
|
||||||
|
This CORS middleware automatically handles `OPTIONS` preflight requests.
|
||||||
|
|
||||||
|
## Crate Features
|
||||||
|
|
||||||
|
- `draft-private-network-access`: ⚠️ Unstable. Adds opt-in support for the [Private Network Access] spec extensions. This feature is unstable since it will follow breaking changes in the draft spec until it is finalized.
|
||||||
|
|
||||||
|
## Example
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use actix_cors::Cors;
|
||||||
|
use actix_web::{get, http, web, App, HttpRequest, HttpResponse, HttpServer};
|
||||||
|
|
||||||
|
#[get("/index.html")]
|
||||||
|
async fn index(req: HttpRequest) -> &'static str {
|
||||||
|
"<p>Hello World!</p>"
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_web::main]
|
||||||
|
async fn main() -> std::io::Result<()> {
|
||||||
|
HttpServer::new(|| {
|
||||||
|
let cors = Cors::default()
|
||||||
|
.allowed_origin("https://www.rust-lang.org")
|
||||||
|
.allowed_origin_fn(|origin, _req_head| {
|
||||||
|
origin.as_bytes().ends_with(b".rust-lang.org")
|
||||||
|
})
|
||||||
|
.allowed_methods(vec!["GET", "POST"])
|
||||||
|
.allowed_headers(vec![http::header::AUTHORIZATION, http::header::ACCEPT])
|
||||||
|
.allowed_header(http::header::CONTENT_TYPE)
|
||||||
|
.max_age(3600);
|
||||||
|
|
||||||
|
App::new()
|
||||||
|
.wrap(cors)
|
||||||
|
.service(index)
|
||||||
|
})
|
||||||
|
.bind(("127.0.0.1", 8080))?
|
||||||
|
.run()
|
||||||
|
.await;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
[Private Network Access]: https://wicg.github.io/private-network-access
|
||||||
|
|
||||||
|
<!-- cargo-rdme end -->
|
||||||
|
|
||||||
## Documentation & Resources
|
## Documentation & Resources
|
||||||
|
|
||||||
- [API Documentation](https://docs.rs/actix-cors)
|
- [API Documentation](https://docs.rs/actix-cors)
|
||||||
- [Example Project](https://github.com/actix/examples/tree/master/cors)
|
- [Example Project](https://github.com/actix/examples/tree/master/cors)
|
||||||
- Minimum Supported Rust Version (MSRV): 1.54
|
- Minimum Supported Rust Version (MSRV): 1.75
|
||||||
|
@ -39,6 +39,8 @@ async fn main() -> std::io::Result<()> {
|
|||||||
.allowed_header(header::CONTENT_TYPE)
|
.allowed_header(header::CONTENT_TYPE)
|
||||||
// set list of headers that are safe to expose
|
// set list of headers that are safe to expose
|
||||||
.expose_headers(&[header::CONTENT_DISPOSITION])
|
.expose_headers(&[header::CONTENT_DISPOSITION])
|
||||||
|
// allow cURL/HTTPie from working without providing Origin headers
|
||||||
|
.block_on_origin_mismatch(false)
|
||||||
// set preflight cache TTL
|
// set preflight cache TTL
|
||||||
.max_age(3600),
|
.max_age(3600),
|
||||||
)
|
)
|
||||||
|
@ -1,5 +1,5 @@
|
|||||||
/// An enum signifying that some of type `T` is allowed, or `All` (anything is allowed).
|
/// An enum signifying that some of type `T` is allowed, or `All` (anything is allowed).
|
||||||
#[derive(Clone, Debug, PartialEq, Eq)]
|
#[derive(Debug, Clone, PartialEq, Eq)]
|
||||||
pub enum AllOrSome<T> {
|
pub enum AllOrSome<T> {
|
||||||
/// Everything is allowed. Usually equivalent to the `*` value.
|
/// Everything is allowed. Usually equivalent to the `*` value.
|
||||||
All,
|
All,
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
use std::{collections::HashSet, convert::TryInto, iter::FromIterator, rc::Rc};
|
use std::{collections::HashSet, rc::Rc};
|
||||||
|
|
||||||
use actix_utils::future::{self, Ready};
|
use actix_utils::future::{self, Ready};
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
@ -52,13 +52,20 @@ static ALL_METHODS_SET: Lazy<HashSet<Method>> = Lazy::new(|| {
|
|||||||
/// The alternative [`Cors::permissive()`] constructor is available for local development, allowing
|
/// The alternative [`Cors::permissive()`] constructor is available for local development, allowing
|
||||||
/// all origins and headers, etc. **The permissive constructor should not be used in production.**
|
/// all origins and headers, etc. **The permissive constructor should not be used in production.**
|
||||||
///
|
///
|
||||||
|
/// # Behavior
|
||||||
|
///
|
||||||
|
/// In all cases, behavior for this crate follows the [Fetch Standard CORS protocol]. See that
|
||||||
|
/// document for information on exact semantics for configuration options and combinations.
|
||||||
|
///
|
||||||
/// # Errors
|
/// # Errors
|
||||||
|
///
|
||||||
/// Errors surface in the middleware initialization phase. This means that, if you have logs enabled
|
/// Errors surface in the middleware initialization phase. This means that, if you have logs enabled
|
||||||
/// in Actix Web (using `env_logger` or other crate that exposes logs from the `log` crate), error
|
/// in Actix Web (using `env_logger` or other crate that exposes logs from the `log` crate), error
|
||||||
/// messages will outline what is wrong with the CORS configuration in the server logs and the
|
/// messages will outline what is wrong with the CORS configuration in the server logs and the
|
||||||
/// server will fail to start up or serve requests.
|
/// server will fail to start up or serve requests.
|
||||||
///
|
///
|
||||||
/// # Example
|
/// # Example
|
||||||
|
///
|
||||||
/// ```
|
/// ```
|
||||||
/// use actix_cors::Cors;
|
/// use actix_cors::Cors;
|
||||||
/// use actix_web::http::header;
|
/// use actix_web::http::header;
|
||||||
@ -72,14 +79,18 @@ static ALL_METHODS_SET: Lazy<HashSet<Method>> = Lazy::new(|| {
|
|||||||
///
|
///
|
||||||
/// // `cors` can now be used in `App::wrap`.
|
/// // `cors` can now be used in `App::wrap`.
|
||||||
/// ```
|
/// ```
|
||||||
|
///
|
||||||
|
/// [Fetch Standard CORS protocol]: https://fetch.spec.whatwg.org/#http-cors-protocol
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
|
#[must_use]
|
||||||
pub struct Cors {
|
pub struct Cors {
|
||||||
inner: Rc<Inner>,
|
inner: Rc<Inner>,
|
||||||
error: Option<Either<HttpError, CorsError>>,
|
error: Option<Either<HttpError, CorsError>>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Cors {
|
impl Cors {
|
||||||
/// A very permissive set of default for quick development. Not recommended for production use.
|
/// Constructs a very permissive set of defaults for quick development. (Not recommended for
|
||||||
|
/// production use.)
|
||||||
///
|
///
|
||||||
/// *All* origins, methods, request headers and exposed headers allowed. Credentials supported.
|
/// *All* origins, methods, request headers and exposed headers allowed. Credentials supported.
|
||||||
/// Max age 1 hour. Does not send wildcard.
|
/// Max age 1 hour. Does not send wildcard.
|
||||||
@ -101,7 +112,10 @@ impl Cors {
|
|||||||
preflight: true,
|
preflight: true,
|
||||||
send_wildcard: false,
|
send_wildcard: false,
|
||||||
supports_credentials: true,
|
supports_credentials: true,
|
||||||
|
#[cfg(feature = "draft-private-network-access")]
|
||||||
|
allow_private_network_access: false,
|
||||||
vary_header: true,
|
vary_header: true,
|
||||||
|
block_on_origin_mismatch: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
Cors {
|
Cors {
|
||||||
@ -121,12 +135,12 @@ impl Cors {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Add an origin that is allowed to make requests.
|
/// Adds an origin that is allowed to make requests.
|
||||||
///
|
///
|
||||||
/// By default, requests from all origins are accepted by CORS logic. This method allows to
|
/// This method allows specifying a finite set of origins to verify the value of the `Origin`
|
||||||
/// specify a finite set of origins to verify the value of the `Origin` request header.
|
/// request header. These are `origin-or-null` types in the [Fetch Standard].
|
||||||
///
|
///
|
||||||
/// These are `origin-or-null` types in the [Fetch Standard].
|
/// By default, no origins are accepted.
|
||||||
///
|
///
|
||||||
/// When this list is set, the client's `Origin` request header will be checked in a
|
/// When this list is set, the client's `Origin` request header will be checked in a
|
||||||
/// case-sensitive manner.
|
/// case-sensitive manner.
|
||||||
@ -174,7 +188,7 @@ impl Cors {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Determinate allowed origins by processing requests which didn't match any origins specified
|
/// Determinates allowed origins by processing requests which didn't match any origins specified
|
||||||
/// in the `allowed_origin`.
|
/// in the `allowed_origin`.
|
||||||
///
|
///
|
||||||
/// The function will receive two parameters, the Origin header value, and the `RequestHead` of
|
/// The function will receive two parameters, the Origin header value, and the `RequestHead` of
|
||||||
@ -200,20 +214,17 @@ impl Cors {
|
|||||||
/// See [`Cors::allowed_methods`] for more info on allowed methods.
|
/// See [`Cors::allowed_methods`] for more info on allowed methods.
|
||||||
pub fn allow_any_method(mut self) -> Cors {
|
pub fn allow_any_method(mut self) -> Cors {
|
||||||
if let Some(cors) = cors(&mut self.inner, &self.error) {
|
if let Some(cors) = cors(&mut self.inner, &self.error) {
|
||||||
cors.allowed_methods = ALL_METHODS_SET.clone();
|
ALL_METHODS_SET.clone_into(&mut cors.allowed_methods);
|
||||||
}
|
}
|
||||||
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set a list of methods which allowed origins can perform.
|
/// Sets a list of methods which allowed origins can perform.
|
||||||
///
|
///
|
||||||
/// These will be sent in the `Access-Control-Allow-Methods` response header as specified in
|
/// These will be sent in the `Access-Control-Allow-Methods` response header.
|
||||||
/// the [Fetch Standard CORS protocol].
|
|
||||||
///
|
///
|
||||||
/// Defaults to `[GET, HEAD, POST, OPTIONS, PUT, PATCH, DELETE]`
|
/// This defaults to an empty set.
|
||||||
///
|
|
||||||
/// [Fetch Standard CORS protocol]: https://fetch.spec.whatwg.org/#http-cors-protocol
|
|
||||||
pub fn allowed_methods<U, M>(mut self, methods: U) -> Cors
|
pub fn allowed_methods<U, M>(mut self, methods: U) -> Cors
|
||||||
where
|
where
|
||||||
U: IntoIterator<Item = M>,
|
U: IntoIterator<Item = M>,
|
||||||
@ -276,16 +287,13 @@ impl Cors {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set a list of request header field names which can be used when this resource is accessed by
|
/// Sets a list of request header field names which can be used when this resource is accessed
|
||||||
/// allowed origins.
|
/// by allowed origins.
|
||||||
///
|
///
|
||||||
/// If `All` is set, whatever is requested by the client in `Access-Control-Request-Headers`
|
/// If `All` is set, whatever is requested by the client in `Access-Control-Request-Headers`
|
||||||
/// will be echoed back in the `Access-Control-Allow-Headers` header as specified in
|
/// will be echoed back in the `Access-Control-Allow-Headers` header.
|
||||||
/// the [Fetch Standard CORS protocol].
|
|
||||||
///
|
///
|
||||||
/// Defaults to `All`.
|
/// This defaults to an empty set.
|
||||||
///
|
|
||||||
/// [Fetch Standard CORS protocol]: https://fetch.spec.whatwg.org/#http-cors-protocol
|
|
||||||
pub fn allowed_headers<U, H>(mut self, headers: U) -> Cors
|
pub fn allowed_headers<U, H>(mut self, headers: U) -> Cors
|
||||||
where
|
where
|
||||||
U: IntoIterator<Item = H>,
|
U: IntoIterator<Item = H>,
|
||||||
@ -315,7 +323,7 @@ impl Cors {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Resets exposed response header list to a state where any header is accepted.
|
/// Resets exposed response header list to a state where all headers are exposed.
|
||||||
///
|
///
|
||||||
/// See [`Cors::expose_headers`] for more info on exposed response headers.
|
/// See [`Cors::expose_headers`] for more info on exposed response headers.
|
||||||
pub fn expose_any_header(mut self) -> Cors {
|
pub fn expose_any_header(mut self) -> Cors {
|
||||||
@ -326,13 +334,11 @@ impl Cors {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set a list of headers which are safe to expose to the API of a CORS API specification.
|
/// Sets a list of headers which are safe to expose to the API of a CORS API specification.
|
||||||
/// This corresponds to the `Access-Control-Expose-Headers` response header as specified in
|
///
|
||||||
/// the [Fetch Standard CORS protocol].
|
/// This corresponds to the `Access-Control-Expose-Headers` response header.
|
||||||
///
|
///
|
||||||
/// This defaults to an empty set.
|
/// This defaults to an empty set.
|
||||||
///
|
|
||||||
/// [Fetch Standard CORS protocol]: https://fetch.spec.whatwg.org/#http-cors-protocol
|
|
||||||
pub fn expose_headers<U, H>(mut self, headers: U) -> Cors
|
pub fn expose_headers<U, H>(mut self, headers: U) -> Cors
|
||||||
where
|
where
|
||||||
U: IntoIterator<Item = H>,
|
U: IntoIterator<Item = H>,
|
||||||
@ -361,63 +367,76 @@ impl Cors {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set a maximum time (in seconds) for which this CORS request may be cached. This value is set
|
/// Sets a maximum time (in seconds) for which this CORS request may be cached.
|
||||||
/// as the `Access-Control-Max-Age` header as specified in the [Fetch Standard CORS protocol].
|
///
|
||||||
|
/// This value is set as the `Access-Control-Max-Age` header.
|
||||||
///
|
///
|
||||||
/// Pass a number (of seconds) or use None to disable sending max age header.
|
/// Pass a number (of seconds) or use None to disable sending max age header.
|
||||||
///
|
|
||||||
/// [Fetch Standard CORS protocol]: https://fetch.spec.whatwg.org/#http-cors-protocol
|
|
||||||
pub fn max_age(mut self, max_age: impl Into<Option<usize>>) -> Cors {
|
pub fn max_age(mut self, max_age: impl Into<Option<usize>>) -> Cors {
|
||||||
if let Some(cors) = cors(&mut self.inner, &self.error) {
|
if let Some(cors) = cors(&mut self.inner, &self.error) {
|
||||||
cors.max_age = max_age.into()
|
cors.max_age = max_age.into();
|
||||||
}
|
}
|
||||||
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set to use wildcard origins.
|
/// Configures use of wildcard (`*`) origin in responses when appropriate.
|
||||||
///
|
///
|
||||||
/// If send wildcard is set and the `allowed_origins` parameter is `All`, a wildcard
|
/// If send wildcard is set and the `allowed_origins` parameter is `All`, a wildcard
|
||||||
/// `Access-Control-Allow-Origin` response header is sent, rather than the request’s
|
/// `Access-Control-Allow-Origin` response header is sent, rather than the request’s
|
||||||
/// `Origin` header.
|
/// `Origin` header.
|
||||||
///
|
///
|
||||||
/// This **CANNOT** be used in conjunction with `allowed_origins` set to `All` and
|
/// This option **CANNOT** be used in conjunction with a [credential
|
||||||
/// `allow_credentials` set to `true`. Depending on the mode of usage, this will either result
|
/// supported](Self::supports_credentials()) configuration. Doing so will result in an error
|
||||||
/// in an `CorsError::CredentialsWithWildcardOrigin` error during actix launch or runtime.
|
/// during server startup.
|
||||||
///
|
///
|
||||||
/// Defaults to `false`.
|
/// Defaults to disabled.
|
||||||
pub fn send_wildcard(mut self) -> Cors {
|
pub fn send_wildcard(mut self) -> Cors {
|
||||||
if let Some(cors) = cors(&mut self.inner, &self.error) {
|
if let Some(cors) = cors(&mut self.inner, &self.error) {
|
||||||
cors.send_wildcard = true
|
cors.send_wildcard = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Allows users to make authenticated requests
|
/// Allows users to make authenticated requests.
|
||||||
///
|
///
|
||||||
/// If true, injects the `Access-Control-Allow-Credentials` header in responses. This allows
|
/// If true, injects the `Access-Control-Allow-Credentials` header in responses. This allows
|
||||||
/// cookies and credentials to be submitted across domains as specified in
|
/// cookies and credentials to be submitted across domains.
|
||||||
/// the [Fetch Standard CORS protocol].
|
|
||||||
///
|
///
|
||||||
/// This option cannot be used in conjunction with an `allowed_origin` set to `All` and
|
/// This option **CANNOT** be used in conjunction with option cannot be used in conjunction
|
||||||
/// `send_wildcards` set to `true`.
|
/// with [wildcard origins](Self::send_wildcard()) configured. Doing so will result in an error
|
||||||
|
/// during server startup.
|
||||||
|
///
|
||||||
|
/// Defaults to disabled.
|
||||||
|
pub fn supports_credentials(mut self) -> Cors {
|
||||||
|
if let Some(cors) = cors(&mut self.inner, &self.error) {
|
||||||
|
cors.supports_credentials = true;
|
||||||
|
}
|
||||||
|
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Allow private network access.
|
||||||
|
///
|
||||||
|
/// If true, injects the `Access-Control-Allow-Private-Network: true` header in responses if the
|
||||||
|
/// request contained the `Access-Control-Request-Private-Network: true` header.
|
||||||
|
///
|
||||||
|
/// For more information on this behavior, see the draft [Private Network Access] spec.
|
||||||
///
|
///
|
||||||
/// Defaults to `false`.
|
/// Defaults to `false`.
|
||||||
///
|
///
|
||||||
/// A server initialization error will occur if credentials are allowed, but the Origin is set
|
/// [Private Network Access]: https://wicg.github.io/private-network-access
|
||||||
/// to send wildcards (`*`); this is not allowed by the CORS protocol.
|
#[cfg(feature = "draft-private-network-access")]
|
||||||
///
|
pub fn allow_private_network_access(mut self) -> Cors {
|
||||||
/// [Fetch Standard CORS protocol]: https://fetch.spec.whatwg.org/#http-cors-protocol
|
|
||||||
pub fn supports_credentials(mut self) -> Cors {
|
|
||||||
if let Some(cors) = cors(&mut self.inner, &self.error) {
|
if let Some(cors) = cors(&mut self.inner, &self.error) {
|
||||||
cors.supports_credentials = true
|
cors.allow_private_network_access = true;
|
||||||
}
|
}
|
||||||
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Disable `Vary` header support.
|
/// Disables `Vary` header support.
|
||||||
///
|
///
|
||||||
/// When enabled the header `Vary: Origin` will be returned as per the Fetch Standard
|
/// When enabled the header `Vary: Origin` will be returned as per the Fetch Standard
|
||||||
/// implementation guidelines.
|
/// implementation guidelines.
|
||||||
@ -429,21 +448,39 @@ impl Cors {
|
|||||||
/// By default, `Vary` header support is enabled.
|
/// By default, `Vary` header support is enabled.
|
||||||
pub fn disable_vary_header(mut self) -> Cors {
|
pub fn disable_vary_header(mut self) -> Cors {
|
||||||
if let Some(cors) = cors(&mut self.inner, &self.error) {
|
if let Some(cors) = cors(&mut self.inner, &self.error) {
|
||||||
cors.vary_header = false
|
cors.vary_header = false;
|
||||||
}
|
}
|
||||||
|
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Disable support for preflight requests.
|
/// Disables preflight request handling.
|
||||||
///
|
///
|
||||||
/// When enabled CORS middleware automatically handles `OPTIONS` requests.
|
/// When enabled CORS middleware automatically handles `OPTIONS` requests. This is useful for
|
||||||
/// This is useful for application level middleware.
|
/// application level middleware.
|
||||||
///
|
///
|
||||||
/// By default *preflight* support is enabled.
|
/// By default, preflight support is enabled.
|
||||||
pub fn disable_preflight(mut self) -> Cors {
|
pub fn disable_preflight(mut self) -> Cors {
|
||||||
if let Some(cors) = cors(&mut self.inner, &self.error) {
|
if let Some(cors) = cors(&mut self.inner, &self.error) {
|
||||||
cors.preflight = false
|
cors.preflight = false;
|
||||||
|
}
|
||||||
|
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Configures whether requests should be pre-emptively blocked on mismatched origin.
|
||||||
|
///
|
||||||
|
/// If `true`, a 400 Bad Request is returned immediately when a request fails origin validation.
|
||||||
|
///
|
||||||
|
/// If `false`, the request will be processed as normal but relevant CORS headers will not be
|
||||||
|
/// appended to the response. In this case, the browser is trusted to validate CORS headers and
|
||||||
|
/// and block requests based on pre-flight requests. Use this setting to allow cURL and other
|
||||||
|
/// non-browser HTTP clients to function as normal, no matter what `Origin` the request has.
|
||||||
|
///
|
||||||
|
/// Defaults to false.
|
||||||
|
pub fn block_on_origin_mismatch(mut self, block: bool) -> Cors {
|
||||||
|
if let Some(cors) = cors(&mut self.inner, &self.error) {
|
||||||
|
cors.block_on_origin_mismatch = block;
|
||||||
}
|
}
|
||||||
|
|
||||||
self
|
self
|
||||||
@ -473,7 +510,10 @@ impl Default for Cors {
|
|||||||
preflight: true,
|
preflight: true,
|
||||||
send_wildcard: false,
|
send_wildcard: false,
|
||||||
supports_credentials: false,
|
supports_credentials: false,
|
||||||
|
#[cfg(feature = "draft-private-network-access")]
|
||||||
|
allow_private_network_access: false,
|
||||||
vary_header: true,
|
vary_header: true,
|
||||||
|
block_on_origin_mismatch: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
Cors {
|
Cors {
|
||||||
@ -568,14 +608,27 @@ where
|
|||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl PartialEq for Cors {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
self.inner == other.inner
|
||||||
|
// Because of the cors-function, checking if the content is equal implies that the errors are equal
|
||||||
|
//
|
||||||
|
// Proof by contradiction:
|
||||||
|
// Lets assume that the inner values are equal, but the error values are not.
|
||||||
|
// This means there had been an error, which has been fixed.
|
||||||
|
// This cannot happen as the first call to set the invalid value means that further usages of the cors-function will reject other input.
|
||||||
|
// => inner has to be in a different state
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod test {
|
||||||
use std::convert::{Infallible, TryInto};
|
use std::convert::Infallible;
|
||||||
|
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
body,
|
body,
|
||||||
dev::{fn_service, Transform},
|
dev::fn_service,
|
||||||
http::{header::HeaderName, StatusCode},
|
http::StatusCode,
|
||||||
test::{self, TestRequest},
|
test::{self, TestRequest},
|
||||||
HttpResponse,
|
HttpResponse,
|
||||||
};
|
};
|
||||||
@ -606,8 +659,9 @@ mod test {
|
|||||||
.insert_header(("Origin", "https://www.example.com"))
|
.insert_header(("Origin", "https://www.example.com"))
|
||||||
.to_srv_request();
|
.to_srv_request();
|
||||||
|
|
||||||
let resp = test::call_service(&cors, req).await;
|
let res = test::call_service(&cors, req).await;
|
||||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
assert_eq!(res.status(), StatusCode::OK);
|
||||||
|
assert!(!res.headers().contains_key("Access-Control-Allow-Origin"));
|
||||||
}
|
}
|
||||||
|
|
||||||
#[actix_web::test]
|
#[actix_web::test]
|
||||||
@ -638,4 +692,11 @@ mod test {
|
|||||||
|
|
||||||
Cors::default().new_transform(srv).await.unwrap();
|
Cors::default().new_transform(srv).await.unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn impl_eq() {
|
||||||
|
assert_eq!(Cors::default(), Cors::default());
|
||||||
|
assert_ne!(Cors::default().send_wildcard(), Cors::default());
|
||||||
|
assert_ne!(Cors::default(), Cors::permissive());
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,41 +1,40 @@
|
|||||||
use actix_web::{http::StatusCode, HttpResponse, ResponseError};
|
use actix_web::{http::StatusCode, HttpResponse, ResponseError};
|
||||||
|
use derive_more::derive::{Display, Error};
|
||||||
use derive_more::{Display, Error};
|
|
||||||
|
|
||||||
/// Errors that can occur when processing CORS guarded requests.
|
/// Errors that can occur when processing CORS guarded requests.
|
||||||
#[derive(Debug, Clone, Display, Error)]
|
#[derive(Debug, Clone, Display, Error)]
|
||||||
#[non_exhaustive]
|
#[non_exhaustive]
|
||||||
pub enum CorsError {
|
pub enum CorsError {
|
||||||
/// Allowed origin argument must not be wildcard (`*`).
|
/// Allowed origin argument must not be wildcard (`*`).
|
||||||
#[display(fmt = "`allowed_origin` argument must not be wildcard (`*`)")]
|
#[display("`allowed_origin` argument must not be wildcard (`*`)")]
|
||||||
WildcardOrigin,
|
WildcardOrigin,
|
||||||
|
|
||||||
/// Request header `Origin` is required but was not provided.
|
/// Request header `Origin` is required but was not provided.
|
||||||
#[display(fmt = "Request header `Origin` is required but was not provided")]
|
#[display("Request header `Origin` is required but was not provided")]
|
||||||
MissingOrigin,
|
MissingOrigin,
|
||||||
|
|
||||||
/// Request header `Access-Control-Request-Method` is required but is missing.
|
/// Request header `Access-Control-Request-Method` is required but is missing.
|
||||||
#[display(fmt = "Request header `Access-Control-Request-Method` is required but is missing")]
|
#[display("Request header `Access-Control-Request-Method` is required but is missing")]
|
||||||
MissingRequestMethod,
|
MissingRequestMethod,
|
||||||
|
|
||||||
/// Request header `Access-Control-Request-Method` has an invalid value.
|
/// Request header `Access-Control-Request-Method` has an invalid value.
|
||||||
#[display(fmt = "Request header `Access-Control-Request-Method` has an invalid value")]
|
#[display("Request header `Access-Control-Request-Method` has an invalid value")]
|
||||||
BadRequestMethod,
|
BadRequestMethod,
|
||||||
|
|
||||||
/// Request header `Access-Control-Request-Headers` has an invalid value.
|
/// Request header `Access-Control-Request-Headers` has an invalid value.
|
||||||
#[display(fmt = "Request header `Access-Control-Request-Headers` has an invalid value")]
|
#[display("Request header `Access-Control-Request-Headers` has an invalid value")]
|
||||||
BadRequestHeaders,
|
BadRequestHeaders,
|
||||||
|
|
||||||
/// Origin is not allowed to make this request.
|
/// Origin is not allowed to make this request.
|
||||||
#[display(fmt = "Origin is not allowed to make this request")]
|
#[display("Origin is not allowed to make this request")]
|
||||||
OriginNotAllowed,
|
OriginNotAllowed,
|
||||||
|
|
||||||
/// Request method is not allowed.
|
/// Request method is not allowed.
|
||||||
#[display(fmt = "Requested method is not allowed")]
|
#[display("Requested method is not allowed")]
|
||||||
MethodNotAllowed,
|
MethodNotAllowed,
|
||||||
|
|
||||||
/// One or more request headers are not allowed.
|
/// One or more request headers are not allowed.
|
||||||
#[display(fmt = "One or more request headers are not allowed")]
|
#[display("One or more request headers are not allowed")]
|
||||||
HeadersNotAllowed,
|
HeadersNotAllowed,
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
use std::{collections::HashSet, convert::TryFrom, convert::TryInto, fmt, rc::Rc};
|
use std::{collections::HashSet, fmt, rc::Rc};
|
||||||
|
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
dev::RequestHead,
|
dev::RequestHead,
|
||||||
@ -15,6 +15,7 @@ use crate::{AllOrSome, CorsError};
|
|||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub(crate) struct OriginFn {
|
pub(crate) struct OriginFn {
|
||||||
|
#[allow(clippy::type_complexity)]
|
||||||
pub(crate) boxed_fn: Rc<dyn Fn(&HeaderValue, &RequestHead) -> bool>,
|
pub(crate) boxed_fn: Rc<dyn Fn(&HeaderValue, &RequestHead) -> bool>,
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -26,6 +27,12 @@ impl Default for OriginFn {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
impl PartialEq for OriginFn {
|
||||||
|
fn eq(&self, other: &Self) -> bool {
|
||||||
|
Rc::ptr_eq(&self.boxed_fn, &other.boxed_fn)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
impl fmt::Debug for OriginFn {
|
impl fmt::Debug for OriginFn {
|
||||||
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
f.write_str("origin_fn")
|
f.write_str("origin_fn")
|
||||||
@ -39,7 +46,7 @@ pub(crate) fn header_value_try_into_method(hdr: &HeaderValue) -> Option<Method>
|
|||||||
.and_then(|meth| Method::try_from(meth).ok())
|
.and_then(|meth| Method::try_from(meth).ok())
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Clone)]
|
#[derive(Debug, Clone, PartialEq)]
|
||||||
pub(crate) struct Inner {
|
pub(crate) struct Inner {
|
||||||
pub(crate) allowed_origins: AllOrSome<HashSet<HeaderValue>>,
|
pub(crate) allowed_origins: AllOrSome<HashSet<HeaderValue>>,
|
||||||
pub(crate) allowed_origins_fns: SmallVec<[OriginFn; 4]>,
|
pub(crate) allowed_origins_fns: SmallVec<[OriginFn; 4]>,
|
||||||
@ -58,17 +65,22 @@ pub(crate) struct Inner {
|
|||||||
pub(crate) preflight: bool,
|
pub(crate) preflight: bool,
|
||||||
pub(crate) send_wildcard: bool,
|
pub(crate) send_wildcard: bool,
|
||||||
pub(crate) supports_credentials: bool,
|
pub(crate) supports_credentials: bool,
|
||||||
|
#[cfg(feature = "draft-private-network-access")]
|
||||||
|
pub(crate) allow_private_network_access: bool,
|
||||||
pub(crate) vary_header: bool,
|
pub(crate) vary_header: bool,
|
||||||
|
pub(crate) block_on_origin_mismatch: bool,
|
||||||
}
|
}
|
||||||
|
|
||||||
static EMPTY_ORIGIN_SET: Lazy<HashSet<HeaderValue>> = Lazy::new(HashSet::new);
|
static EMPTY_ORIGIN_SET: Lazy<HashSet<HeaderValue>> = Lazy::new(HashSet::new);
|
||||||
|
|
||||||
impl Inner {
|
impl Inner {
|
||||||
pub(crate) fn validate_origin(&self, req: &RequestHead) -> Result<(), CorsError> {
|
/// The bool returned in Ok(_) position indicates whether the `Access-Control-Allow-Origin`
|
||||||
|
/// header should be added to the response or not.
|
||||||
|
pub(crate) fn validate_origin(&self, req: &RequestHead) -> Result<bool, CorsError> {
|
||||||
// return early if all origins are allowed or get ref to allowed origins set
|
// return early if all origins are allowed or get ref to allowed origins set
|
||||||
#[allow(clippy::mutable_key_type)]
|
#[allow(clippy::mutable_key_type)]
|
||||||
let allowed_origins = match &self.allowed_origins {
|
let allowed_origins = match &self.allowed_origins {
|
||||||
AllOrSome::All if self.allowed_origins_fns.is_empty() => return Ok(()),
|
AllOrSome::All if self.allowed_origins_fns.is_empty() => return Ok(true),
|
||||||
AllOrSome::Some(allowed_origins) => allowed_origins,
|
AllOrSome::Some(allowed_origins) => allowed_origins,
|
||||||
// only function origin validators are defined
|
// only function origin validators are defined
|
||||||
_ => &EMPTY_ORIGIN_SET,
|
_ => &EMPTY_ORIGIN_SET,
|
||||||
@ -79,9 +91,11 @@ impl Inner {
|
|||||||
// origin header exists and is a string
|
// origin header exists and is a string
|
||||||
Some(origin) => {
|
Some(origin) => {
|
||||||
if allowed_origins.contains(origin) || self.validate_origin_fns(origin, req) {
|
if allowed_origins.contains(origin) || self.validate_origin_fns(origin, req) {
|
||||||
Ok(())
|
Ok(true)
|
||||||
} else {
|
} else if self.block_on_origin_mismatch {
|
||||||
Err(CorsError::OriginNotAllowed)
|
Err(CorsError::OriginNotAllowed)
|
||||||
|
} else {
|
||||||
|
Ok(false)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -208,8 +222,20 @@ pub(crate) fn add_vary_header(headers: &mut HeaderMap) {
|
|||||||
let mut val: Vec<u8> = Vec::with_capacity(hdr.len() + 71);
|
let mut val: Vec<u8> = Vec::with_capacity(hdr.len() + 71);
|
||||||
val.extend(hdr.as_bytes());
|
val.extend(hdr.as_bytes());
|
||||||
val.extend(b", Origin, Access-Control-Request-Method, Access-Control-Request-Headers");
|
val.extend(b", Origin, Access-Control-Request-Method, Access-Control-Request-Headers");
|
||||||
|
|
||||||
|
#[cfg(feature = "draft-private-network-access")]
|
||||||
|
val.extend(b", Access-Control-Request-Private-Network");
|
||||||
|
|
||||||
val.try_into().unwrap()
|
val.try_into().unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "draft-private-network-access")]
|
||||||
|
None => HeaderValue::from_static(
|
||||||
|
"Origin, Access-Control-Request-Method, Access-Control-Request-Headers, \
|
||||||
|
Access-Control-Request-Private-Network",
|
||||||
|
),
|
||||||
|
|
||||||
|
#[cfg(not(feature = "draft-private-network-access"))]
|
||||||
None => HeaderValue::from_static(
|
None => HeaderValue::from_static(
|
||||||
"Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
|
"Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
|
||||||
),
|
),
|
||||||
@ -241,6 +267,7 @@ mod test {
|
|||||||
async fn test_validate_not_allowed_origin() {
|
async fn test_validate_not_allowed_origin() {
|
||||||
let cors = Cors::default()
|
let cors = Cors::default()
|
||||||
.allowed_origin("https://www.example.com")
|
.allowed_origin("https://www.example.com")
|
||||||
|
.block_on_origin_mismatch(true)
|
||||||
.new_transform(test::ok_service())
|
.new_transform(test::ok_service())
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
@ -1,11 +1,16 @@
|
|||||||
//! Cross-Origin Resource Sharing (CORS) controls for Actix Web.
|
//! Cross-Origin Resource Sharing (CORS) controls for Actix Web.
|
||||||
//!
|
//!
|
||||||
//! This middleware can be applied to both applications and resources. Once built, a
|
//! This middleware can be applied to both applications and resources. Once built, a [`Cors`]
|
||||||
//! [`Cors`] builder can be used as an argument for Actix Web's `App::wrap()`,
|
//! builder can be used as an argument for Actix Web's `App::wrap()`, `Scope::wrap()`, or
|
||||||
//! `Scope::wrap()`, or `Resource::wrap()` methods.
|
//! `Resource::wrap()` methods.
|
||||||
//!
|
//!
|
||||||
//! This CORS middleware automatically handles `OPTIONS` preflight requests.
|
//! This CORS middleware automatically handles `OPTIONS` preflight requests.
|
||||||
//!
|
//!
|
||||||
|
//! # Crate Features
|
||||||
|
//! - `draft-private-network-access`: ⚠️ Unstable. Adds opt-in support for the [Private Network
|
||||||
|
//! Access] spec extensions. This feature is unstable since it will follow breaking changes in the
|
||||||
|
//! draft spec until it is finalized.
|
||||||
|
//!
|
||||||
//! # Example
|
//! # Example
|
||||||
//! ```no_run
|
//! ```no_run
|
||||||
//! use actix_cors::Cors;
|
//! use actix_cors::Cors;
|
||||||
@ -20,7 +25,7 @@
|
|||||||
//! async fn main() -> std::io::Result<()> {
|
//! async fn main() -> std::io::Result<()> {
|
||||||
//! HttpServer::new(|| {
|
//! HttpServer::new(|| {
|
||||||
//! let cors = Cors::default()
|
//! let cors = Cors::default()
|
||||||
//! .allowed_origin("https://www.rust-lang.org/")
|
//! .allowed_origin("https://www.rust-lang.org")
|
||||||
//! .allowed_origin_fn(|origin, _req_head| {
|
//! .allowed_origin_fn(|origin, _req_head| {
|
||||||
//! origin.as_bytes().ends_with(b".rust-lang.org")
|
//! origin.as_bytes().ends_with(b".rust-lang.org")
|
||||||
//! })
|
//! })
|
||||||
@ -40,12 +45,14 @@
|
|||||||
//! Ok(())
|
//! Ok(())
|
||||||
//! }
|
//! }
|
||||||
//! ```
|
//! ```
|
||||||
|
//!
|
||||||
|
//! [Private Network Access]: https://wicg.github.io/private-network-access
|
||||||
|
|
||||||
#![forbid(unsafe_code)]
|
#![forbid(unsafe_code)]
|
||||||
#![deny(rust_2018_idioms, nonstandard_style)]
|
|
||||||
#![warn(future_incompatible, missing_docs, missing_debug_implementations)]
|
#![warn(future_incompatible, missing_docs, missing_debug_implementations)]
|
||||||
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
|
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
|
||||||
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
|
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
|
||||||
|
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||||
|
|
||||||
mod all_or_some;
|
mod all_or_some;
|
||||||
mod builder;
|
mod builder;
|
||||||
@ -53,8 +60,8 @@ mod error;
|
|||||||
mod inner;
|
mod inner;
|
||||||
mod middleware;
|
mod middleware;
|
||||||
|
|
||||||
use all_or_some::AllOrSome;
|
use crate::{
|
||||||
pub use builder::Cors;
|
all_or_some::AllOrSome,
|
||||||
pub use error::CorsError;
|
inner::{Inner, OriginFn},
|
||||||
use inner::{Inner, OriginFn};
|
};
|
||||||
pub use middleware::CorsMiddleware;
|
pub use crate::{builder::Cors, error::CorsError, middleware::CorsMiddleware};
|
||||||
|
@ -16,7 +16,7 @@ use log::debug;
|
|||||||
use crate::{
|
use crate::{
|
||||||
builder::intersperse_header_values,
|
builder::intersperse_header_values,
|
||||||
inner::{add_vary_header, header_value_try_into_method},
|
inner::{add_vary_header, header_value_try_into_method},
|
||||||
AllOrSome, Inner,
|
AllOrSome, CorsError, Inner,
|
||||||
};
|
};
|
||||||
|
|
||||||
/// Service wrapper for Cross-Origin Resource Sharing support.
|
/// Service wrapper for Cross-Origin Resource Sharing support.
|
||||||
@ -60,9 +60,14 @@ impl<S> CorsMiddleware<S> {
|
|||||||
fn handle_preflight(&self, req: ServiceRequest) -> ServiceResponse {
|
fn handle_preflight(&self, req: ServiceRequest) -> ServiceResponse {
|
||||||
let inner = Rc::clone(&self.inner);
|
let inner = Rc::clone(&self.inner);
|
||||||
|
|
||||||
|
match inner.validate_origin(req.head()) {
|
||||||
|
Ok(true) => {}
|
||||||
|
Ok(false) => return req.error_response(CorsError::OriginNotAllowed),
|
||||||
|
Err(err) => return req.error_response(err),
|
||||||
|
};
|
||||||
|
|
||||||
if let Err(err) = inner
|
if let Err(err) = inner
|
||||||
.validate_origin(req.head())
|
.validate_allowed_method(req.head())
|
||||||
.and_then(|_| inner.validate_allowed_method(req.head()))
|
|
||||||
.and_then(|_| inner.validate_allowed_headers(req.head()))
|
.and_then(|_| inner.validate_allowed_headers(req.head()))
|
||||||
{
|
{
|
||||||
return req.error_response(err);
|
return req.error_response(err);
|
||||||
@ -88,6 +93,18 @@ impl<S> CorsMiddleware<S> {
|
|||||||
res.insert_header((header::ACCESS_CONTROL_ALLOW_HEADERS, headers.clone()));
|
res.insert_header((header::ACCESS_CONTROL_ALLOW_HEADERS, headers.clone()));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "draft-private-network-access")]
|
||||||
|
if inner.allow_private_network_access
|
||||||
|
&& req
|
||||||
|
.headers()
|
||||||
|
.contains_key("access-control-request-private-network")
|
||||||
|
{
|
||||||
|
res.insert_header((
|
||||||
|
header::HeaderName::from_static("access-control-allow-private-network"),
|
||||||
|
HeaderValue::from_static("true"),
|
||||||
|
));
|
||||||
|
}
|
||||||
|
|
||||||
if inner.supports_credentials {
|
if inner.supports_credentials {
|
||||||
res.insert_header((
|
res.insert_header((
|
||||||
header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
|
header::ACCESS_CONTROL_ALLOW_CREDENTIALS,
|
||||||
@ -108,11 +125,17 @@ impl<S> CorsMiddleware<S> {
|
|||||||
req.into_response(res)
|
req.into_response(res)
|
||||||
}
|
}
|
||||||
|
|
||||||
fn augment_response<B>(inner: &Inner, mut res: ServiceResponse<B>) -> ServiceResponse<B> {
|
fn augment_response<B>(
|
||||||
|
inner: &Inner,
|
||||||
|
origin_allowed: bool,
|
||||||
|
mut res: ServiceResponse<B>,
|
||||||
|
) -> ServiceResponse<B> {
|
||||||
|
if origin_allowed {
|
||||||
if let Some(origin) = inner.access_control_allow_origin(res.request().head()) {
|
if let Some(origin) = inner.access_control_allow_origin(res.request().head()) {
|
||||||
res.headers_mut()
|
res.headers_mut()
|
||||||
.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, origin);
|
.insert(header::ACCESS_CONTROL_ALLOW_ORIGIN, origin);
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
|
||||||
if let Some(ref expose) = inner.expose_headers_baked {
|
if let Some(ref expose) = inner.expose_headers_baked {
|
||||||
log::trace!("exposing selected headers: {:?}", expose);
|
log::trace!("exposing selected headers: {:?}", expose);
|
||||||
@ -121,13 +144,11 @@ impl<S> CorsMiddleware<S> {
|
|||||||
.insert(header::ACCESS_CONTROL_EXPOSE_HEADERS, expose.clone());
|
.insert(header::ACCESS_CONTROL_EXPOSE_HEADERS, expose.clone());
|
||||||
} else if matches!(inner.expose_headers, AllOrSome::All) {
|
} else if matches!(inner.expose_headers, AllOrSome::All) {
|
||||||
// intersperse_header_values requires that argument is non-empty
|
// intersperse_header_values requires that argument is non-empty
|
||||||
if !res.request().headers().is_empty() {
|
if !res.headers().is_empty() {
|
||||||
// extract header names from request
|
// extract header names from request
|
||||||
let expose_all_request_headers = res
|
let expose_all_request_headers = res
|
||||||
.request()
|
|
||||||
.headers()
|
.headers()
|
||||||
.keys()
|
.keys()
|
||||||
.into_iter()
|
|
||||||
.map(|name| name.as_str())
|
.map(|name| name.as_str())
|
||||||
.collect::<HashSet<_>>();
|
.collect::<HashSet<_>>();
|
||||||
|
|
||||||
@ -152,6 +173,19 @@ impl<S> CorsMiddleware<S> {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "draft-private-network-access")]
|
||||||
|
if inner.allow_private_network_access
|
||||||
|
&& res
|
||||||
|
.request()
|
||||||
|
.headers()
|
||||||
|
.contains_key("access-control-request-private-network")
|
||||||
|
{
|
||||||
|
res.headers_mut().insert(
|
||||||
|
header::HeaderName::from_static("access-control-allow-private-network"),
|
||||||
|
HeaderValue::from_static("true"),
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
if inner.vary_header {
|
if inner.vary_header {
|
||||||
add_vary_header(res.headers_mut());
|
add_vary_header(res.headers_mut());
|
||||||
}
|
}
|
||||||
@ -183,8 +217,10 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
// only check actual requests with a origin header
|
// only check actual requests with a origin header
|
||||||
if origin.is_some() {
|
let origin_allowed = match (origin, self.inner.validate_origin(req.head())) {
|
||||||
if let Err(err) = self.inner.validate_origin(req.head()) {
|
(None, _) => false,
|
||||||
|
(_, Ok(origin_allowed)) => origin_allowed,
|
||||||
|
(_, Err(err)) => {
|
||||||
debug!("origin validation failed; inner service is not called");
|
debug!("origin validation failed; inner service is not called");
|
||||||
let mut res = req.error_response(err);
|
let mut res = req.error_response(err);
|
||||||
|
|
||||||
@ -194,14 +230,14 @@ where
|
|||||||
|
|
||||||
return ok(res.map_into_right_body()).boxed_local();
|
return ok(res.map_into_right_body()).boxed_local();
|
||||||
}
|
}
|
||||||
}
|
};
|
||||||
|
|
||||||
let inner = Rc::clone(&self.inner);
|
let inner = Rc::clone(&self.inner);
|
||||||
let fut = self.service.call(req);
|
let fut = self.service.call(req);
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
let res = fut.await;
|
let res = fut.await;
|
||||||
Ok(Self::augment_response(&inner, res?).map_into_left_body())
|
Ok(Self::augment_response(&inner, origin_allowed, res?).map_into_left_body())
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
|
use actix_cors::Cors;
|
||||||
use actix_utils::future::ok;
|
use actix_utils::future::ok;
|
||||||
use actix_web::dev::fn_service;
|
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
dev::{ServiceRequest, Transform},
|
dev::{fn_service, ServiceRequest, Transform},
|
||||||
http::{
|
http::{
|
||||||
header::{self, HeaderValue},
|
header::{self, HeaderValue},
|
||||||
Method, StatusCode,
|
Method, StatusCode,
|
||||||
@ -11,8 +11,6 @@ use actix_web::{
|
|||||||
};
|
};
|
||||||
use regex::bytes::Regex;
|
use regex::bytes::Regex;
|
||||||
|
|
||||||
use actix_cors::Cors;
|
|
||||||
|
|
||||||
fn val_as_str(val: &HeaderValue) -> &str {
|
fn val_as_str(val: &HeaderValue) -> &str {
|
||||||
val.to_str().unwrap()
|
val.to_str().unwrap()
|
||||||
}
|
}
|
||||||
@ -266,10 +264,16 @@ async fn test_response() {
|
|||||||
.get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
|
.get(header::ACCESS_CONTROL_ALLOW_ORIGIN)
|
||||||
.map(HeaderValue::as_bytes)
|
.map(HeaderValue::as_bytes)
|
||||||
);
|
);
|
||||||
|
#[cfg(not(feature = "draft-private-network-access"))]
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
resp.headers().get(header::VARY).map(HeaderValue::as_bytes),
|
resp.headers().get(header::VARY).map(HeaderValue::as_bytes),
|
||||||
Some(&b"Origin, Access-Control-Request-Method, Access-Control-Request-Headers"[..]),
|
Some(&b"Origin, Access-Control-Request-Method, Access-Control-Request-Headers"[..]),
|
||||||
);
|
);
|
||||||
|
#[cfg(feature = "draft-private-network-access")]
|
||||||
|
assert_eq!(
|
||||||
|
resp.headers().get(header::VARY).map(HeaderValue::as_bytes),
|
||||||
|
Some(&b"Origin, Access-Control-Request-Method, Access-Control-Request-Headers, Access-Control-Request-Private-Network"[..]),
|
||||||
|
);
|
||||||
|
|
||||||
#[allow(clippy::needless_collect)]
|
#[allow(clippy::needless_collect)]
|
||||||
{
|
{
|
||||||
@ -313,9 +317,18 @@ async fn test_response() {
|
|||||||
.method(Method::OPTIONS)
|
.method(Method::OPTIONS)
|
||||||
.to_srv_request();
|
.to_srv_request();
|
||||||
let resp = test::call_service(&cors, req).await;
|
let resp = test::call_service(&cors, req).await;
|
||||||
|
#[cfg(not(feature = "draft-private-network-access"))]
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
resp.headers().get(header::VARY).map(HeaderValue::as_bytes),
|
resp.headers()
|
||||||
Some(&b"Accept, Origin, Access-Control-Request-Method, Access-Control-Request-Headers"[..]),
|
.get(header::VARY)
|
||||||
|
.map(HeaderValue::as_bytes)
|
||||||
|
.unwrap(),
|
||||||
|
b"Accept, Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
|
||||||
|
);
|
||||||
|
#[cfg(feature = "draft-private-network-access")]
|
||||||
|
assert_eq!(
|
||||||
|
resp.headers().get(header::VARY).map(HeaderValue::as_bytes).unwrap(),
|
||||||
|
b"Accept, Origin, Access-Control-Request-Method, Access-Control-Request-Headers, Access-Control-Request-Private-Network",
|
||||||
);
|
);
|
||||||
|
|
||||||
let cors = Cors::default()
|
let cors = Cors::default()
|
||||||
@ -356,6 +369,55 @@ async fn test_validate_origin() {
|
|||||||
assert_eq!(resp.status(), StatusCode::OK);
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[actix_web::test]
|
||||||
|
async fn test_blocks_mismatched_origin_by_default() {
|
||||||
|
let cors = Cors::default()
|
||||||
|
.allowed_origin("https://www.example.com")
|
||||||
|
.new_transform(test::ok_service())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let req = TestRequest::get()
|
||||||
|
.insert_header(("Origin", "https://www.example.test"))
|
||||||
|
.to_srv_request();
|
||||||
|
|
||||||
|
let res = test::call_service(&cors, req).await;
|
||||||
|
assert_eq!(res.status(), StatusCode::OK);
|
||||||
|
assert!(!res
|
||||||
|
.headers()
|
||||||
|
.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN));
|
||||||
|
assert!(!res
|
||||||
|
.headers()
|
||||||
|
.contains_key(header::ACCESS_CONTROL_ALLOW_METHODS));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_web::test]
|
||||||
|
async fn test_mismatched_origin_block_turned_off() {
|
||||||
|
let cors = Cors::default()
|
||||||
|
.allow_any_method()
|
||||||
|
.allowed_origin("https://www.example.com")
|
||||||
|
.block_on_origin_mismatch(false)
|
||||||
|
.new_transform(test::ok_service())
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let req = TestRequest::default()
|
||||||
|
.method(Method::OPTIONS)
|
||||||
|
.insert_header(("Origin", "https://wrong.com"))
|
||||||
|
.insert_header(("Access-Control-Request-Method", "POST"))
|
||||||
|
.to_srv_request();
|
||||||
|
let res = test::call_service(&cors, req).await;
|
||||||
|
assert_eq!(res.status(), StatusCode::BAD_REQUEST);
|
||||||
|
assert_eq!(res.headers().get(header::ACCESS_CONTROL_ALLOW_ORIGIN), None);
|
||||||
|
|
||||||
|
let req = TestRequest::get()
|
||||||
|
.insert_header(("Origin", "https://wrong.com"))
|
||||||
|
.to_srv_request();
|
||||||
|
let res = test::call_service(&cors, req).await;
|
||||||
|
assert_eq!(res.status(), StatusCode::OK);
|
||||||
|
assert_eq!(res.headers().get(header::ACCESS_CONTROL_ALLOW_ORIGIN), None);
|
||||||
|
}
|
||||||
|
|
||||||
#[actix_web::test]
|
#[actix_web::test]
|
||||||
async fn test_no_origin_response() {
|
async fn test_no_origin_response() {
|
||||||
let cors = Cors::permissive()
|
let cors = Cors::permissive()
|
||||||
@ -417,6 +479,7 @@ async fn vary_header_on_all_handled_responses() {
|
|||||||
assert!(resp
|
assert!(resp
|
||||||
.headers()
|
.headers()
|
||||||
.contains_key(header::ACCESS_CONTROL_ALLOW_METHODS));
|
.contains_key(header::ACCESS_CONTROL_ALLOW_METHODS));
|
||||||
|
#[cfg(not(feature = "draft-private-network-access"))]
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
resp.headers()
|
resp.headers()
|
||||||
.get(header::VARY)
|
.get(header::VARY)
|
||||||
@ -425,6 +488,15 @@ async fn vary_header_on_all_handled_responses() {
|
|||||||
.unwrap(),
|
.unwrap(),
|
||||||
"Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
|
"Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
|
||||||
);
|
);
|
||||||
|
#[cfg(feature = "draft-private-network-access")]
|
||||||
|
assert_eq!(
|
||||||
|
resp.headers()
|
||||||
|
.get(header::VARY)
|
||||||
|
.expect("response should have Vary header")
|
||||||
|
.to_str()
|
||||||
|
.unwrap(),
|
||||||
|
"Origin, Access-Control-Request-Method, Access-Control-Request-Headers, Access-Control-Request-Private-Network",
|
||||||
|
);
|
||||||
|
|
||||||
// follow-up regular request
|
// follow-up regular request
|
||||||
let req = TestRequest::default()
|
let req = TestRequest::default()
|
||||||
@ -433,6 +505,7 @@ async fn vary_header_on_all_handled_responses() {
|
|||||||
.to_srv_request();
|
.to_srv_request();
|
||||||
let resp = test::call_service(&cors, req).await;
|
let resp = test::call_service(&cors, req).await;
|
||||||
assert_eq!(resp.status(), StatusCode::OK);
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
#[cfg(not(feature = "draft-private-network-access"))]
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
resp.headers()
|
resp.headers()
|
||||||
.get(header::VARY)
|
.get(header::VARY)
|
||||||
@ -441,6 +514,15 @@ async fn vary_header_on_all_handled_responses() {
|
|||||||
.unwrap(),
|
.unwrap(),
|
||||||
"Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
|
"Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
|
||||||
);
|
);
|
||||||
|
#[cfg(feature = "draft-private-network-access")]
|
||||||
|
assert_eq!(
|
||||||
|
resp.headers()
|
||||||
|
.get(header::VARY)
|
||||||
|
.expect("response should have Vary header")
|
||||||
|
.to_str()
|
||||||
|
.unwrap(),
|
||||||
|
"Origin, Access-Control-Request-Method, Access-Control-Request-Headers, Access-Control-Request-Private-Network",
|
||||||
|
);
|
||||||
|
|
||||||
let cors = Cors::default()
|
let cors = Cors::default()
|
||||||
.allow_any_method()
|
.allow_any_method()
|
||||||
@ -448,13 +530,44 @@ async fn vary_header_on_all_handled_responses() {
|
|||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
// regular request bad origin
|
// regular request OK with no CORS response headers
|
||||||
let req = TestRequest::default()
|
let req = TestRequest::default()
|
||||||
.method(Method::PUT)
|
.method(Method::PUT)
|
||||||
.insert_header((header::ORIGIN, "https://www.example.com"))
|
.insert_header((header::ORIGIN, "https://www.example.com"))
|
||||||
.to_srv_request();
|
.to_srv_request();
|
||||||
|
let res = test::call_service(&cors, req).await;
|
||||||
|
assert_eq!(res.status(), StatusCode::OK);
|
||||||
|
assert!(!res
|
||||||
|
.headers()
|
||||||
|
.contains_key(header::ACCESS_CONTROL_ALLOW_ORIGIN));
|
||||||
|
assert!(!res
|
||||||
|
.headers()
|
||||||
|
.contains_key(header::ACCESS_CONTROL_ALLOW_METHODS));
|
||||||
|
|
||||||
|
#[cfg(not(feature = "draft-private-network-access"))]
|
||||||
|
assert_eq!(
|
||||||
|
res.headers()
|
||||||
|
.get(header::VARY)
|
||||||
|
.expect("response should have Vary header")
|
||||||
|
.to_str()
|
||||||
|
.unwrap(),
|
||||||
|
"Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
|
||||||
|
);
|
||||||
|
#[cfg(feature = "draft-private-network-access")]
|
||||||
|
assert_eq!(
|
||||||
|
res.headers()
|
||||||
|
.get(header::VARY)
|
||||||
|
.expect("response should have Vary header")
|
||||||
|
.to_str()
|
||||||
|
.unwrap(),
|
||||||
|
"Origin, Access-Control-Request-Method, Access-Control-Request-Headers, Access-Control-Request-Private-Network",
|
||||||
|
);
|
||||||
|
|
||||||
|
// regular request no origin
|
||||||
|
let req = TestRequest::default().method(Method::PUT).to_srv_request();
|
||||||
let resp = test::call_service(&cors, req).await;
|
let resp = test::call_service(&cors, req).await;
|
||||||
assert_eq!(resp.status(), StatusCode::BAD_REQUEST);
|
assert_eq!(resp.status(), StatusCode::OK);
|
||||||
|
#[cfg(not(feature = "draft-private-network-access"))]
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
resp.headers()
|
resp.headers()
|
||||||
.get(header::VARY)
|
.get(header::VARY)
|
||||||
@ -463,18 +576,14 @@ async fn vary_header_on_all_handled_responses() {
|
|||||||
.unwrap(),
|
.unwrap(),
|
||||||
"Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
|
"Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
|
||||||
);
|
);
|
||||||
|
#[cfg(feature = "draft-private-network-access")]
|
||||||
// regular request no origin
|
|
||||||
let req = TestRequest::default().method(Method::PUT).to_srv_request();
|
|
||||||
let resp = test::call_service(&cors, req).await;
|
|
||||||
assert_eq!(resp.status(), StatusCode::OK);
|
|
||||||
assert_eq!(
|
assert_eq!(
|
||||||
resp.headers()
|
resp.headers()
|
||||||
.get(header::VARY)
|
.get(header::VARY)
|
||||||
.expect("response should have Vary header")
|
.expect("response should have Vary header")
|
||||||
.to_str()
|
.to_str()
|
||||||
.unwrap(),
|
.unwrap(),
|
||||||
"Origin, Access-Control-Request-Method, Access-Control-Request-Headers",
|
"Origin, Access-Control-Request-Method, Access-Control-Request-Headers, Access-Control-Request-Private-Network",
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -502,7 +611,15 @@ async fn test_allow_any_origin_any_method_any_header() {
|
|||||||
#[actix_web::test]
|
#[actix_web::test]
|
||||||
async fn expose_all_request_header_values() {
|
async fn expose_all_request_header_values() {
|
||||||
let cors = Cors::permissive()
|
let cors = Cors::permissive()
|
||||||
.new_transform(test::ok_service())
|
.new_transform(fn_service(|req: ServiceRequest| async move {
|
||||||
|
let res = req.into_response(
|
||||||
|
HttpResponse::Ok()
|
||||||
|
.insert_header((header::CONTENT_DISPOSITION, "test disposition"))
|
||||||
|
.finish(),
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(res)
|
||||||
|
}))
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
|
||||||
@ -510,20 +627,56 @@ async fn expose_all_request_header_values() {
|
|||||||
.insert_header((header::ORIGIN, "https://www.example.com"))
|
.insert_header((header::ORIGIN, "https://www.example.com"))
|
||||||
.insert_header((header::ACCESS_CONTROL_REQUEST_METHOD, "POST"))
|
.insert_header((header::ACCESS_CONTROL_REQUEST_METHOD, "POST"))
|
||||||
.insert_header((header::ACCESS_CONTROL_REQUEST_HEADERS, "content-type"))
|
.insert_header((header::ACCESS_CONTROL_REQUEST_HEADERS, "content-type"))
|
||||||
.insert_header(("X-XSRF-TOKEN", "xsrf-token"))
|
|
||||||
.to_srv_request();
|
.to_srv_request();
|
||||||
|
|
||||||
let resp = test::call_service(&cors, req).await;
|
let res = test::call_service(&cors, req).await;
|
||||||
|
|
||||||
assert!(resp
|
let cd_hdr = res
|
||||||
.headers()
|
|
||||||
.contains_key(header::ACCESS_CONTROL_EXPOSE_HEADERS));
|
|
||||||
|
|
||||||
assert!(resp
|
|
||||||
.headers()
|
.headers()
|
||||||
.get(header::ACCESS_CONTROL_EXPOSE_HEADERS)
|
.get(header::ACCESS_CONTROL_EXPOSE_HEADERS)
|
||||||
.unwrap()
|
.unwrap()
|
||||||
.to_str()
|
.to_str()
|
||||||
.unwrap()
|
.unwrap();
|
||||||
.contains("xsrf-token"));
|
|
||||||
|
assert!(cd_hdr.contains("content-disposition"));
|
||||||
|
assert!(cd_hdr.contains("access-control-allow-origin"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "draft-private-network-access")]
|
||||||
|
#[actix_web::test]
|
||||||
|
async fn private_network_access() {
|
||||||
|
let cors = Cors::permissive()
|
||||||
|
.allowed_origin("https://public.site")
|
||||||
|
.allow_private_network_access()
|
||||||
|
.new_transform(fn_service(|req: ServiceRequest| async move {
|
||||||
|
let res = req.into_response(
|
||||||
|
HttpResponse::Ok()
|
||||||
|
.insert_header((header::CONTENT_DISPOSITION, "test disposition"))
|
||||||
|
.finish(),
|
||||||
|
);
|
||||||
|
|
||||||
|
Ok(res)
|
||||||
|
}))
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let req = TestRequest::default()
|
||||||
|
.insert_header((header::ORIGIN, "https://public.site"))
|
||||||
|
.insert_header((header::ACCESS_CONTROL_REQUEST_METHOD, "POST"))
|
||||||
|
.insert_header((header::ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"))
|
||||||
|
.to_srv_request();
|
||||||
|
let res = test::call_service(&cors, req).await;
|
||||||
|
assert!(res.headers().contains_key("access-control-allow-origin"));
|
||||||
|
|
||||||
|
let req = TestRequest::default()
|
||||||
|
.insert_header((header::ORIGIN, "https://public.site"))
|
||||||
|
.insert_header((header::ACCESS_CONTROL_REQUEST_METHOD, "POST"))
|
||||||
|
.insert_header((header::ACCESS_CONTROL_ALLOW_CREDENTIALS, "true"))
|
||||||
|
.insert_header(("Access-Control-Request-Private-Network", "true"))
|
||||||
|
.to_srv_request();
|
||||||
|
let res = test::call_service(&cors, req).await;
|
||||||
|
assert!(res.headers().contains_key("access-control-allow-origin"));
|
||||||
|
assert!(res
|
||||||
|
.headers()
|
||||||
|
.contains_key("access-control-allow-private-network"));
|
||||||
}
|
}
|
||||||
|
@ -1,58 +1,126 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## Unreleased - 2021-xx-xx
|
## Unreleased
|
||||||
|
|
||||||
|
## 0.8.0
|
||||||
|
|
||||||
|
- Update `actix-session` dependency to `0.10`.
|
||||||
|
|
||||||
|
## 0.7.1
|
||||||
|
|
||||||
|
- Add `IdentityMiddlewareBuilder::{id_key, last_visit_unix_timestamp_key, login_unix_timestamp_key}()` methods for customizing keys used in session. Defaults remain the same as before.
|
||||||
|
|
||||||
|
## 0.7.0
|
||||||
|
|
||||||
|
- Update `actix-session` dependency to `0.9`.
|
||||||
|
- Minimum supported Rust version (MSRV) is now 1.75.
|
||||||
|
|
||||||
|
## 0.6.0
|
||||||
|
|
||||||
|
- Add `error` module.
|
||||||
|
- Replace use of `anyhow::Error` in return types with specific error types.
|
||||||
|
- Update `actix-session` dependency to `0.8`.
|
||||||
|
- Minimum supported Rust version (MSRV) is now 1.68.
|
||||||
|
|
||||||
|
## 0.5.2
|
||||||
|
|
||||||
|
- Fix visit deadline. [#263]
|
||||||
|
|
||||||
|
[#263]: https://github.com/actix/actix-extras/pull/263
|
||||||
|
|
||||||
|
## 0.5.1
|
||||||
|
|
||||||
|
- Remove unnecessary dependencies. [#259]
|
||||||
|
|
||||||
|
[#259]: https://github.com/actix/actix-extras/pull/259
|
||||||
|
|
||||||
|
## 0.5.0
|
||||||
|
|
||||||
|
`actix-identity` v0.5 is a complete rewrite. The goal is to streamline user experience and reduce maintenance overhead.
|
||||||
|
|
||||||
|
`actix-identity` is now designed as an additional layer on top of `actix-session` v0.7, focused on identity management. The identity information is stored in the session state, which is managed by `actix-session` and can be stored using any of the supported `SessionStore` implementations. This reduces the surface area in `actix-identity` (e.g., it is no longer concerned with cookies!) and provides a smooth upgrade path for users: if you need to work with sessions, you no longer need to choose between `actix-session` and `actix-identity`; they work together now!
|
||||||
|
|
||||||
|
`actix-identity` v0.5 has feature-parity with `actix-identity` v0.4; if you bump into any blocker when upgrading, please open an issue.
|
||||||
|
|
||||||
|
Changes:
|
||||||
|
|
||||||
|
- Minimum supported Rust version (MSRV) is now 1.57 due to transitive `time` dependency.
|
||||||
|
- `IdentityService`, `IdentityPolicy` and `CookieIdentityPolicy` have been replaced by `IdentityMiddleware`. [#246]
|
||||||
|
- Rename `RequestIdentity` trait to `IdentityExt`. [#246]
|
||||||
|
- Trying to extract an `Identity` for an unauthenticated user will return a `401 Unauthorized` response to the client. Extract an `Option<Identity>` or a `Result<Identity, actix_web::Error>` if you need to handle cases where requests may or may not be authenticated. [#246]
|
||||||
|
|
||||||
|
Example:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use actix_web::{http::header::LOCATION, get, HttpResponse, Responder};
|
||||||
|
use actix_identity::Identity;
|
||||||
|
|
||||||
|
#[get("/")]
|
||||||
|
async fn index(user: Option<Identity>) -> impl Responder {
|
||||||
|
if let Some(user) = user {
|
||||||
|
HttpResponse::Ok().finish()
|
||||||
|
} else {
|
||||||
|
// Redirect to login page if unauthenticated
|
||||||
|
HttpResponse::TemporaryRedirect()
|
||||||
|
.insert_header((LOCATION, "/login"))
|
||||||
|
.finish()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
[#246]: https://github.com/actix/actix-extras/pull/246
|
||||||
|
|
||||||
|
## 0.4.0
|
||||||
|
|
||||||
## 0.4.0 - 2022-03-01
|
|
||||||
- Update `actix-web` dependency to `4`.
|
- Update `actix-web` dependency to `4`.
|
||||||
|
|
||||||
|
## 0.4.0-beta.9
|
||||||
|
|
||||||
## 0.4.0-beta.9 - 2022-02-07
|
|
||||||
- Relax body type bounds on middleware impl. [#223]
|
- Relax body type bounds on middleware impl. [#223]
|
||||||
- Update `actix-web` dependency to `4.0.0-rc.1`.
|
- Update `actix-web` dependency to `4.0.0-rc.1`.
|
||||||
|
|
||||||
[#223]: https://github.com/actix/actix-extras/pull/223
|
[#223]: https://github.com/actix/actix-extras/pull/223
|
||||||
|
|
||||||
|
## 0.4.0-beta.8
|
||||||
|
|
||||||
## 0.4.0-beta.8 - 2022-01-21
|
|
||||||
- No significant changes since `0.4.0-beta.7`.
|
- No significant changes since `0.4.0-beta.7`.
|
||||||
|
|
||||||
|
## 0.4.0-beta.7
|
||||||
|
|
||||||
## 0.4.0-beta.7 - 2021-12-29
|
|
||||||
- Update `actix-web` dependency to `4.0.0.beta-18`. [#218]
|
- Update `actix-web` dependency to `4.0.0.beta-18`. [#218]
|
||||||
- Minimum supported Rust version (MSRV) is now 1.54.
|
- Minimum supported Rust version (MSRV) is now 1.54.
|
||||||
|
|
||||||
[#218]: https://github.com/actix/actix-extras/pull/218
|
[#218]: https://github.com/actix/actix-extras/pull/218
|
||||||
|
|
||||||
|
## 0.4.0-beta.6
|
||||||
|
|
||||||
## 0.4.0-beta.6 - 2021-12-18
|
|
||||||
- Update `actix-web` dependency to `4.0.0.beta-15`. [#216]
|
- Update `actix-web` dependency to `4.0.0.beta-15`. [#216]
|
||||||
|
|
||||||
[#216]: https://github.com/actix/actix-extras/pull/216
|
[#216]: https://github.com/actix/actix-extras/pull/216
|
||||||
|
|
||||||
|
## 0.4.0-beta.5
|
||||||
|
|
||||||
## 0.4.0-beta.5 - 2021-12-12
|
|
||||||
- Update `actix-web` dependency to `4.0.0.beta-14`. [#209]
|
- Update `actix-web` dependency to `4.0.0.beta-14`. [#209]
|
||||||
|
|
||||||
[#209]: https://github.com/actix/actix-extras/pull/209
|
[#209]: https://github.com/actix/actix-extras/pull/209
|
||||||
|
|
||||||
|
## 0.4.0-beta.4
|
||||||
|
|
||||||
## 0.4.0-beta.4 - 2021-11-22
|
|
||||||
- No significant changes since `0.4.0-beta.3`.
|
- No significant changes since `0.4.0-beta.3`.
|
||||||
|
|
||||||
|
## 0.4.0-beta.3
|
||||||
|
|
||||||
## 0.4.0-beta.3 - 2021-10-21
|
|
||||||
- Update `actix-web` dependency to v4.0.0-beta.10. [#203]
|
- Update `actix-web` dependency to v4.0.0-beta.10. [#203]
|
||||||
- Minimum supported Rust version (MSRV) is now 1.52.
|
- Minimum supported Rust version (MSRV) is now 1.52.
|
||||||
|
|
||||||
[#203]: https://github.com/actix/actix-extras/pull/203
|
[#203]: https://github.com/actix/actix-extras/pull/203
|
||||||
|
|
||||||
|
## 0.4.0-beta.2
|
||||||
|
|
||||||
## 0.4.0-beta.2 - 2021-06-27
|
|
||||||
- No notable changes.
|
- No notable changes.
|
||||||
|
|
||||||
|
## 0.4.0-beta.1
|
||||||
|
|
||||||
## 0.4.0-beta.1 - 2021-04-02
|
|
||||||
- Rename `CookieIdentityPolicy::{max_age => max_age_secs}`. [#168]
|
- Rename `CookieIdentityPolicy::{max_age => max_age_secs}`. [#168]
|
||||||
- Rename `CookieIdentityPolicy::{max_age_time => max_age}`. [#168]
|
- Rename `CookieIdentityPolicy::{max_age_time => max_age}`. [#168]
|
||||||
- Update `actix-web` dependency to 4.0.0 beta.
|
- Update `actix-web` dependency to 4.0.0 beta.
|
||||||
@ -60,31 +128,31 @@
|
|||||||
|
|
||||||
[#168]: https://github.com/actix/actix-extras/pull/168
|
[#168]: https://github.com/actix/actix-extras/pull/168
|
||||||
|
|
||||||
|
## 0.3.1
|
||||||
|
|
||||||
## 0.3.1 - 2020-09-20
|
|
||||||
- Add method to set `HttpOnly` flag on cookie identity. [#102]
|
- Add method to set `HttpOnly` flag on cookie identity. [#102]
|
||||||
|
|
||||||
[#102]: https://github.com/actix/actix-extras/pull/102
|
[#102]: https://github.com/actix/actix-extras/pull/102
|
||||||
|
|
||||||
|
## 0.3.0
|
||||||
|
|
||||||
## 0.3.0 - 2020-09-11
|
|
||||||
- Update `actix-web` dependency to 3.0.0.
|
- Update `actix-web` dependency to 3.0.0.
|
||||||
- Minimum supported Rust version (MSRV) is now 1.42.0.
|
- Minimum supported Rust version (MSRV) is now 1.42.0.
|
||||||
|
|
||||||
|
## 0.3.0-alpha.1
|
||||||
|
|
||||||
## 0.3.0-alpha.1 - 2020-03-14
|
|
||||||
- Update the `time` dependency to 0.2.7
|
- Update the `time` dependency to 0.2.7
|
||||||
- Update the `actix-web` dependency to 3.0.0-alpha.1
|
- Update the `actix-web` dependency to 3.0.0-alpha.1
|
||||||
- Minimize `futures` dependency
|
- Minimize `futures` dependency
|
||||||
|
|
||||||
|
## 0.2.1
|
||||||
|
|
||||||
## 0.2.1 - 2020-01-10
|
|
||||||
- Fix panic with already borrowed: BorrowMutError #1263
|
- Fix panic with already borrowed: BorrowMutError #1263
|
||||||
|
|
||||||
|
|
||||||
## 0.2.0 - 2019-12-20
|
## 0.2.0 - 2019-12-20
|
||||||
|
|
||||||
- Use actix-web 2.0
|
- Use actix-web 2.0
|
||||||
|
|
||||||
|
|
||||||
## 0.1.0 - 2019-06-xx
|
## 0.1.0 - 2019-06-xx
|
||||||
|
|
||||||
- Move identity middleware to separate crate
|
- Move identity middleware to separate crate
|
||||||
|
@ -1,28 +1,41 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-identity"
|
name = "actix-identity"
|
||||||
version = "0.4.0"
|
version = "0.8.0"
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
authors = [
|
||||||
description = "Identity service for Actix Web"
|
"Nikolay Kim <fafhrd91@gmail.com>",
|
||||||
|
"Luca Palmieri <rust@lpalmieri.com>",
|
||||||
|
]
|
||||||
|
description = "Identity management for Actix Web"
|
||||||
keywords = ["actix", "auth", "identity", "web", "security"]
|
keywords = ["actix", "auth", "identity", "web", "security"]
|
||||||
homepage = "https://actix.rs"
|
repository.workspace = true
|
||||||
repository = "https://github.com/actix/actix-extras.git"
|
homepage.workspace = true
|
||||||
license = "MIT OR Apache-2.0"
|
license.workspace = true
|
||||||
edition = "2018"
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
|
||||||
[lib]
|
[package.metadata.docs.rs]
|
||||||
name = "actix_identity"
|
rustdoc-args = ["--cfg", "docsrs"]
|
||||||
path = "src/lib.rs"
|
all-features = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "2"
|
actix-service = "2"
|
||||||
|
actix-session = "0.10"
|
||||||
actix-utils = "3"
|
actix-utils = "3"
|
||||||
actix-web = { version = "4", default-features = false, features = ["cookies", "secure-cookies"] }
|
actix-web = { version = "4", default-features = false, features = ["cookies", "secure-cookies"] }
|
||||||
|
|
||||||
futures-util = { version = "0.3.7", default-features = false }
|
derive_more = { version = "2", features = ["display", "error", "from"] }
|
||||||
|
futures-core = "0.3.17"
|
||||||
serde = { version = "1", features = ["derive"] }
|
serde = { version = "1", features = ["derive"] }
|
||||||
serde_json = "1"
|
tracing = { version = "0.1.30", default-features = false, features = ["log"] }
|
||||||
time = "0.3"
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-http = "3.0.0-rc.1"
|
actix-http = "3"
|
||||||
actix-web = { version = "4", default_features = false, features = ["macros", "cookies", "secure-cookies"] }
|
actix-web = { version = "4", default-features = false, features = ["macros", "cookies", "secure-cookies"] }
|
||||||
|
actix-session = { version = "0.10", features = ["redis-session", "cookie-session"] }
|
||||||
|
|
||||||
|
env_logger = "0.11"
|
||||||
|
reqwest = { version = "0.12", default-features = false, features = ["cookies", "json"] }
|
||||||
|
uuid = { version = "1", features = ["v4"] }
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
|
@ -1,13 +1,106 @@
|
|||||||
# actix-identity
|
# actix-identity
|
||||||
|
|
||||||
> Identity service for actix-web framework.
|
> Identity management for Actix Web.
|
||||||
|
|
||||||
|
<!-- prettier-ignore-start -->
|
||||||
|
|
||||||
[](https://crates.io/crates/actix-identity)
|
[](https://crates.io/crates/actix-identity)
|
||||||
[](https://docs.rs/actix-identity/0.4.0)
|
[](https://docs.rs/actix-identity/0.8.0)
|
||||||

|

|
||||||
[](https://deps.rs/crate/actix-identity/0.4.0)
|
[](https://deps.rs/crate/actix-identity/0.8.0)
|
||||||
|
|
||||||
## Documentation & community resources
|
<!-- prettier-ignore-end -->
|
||||||
|
|
||||||
* [API Documentation](https://docs.rs/actix-identity)
|
<!-- cargo-rdme start -->
|
||||||
* Minimum Supported Rust Version (MSRV): 1.54
|
|
||||||
|
Identity management for Actix Web.
|
||||||
|
|
||||||
|
`actix-identity` can be used to track identity of a user across multiple requests. It is built on top of HTTP sessions, via [`actix-session`](https://docs.rs/actix-session).
|
||||||
|
|
||||||
|
## Getting started
|
||||||
|
|
||||||
|
To start using identity management in your Actix Web application you must register [`IdentityMiddleware`] and `SessionMiddleware` as middleware on your `App`:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use actix_web::{cookie::Key, App, HttpServer, HttpResponse};
|
||||||
|
use actix_identity::IdentityMiddleware;
|
||||||
|
use actix_session::{storage::RedisSessionStore, SessionMiddleware};
|
||||||
|
|
||||||
|
#[actix_web::main]
|
||||||
|
async fn main() {
|
||||||
|
// When using `Key::generate()` it is important to initialize outside of the
|
||||||
|
// `HttpServer::new` closure. When deployed the secret key should be read from a
|
||||||
|
// configuration file or environment variables.
|
||||||
|
let secret_key = Key::generate();
|
||||||
|
|
||||||
|
let redis_store = RedisSessionStore::new("redis://127.0.0.1:6379")
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
HttpServer::new(move || {
|
||||||
|
App::new()
|
||||||
|
// Install the identity framework first.
|
||||||
|
.wrap(IdentityMiddleware::default())
|
||||||
|
// The identity system is built on top of sessions. You must install the session
|
||||||
|
// middleware to leverage `actix-identity`. The session middleware must be mounted
|
||||||
|
// AFTER the identity middleware: `actix-web` invokes middleware in the OPPOSITE
|
||||||
|
// order of registration when it receives an incoming request.
|
||||||
|
.wrap(SessionMiddleware::new(
|
||||||
|
redis_store.clone(),
|
||||||
|
secret_key.clone(),
|
||||||
|
))
|
||||||
|
// Your request handlers [...]
|
||||||
|
})
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
User identities can be created, accessed and destroyed using the [`Identity`] extractor in your request handlers:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use actix_web::{get, post, HttpResponse, Responder, HttpRequest, HttpMessage};
|
||||||
|
use actix_identity::Identity;
|
||||||
|
use actix_session::storage::RedisSessionStore;
|
||||||
|
|
||||||
|
#[get("/")]
|
||||||
|
async fn index(user: Option<Identity>) -> impl Responder {
|
||||||
|
if let Some(user) = user {
|
||||||
|
format!("Welcome! {}", user.id().unwrap())
|
||||||
|
} else {
|
||||||
|
"Welcome Anonymous!".to_owned()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[post("/login")]
|
||||||
|
async fn login(request: HttpRequest) -> impl Responder {
|
||||||
|
// Some kind of authentication should happen here
|
||||||
|
// e.g. password-based, biometric, etc.
|
||||||
|
// [...]
|
||||||
|
|
||||||
|
// attach a verified user identity to the active session
|
||||||
|
Identity::login(&request.extensions(), "User1".into()).unwrap();
|
||||||
|
|
||||||
|
HttpResponse::Ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[post("/logout")]
|
||||||
|
async fn logout(user: Option<Identity>) -> impl Responder {
|
||||||
|
if let Some(user) = user {
|
||||||
|
user.logout();
|
||||||
|
}
|
||||||
|
HttpResponse::Ok()
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Advanced configuration
|
||||||
|
|
||||||
|
By default, `actix-identity` does not automatically log out users. You can change this behaviour by customising the configuration for [`IdentityMiddleware`] via [`IdentityMiddleware::builder`].
|
||||||
|
|
||||||
|
In particular, you can automatically log out users who:
|
||||||
|
|
||||||
|
- have been inactive for a while (see [`IdentityMiddlewareBuilder::visit_deadline`]);
|
||||||
|
- logged in too long ago (see [`IdentityMiddlewareBuilder::login_deadline`]).
|
||||||
|
|
||||||
|
[`IdentityMiddlewareBuilder::visit_deadline`]: config::IdentityMiddlewareBuilder::visit_deadline
|
||||||
|
[`IdentityMiddlewareBuilder::login_deadline`]: config::IdentityMiddlewareBuilder::login_deadline
|
||||||
|
|
||||||
|
<!-- cargo-rdme end -->
|
||||||
|
93
actix-identity/examples/identity.rs
Normal file
93
actix-identity/examples/identity.rs
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
//! A rudimentary example of how to set up and use `actix-identity`.
|
||||||
|
//!
|
||||||
|
//! ```bash
|
||||||
|
//! # using HTTPie (https://httpie.io/cli)
|
||||||
|
//!
|
||||||
|
//! # outputs "Welcome Anonymous!" message
|
||||||
|
//! http -v --session=identity GET localhost:8080/
|
||||||
|
//!
|
||||||
|
//! # log in using fake details, ensuring that --session is used to persist cookies
|
||||||
|
//! http -v --session=identity POST localhost:8080/login user_id=foo
|
||||||
|
//!
|
||||||
|
//! # outputs "Welcome User1" message
|
||||||
|
//! http -v --session=identity GET localhost:8080/
|
||||||
|
//! ```
|
||||||
|
|
||||||
|
use std::{io, time::Duration};
|
||||||
|
|
||||||
|
use actix_identity::{Identity, IdentityMiddleware};
|
||||||
|
use actix_session::{config::PersistentSession, storage::CookieSessionStore, SessionMiddleware};
|
||||||
|
use actix_web::{
|
||||||
|
cookie::Key, get, middleware::Logger, post, App, HttpMessage, HttpRequest, HttpResponse,
|
||||||
|
HttpServer, Responder,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[actix_web::main]
|
||||||
|
async fn main() -> io::Result<()> {
|
||||||
|
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
||||||
|
|
||||||
|
let secret_key = Key::generate();
|
||||||
|
|
||||||
|
let expiration = Duration::from_secs(24 * 60 * 60);
|
||||||
|
|
||||||
|
HttpServer::new(move || {
|
||||||
|
let session_mw =
|
||||||
|
SessionMiddleware::builder(CookieSessionStore::default(), secret_key.clone())
|
||||||
|
// disable secure cookie for local testing
|
||||||
|
.cookie_secure(false)
|
||||||
|
// Set a ttl for the cookie if the identity should live longer than the user session
|
||||||
|
.session_lifecycle(
|
||||||
|
PersistentSession::default().session_ttl(expiration.try_into().unwrap()),
|
||||||
|
)
|
||||||
|
.build();
|
||||||
|
let identity_mw = IdentityMiddleware::builder()
|
||||||
|
.visit_deadline(Some(expiration))
|
||||||
|
.build();
|
||||||
|
|
||||||
|
App::new()
|
||||||
|
// Install the identity framework first.
|
||||||
|
.wrap(identity_mw)
|
||||||
|
// The identity system is built on top of sessions. You must install the session
|
||||||
|
// middleware to leverage `actix-identity`. The session middleware must be mounted
|
||||||
|
// AFTER the identity middleware: `actix-web` invokes middleware in the OPPOSITE
|
||||||
|
// order of registration when it receives an incoming request.
|
||||||
|
.wrap(session_mw)
|
||||||
|
.wrap(Logger::default())
|
||||||
|
.service(index)
|
||||||
|
.service(login)
|
||||||
|
.service(logout)
|
||||||
|
})
|
||||||
|
.bind(("127.0.0.1", 8080))
|
||||||
|
.unwrap()
|
||||||
|
.workers(2)
|
||||||
|
.run()
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
#[get("/")]
|
||||||
|
async fn index(user: Option<Identity>) -> impl Responder {
|
||||||
|
if let Some(user) = user {
|
||||||
|
format!("Welcome! {}", user.id().unwrap())
|
||||||
|
} else {
|
||||||
|
"Welcome Anonymous!".to_owned()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[post("/login")]
|
||||||
|
async fn login(request: HttpRequest) -> impl Responder {
|
||||||
|
// Some kind of authentication should happen here -
|
||||||
|
// e.g. password-based, biometric, etc.
|
||||||
|
// [...]
|
||||||
|
|
||||||
|
// Attached a verified user identity to the active
|
||||||
|
// session.
|
||||||
|
Identity::login(&request.extensions(), "User1".into()).unwrap();
|
||||||
|
|
||||||
|
HttpResponse::Ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[post("/logout")]
|
||||||
|
async fn logout(user: Identity) -> impl Responder {
|
||||||
|
user.logout();
|
||||||
|
HttpResponse::NoContent()
|
||||||
|
}
|
125
actix-identity/src/config.rs
Normal file
125
actix-identity/src/config.rs
Normal file
@ -0,0 +1,125 @@
|
|||||||
|
//! Configuration options to tune the behaviour of [`IdentityMiddleware`].
|
||||||
|
|
||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use crate::IdentityMiddleware;
|
||||||
|
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub(crate) struct Configuration {
|
||||||
|
pub(crate) on_logout: LogoutBehaviour,
|
||||||
|
pub(crate) login_deadline: Option<Duration>,
|
||||||
|
pub(crate) visit_deadline: Option<Duration>,
|
||||||
|
pub(crate) id_key: &'static str,
|
||||||
|
pub(crate) last_visit_unix_timestamp_key: &'static str,
|
||||||
|
pub(crate) login_unix_timestamp_key: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for Configuration {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
on_logout: LogoutBehaviour::PurgeSession,
|
||||||
|
login_deadline: None,
|
||||||
|
visit_deadline: None,
|
||||||
|
id_key: "actix_identity.user_id",
|
||||||
|
last_visit_unix_timestamp_key: "actix_identity.last_visited_at",
|
||||||
|
login_unix_timestamp_key: "actix_identity.logged_in_at",
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// `LogoutBehaviour` controls what actions are going to be performed when [`Identity::logout`] is
|
||||||
|
/// invoked.
|
||||||
|
///
|
||||||
|
/// [`Identity::logout`]: crate::Identity::logout
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub enum LogoutBehaviour {
|
||||||
|
/// When [`Identity::logout`](crate::Identity::logout) is called, purge the current session.
|
||||||
|
///
|
||||||
|
/// This behaviour might be desirable when you have stored additional information in the
|
||||||
|
/// session state that are tied to the user's identity and should not be retained after logout.
|
||||||
|
PurgeSession,
|
||||||
|
|
||||||
|
/// When [`Identity::logout`](crate::Identity::logout) is called, remove the identity
|
||||||
|
/// information from the current session state. The session itself is not destroyed.
|
||||||
|
///
|
||||||
|
/// This behaviour might be desirable when you have stored information in the session state that
|
||||||
|
/// is not tied to the user's identity and should be retained after logout.
|
||||||
|
DeleteIdentityKeys,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A fluent builder to construct an [`IdentityMiddleware`] instance with custom configuration
|
||||||
|
/// parameters.
|
||||||
|
///
|
||||||
|
/// Use [`IdentityMiddleware::builder`] to get started!
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct IdentityMiddlewareBuilder {
|
||||||
|
configuration: Configuration,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IdentityMiddlewareBuilder {
|
||||||
|
pub(crate) fn new() -> Self {
|
||||||
|
Self {
|
||||||
|
configuration: Configuration::default(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set a custom key to identify the user in the session.
|
||||||
|
pub fn id_key(mut self, key: &'static str) -> Self {
|
||||||
|
self.configuration.id_key = key;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set a custom key to store the last visited unix timestamp.
|
||||||
|
pub fn last_visit_unix_timestamp_key(mut self, key: &'static str) -> Self {
|
||||||
|
self.configuration.last_visit_unix_timestamp_key = key;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set a custom key to store the login unix timestamp.
|
||||||
|
pub fn login_unix_timestamp_key(mut self, key: &'static str) -> Self {
|
||||||
|
self.configuration.login_unix_timestamp_key = key;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Determines how [`Identity::logout`](crate::Identity::logout) affects the current session.
|
||||||
|
///
|
||||||
|
/// By default, the current session is purged ([`LogoutBehaviour::PurgeSession`]).
|
||||||
|
pub fn logout_behaviour(mut self, logout_behaviour: LogoutBehaviour) -> Self {
|
||||||
|
self.configuration.on_logout = logout_behaviour;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Automatically logs out users after a certain amount of time has passed since they logged in,
|
||||||
|
/// regardless of their activity pattern.
|
||||||
|
///
|
||||||
|
/// If set to:
|
||||||
|
/// - `None`: login deadline is disabled.
|
||||||
|
/// - `Some(duration)`: login deadline is enabled and users will be logged out after `duration`
|
||||||
|
/// has passed since their login.
|
||||||
|
///
|
||||||
|
/// By default, login deadline is disabled.
|
||||||
|
pub fn login_deadline(mut self, deadline: Option<Duration>) -> Self {
|
||||||
|
self.configuration.login_deadline = deadline;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Automatically logs out users after a certain amount of time has passed since their last
|
||||||
|
/// visit.
|
||||||
|
///
|
||||||
|
/// If set to:
|
||||||
|
/// - `None`: visit deadline is disabled.
|
||||||
|
/// - `Some(duration)`: visit deadline is enabled and users will be logged out after `duration`
|
||||||
|
/// has passed since their last visit.
|
||||||
|
///
|
||||||
|
/// By default, visit deadline is disabled.
|
||||||
|
pub fn visit_deadline(mut self, deadline: Option<Duration>) -> Self {
|
||||||
|
self.configuration.visit_deadline = deadline;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finalises the builder and returns an [`IdentityMiddleware`] instance.
|
||||||
|
pub fn build(self) -> IdentityMiddleware {
|
||||||
|
IdentityMiddleware::new(self.configuration)
|
||||||
|
}
|
||||||
|
}
|
@ -1,829 +0,0 @@
|
|||||||
use std::{rc::Rc, time::SystemTime};
|
|
||||||
|
|
||||||
use actix_utils::future::{ready, Ready};
|
|
||||||
use serde::{Deserialize, Serialize};
|
|
||||||
use time::Duration;
|
|
||||||
|
|
||||||
use actix_web::{
|
|
||||||
cookie::{Cookie, CookieJar, Key, SameSite},
|
|
||||||
dev::{ServiceRequest, ServiceResponse},
|
|
||||||
error::{Error, Result},
|
|
||||||
http::header::{self, HeaderValue},
|
|
||||||
HttpMessage,
|
|
||||||
};
|
|
||||||
|
|
||||||
use crate::IdentityPolicy;
|
|
||||||
|
|
||||||
struct CookieIdentityInner {
|
|
||||||
key: Key,
|
|
||||||
key_v2: Key,
|
|
||||||
name: String,
|
|
||||||
path: String,
|
|
||||||
domain: Option<String>,
|
|
||||||
secure: bool,
|
|
||||||
max_age: Option<Duration>,
|
|
||||||
http_only: Option<bool>,
|
|
||||||
same_site: Option<SameSite>,
|
|
||||||
visit_deadline: Option<Duration>,
|
|
||||||
login_deadline: Option<Duration>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug, Deserialize, Serialize)]
|
|
||||||
struct CookieValue {
|
|
||||||
identity: String,
|
|
||||||
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
login_timestamp: Option<SystemTime>,
|
|
||||||
|
|
||||||
#[serde(skip_serializing_if = "Option::is_none")]
|
|
||||||
visit_timestamp: Option<SystemTime>,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Debug)]
|
|
||||||
struct CookieIdentityExtension {
|
|
||||||
login_timestamp: Option<SystemTime>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl CookieIdentityInner {
|
|
||||||
fn new(key: &[u8]) -> CookieIdentityInner {
|
|
||||||
let key_v2: Vec<u8> = [key, &[1, 0, 0, 0]].concat();
|
|
||||||
|
|
||||||
CookieIdentityInner {
|
|
||||||
key: Key::derive_from(key),
|
|
||||||
key_v2: Key::derive_from(&key_v2),
|
|
||||||
name: "actix-identity".to_owned(),
|
|
||||||
path: "/".to_owned(),
|
|
||||||
domain: None,
|
|
||||||
secure: true,
|
|
||||||
max_age: None,
|
|
||||||
http_only: None,
|
|
||||||
same_site: None,
|
|
||||||
visit_deadline: None,
|
|
||||||
login_deadline: None,
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn set_cookie<B>(
|
|
||||||
&self,
|
|
||||||
resp: &mut ServiceResponse<B>,
|
|
||||||
value: Option<CookieValue>,
|
|
||||||
) -> Result<()> {
|
|
||||||
let add_cookie = value.is_some();
|
|
||||||
let val = value
|
|
||||||
.map(|val| {
|
|
||||||
if !self.legacy_supported() {
|
|
||||||
serde_json::to_string(&val)
|
|
||||||
} else {
|
|
||||||
Ok(val.identity)
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.transpose()?;
|
|
||||||
|
|
||||||
let mut cookie = Cookie::new(self.name.clone(), val.unwrap_or_default());
|
|
||||||
cookie.set_path(self.path.clone());
|
|
||||||
cookie.set_secure(self.secure);
|
|
||||||
cookie.set_http_only(true);
|
|
||||||
|
|
||||||
if let Some(ref domain) = self.domain {
|
|
||||||
cookie.set_domain(domain.clone());
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(max_age) = self.max_age {
|
|
||||||
cookie.set_max_age(max_age);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(http_only) = self.http_only {
|
|
||||||
cookie.set_http_only(http_only);
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(same_site) = self.same_site {
|
|
||||||
cookie.set_same_site(same_site);
|
|
||||||
}
|
|
||||||
|
|
||||||
let mut jar = CookieJar::new();
|
|
||||||
|
|
||||||
let key = if self.legacy_supported() {
|
|
||||||
&self.key
|
|
||||||
} else {
|
|
||||||
&self.key_v2
|
|
||||||
};
|
|
||||||
|
|
||||||
if add_cookie {
|
|
||||||
jar.private_mut(key).add(cookie);
|
|
||||||
} else {
|
|
||||||
jar.add_original(cookie.clone());
|
|
||||||
jar.private_mut(key).remove(cookie);
|
|
||||||
}
|
|
||||||
|
|
||||||
for cookie in jar.delta() {
|
|
||||||
let val = HeaderValue::from_str(&cookie.to_string())?;
|
|
||||||
resp.headers_mut().append(header::SET_COOKIE, val);
|
|
||||||
}
|
|
||||||
|
|
||||||
Ok(())
|
|
||||||
}
|
|
||||||
|
|
||||||
fn load(&self, req: &ServiceRequest) -> Option<CookieValue> {
|
|
||||||
let cookie = req.cookie(&self.name)?;
|
|
||||||
let mut jar = CookieJar::new();
|
|
||||||
jar.add_original(cookie.clone());
|
|
||||||
|
|
||||||
let res = if self.legacy_supported() {
|
|
||||||
jar.private_mut(&self.key)
|
|
||||||
.get(&self.name)
|
|
||||||
.map(|n| CookieValue {
|
|
||||||
identity: n.value().to_string(),
|
|
||||||
login_timestamp: None,
|
|
||||||
visit_timestamp: None,
|
|
||||||
})
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
res.or_else(|| {
|
|
||||||
jar.private_mut(&self.key_v2)
|
|
||||||
.get(&self.name)
|
|
||||||
.and_then(|c| self.parse(c))
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
fn parse(&self, cookie: Cookie<'_>) -> Option<CookieValue> {
|
|
||||||
let value: CookieValue = serde_json::from_str(cookie.value()).ok()?;
|
|
||||||
let now = SystemTime::now();
|
|
||||||
|
|
||||||
if let Some(visit_deadline) = self.visit_deadline {
|
|
||||||
let inactivity = now.duration_since(value.visit_timestamp?).ok()?;
|
|
||||||
|
|
||||||
if inactivity > visit_deadline {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
if let Some(login_deadline) = self.login_deadline {
|
|
||||||
let logged_in_dur = now.duration_since(value.login_timestamp?).ok()?;
|
|
||||||
|
|
||||||
if logged_in_dur > login_deadline {
|
|
||||||
return None;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
Some(value)
|
|
||||||
}
|
|
||||||
|
|
||||||
fn legacy_supported(&self) -> bool {
|
|
||||||
self.visit_deadline.is_none() && self.login_deadline.is_none()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn always_update_cookie(&self) -> bool {
|
|
||||||
self.visit_deadline.is_some()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn requires_oob_data(&self) -> bool {
|
|
||||||
self.login_deadline.is_some()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Use cookies for request identity storage.
|
|
||||||
///
|
|
||||||
/// [See this page on MDN](mdn-cookies) for details on cookie attributes.
|
|
||||||
///
|
|
||||||
/// # Examples
|
|
||||||
/// ```
|
|
||||||
/// use actix_web::App;
|
|
||||||
/// use actix_identity::{CookieIdentityPolicy, IdentityService};
|
|
||||||
///
|
|
||||||
/// // create cookie identity backend
|
|
||||||
/// let policy = CookieIdentityPolicy::new(&[0; 32])
|
|
||||||
/// .domain("www.rust-lang.org")
|
|
||||||
/// .name("actix_auth")
|
|
||||||
/// .path("/")
|
|
||||||
/// .secure(true);
|
|
||||||
///
|
|
||||||
/// let app = App::new()
|
|
||||||
/// // wrap policy into identity middleware
|
|
||||||
/// .wrap(IdentityService::new(policy));
|
|
||||||
/// ```
|
|
||||||
///
|
|
||||||
/// [mdn-cookies]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Cookies
|
|
||||||
pub struct CookieIdentityPolicy(Rc<CookieIdentityInner>);
|
|
||||||
|
|
||||||
impl CookieIdentityPolicy {
|
|
||||||
/// Create new `CookieIdentityPolicy` instance.
|
|
||||||
///
|
|
||||||
/// Key argument is the private key for issued cookies. If this value is changed, all issued
|
|
||||||
/// cookie identities are invalidated.
|
|
||||||
///
|
|
||||||
/// # Panics
|
|
||||||
/// Panics if `key` is less than 32 bytes in length..
|
|
||||||
pub fn new(key: &[u8]) -> CookieIdentityPolicy {
|
|
||||||
CookieIdentityPolicy(Rc::new(CookieIdentityInner::new(key)))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets the name of issued cookies.
|
|
||||||
pub fn name(mut self, value: impl Into<String>) -> CookieIdentityPolicy {
|
|
||||||
self.inner_mut().name = value.into();
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets the `Path` attribute of issued cookies.
|
|
||||||
pub fn path(mut self, value: impl Into<String>) -> CookieIdentityPolicy {
|
|
||||||
self.inner_mut().path = value.into();
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets the `Domain` attribute of issued cookies.
|
|
||||||
pub fn domain(mut self, value: impl Into<String>) -> CookieIdentityPolicy {
|
|
||||||
self.inner_mut().domain = Some(value.into());
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets the `Secure` attribute of issued cookies.
|
|
||||||
pub fn secure(mut self, value: bool) -> CookieIdentityPolicy {
|
|
||||||
self.inner_mut().secure = value;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets the `Max-Age` attribute of issued cookies.
|
|
||||||
pub fn max_age(mut self, value: Duration) -> CookieIdentityPolicy {
|
|
||||||
self.inner_mut().max_age = Some(value);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets the `Max-Age` attribute of issued cookies with given number of seconds.
|
|
||||||
pub fn max_age_secs(self, seconds: i64) -> CookieIdentityPolicy {
|
|
||||||
self.max_age(Duration::seconds(seconds))
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets the `HttpOnly` attribute of issued cookies.
|
|
||||||
///
|
|
||||||
/// By default, the `HttpOnly` attribute is omitted from issued cookies.
|
|
||||||
pub fn http_only(mut self, http_only: bool) -> Self {
|
|
||||||
self.inner_mut().http_only = Some(http_only);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Sets the `SameSite` attribute of issued cookies.
|
|
||||||
///
|
|
||||||
/// By default, the `SameSite` attribute is omitted from issued cookies.
|
|
||||||
pub fn same_site(mut self, same_site: SameSite) -> Self {
|
|
||||||
self.inner_mut().same_site = Some(same_site);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Accepts only users who have visited within given deadline.
|
|
||||||
///
|
|
||||||
/// In other words, invalidate a login after some amount of inactivity. Using this feature
|
|
||||||
/// causes updated cookies to be issued on each response in order to record the user's last
|
|
||||||
/// visitation timestamp.
|
|
||||||
///
|
|
||||||
/// By default, visit deadline is disabled.
|
|
||||||
pub fn visit_deadline(mut self, deadline: Duration) -> CookieIdentityPolicy {
|
|
||||||
self.inner_mut().visit_deadline = Some(deadline);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Accepts only users who authenticated within the given deadline.
|
|
||||||
///
|
|
||||||
/// In other words, invalidate a login after some amount of time, regardless of activity.
|
|
||||||
/// While [`Max-Age`](CookieIdentityPolicy::max_age) is useful in constraining the cookie
|
|
||||||
/// lifetime, it could be extended manually; using this feature encodes the deadline directly
|
|
||||||
/// into the issued cookies, making it immutable to users.
|
|
||||||
///
|
|
||||||
/// By default, login deadline is disabled.
|
|
||||||
pub fn login_deadline(mut self, deadline: Duration) -> CookieIdentityPolicy {
|
|
||||||
self.inner_mut().login_deadline = Some(deadline);
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
fn inner_mut(&mut self) -> &mut CookieIdentityInner {
|
|
||||||
Rc::get_mut(&mut self.0).unwrap()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl IdentityPolicy for CookieIdentityPolicy {
|
|
||||||
type Future = Ready<Result<Option<String>, Error>>;
|
|
||||||
type ResponseFuture = Ready<Result<(), Error>>;
|
|
||||||
|
|
||||||
fn from_request(&self, req: &mut ServiceRequest) -> Self::Future {
|
|
||||||
ready(Ok(self.0.load(req).map(|value| {
|
|
||||||
let CookieValue {
|
|
||||||
identity,
|
|
||||||
login_timestamp,
|
|
||||||
..
|
|
||||||
} = value;
|
|
||||||
|
|
||||||
if self.0.requires_oob_data() {
|
|
||||||
req.extensions_mut()
|
|
||||||
.insert(CookieIdentityExtension { login_timestamp });
|
|
||||||
}
|
|
||||||
|
|
||||||
identity
|
|
||||||
})))
|
|
||||||
}
|
|
||||||
|
|
||||||
fn to_response<B>(
|
|
||||||
&self,
|
|
||||||
id: Option<String>,
|
|
||||||
changed: bool,
|
|
||||||
res: &mut ServiceResponse<B>,
|
|
||||||
) -> Self::ResponseFuture {
|
|
||||||
let _ = if changed {
|
|
||||||
let login_timestamp = SystemTime::now();
|
|
||||||
|
|
||||||
self.0.set_cookie(
|
|
||||||
res,
|
|
||||||
id.map(|identity| CookieValue {
|
|
||||||
identity,
|
|
||||||
login_timestamp: self.0.login_deadline.map(|_| login_timestamp),
|
|
||||||
visit_timestamp: self.0.visit_deadline.map(|_| login_timestamp),
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
} else if self.0.always_update_cookie() && id.is_some() {
|
|
||||||
let visit_timestamp = SystemTime::now();
|
|
||||||
|
|
||||||
let login_timestamp = if self.0.requires_oob_data() {
|
|
||||||
let CookieIdentityExtension { login_timestamp } =
|
|
||||||
res.request().extensions_mut().remove().unwrap();
|
|
||||||
|
|
||||||
login_timestamp
|
|
||||||
} else {
|
|
||||||
None
|
|
||||||
};
|
|
||||||
|
|
||||||
self.0.set_cookie(
|
|
||||||
res,
|
|
||||||
Some(CookieValue {
|
|
||||||
identity: id.unwrap(),
|
|
||||||
login_timestamp,
|
|
||||||
visit_timestamp: self.0.visit_deadline.map(|_| visit_timestamp),
|
|
||||||
}),
|
|
||||||
)
|
|
||||||
} else {
|
|
||||||
Ok(())
|
|
||||||
};
|
|
||||||
|
|
||||||
ready(Ok(()))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use std::{borrow::Borrow, time::SystemTime};
|
|
||||||
|
|
||||||
use actix_web::{
|
|
||||||
body::{BoxBody, EitherBody},
|
|
||||||
cookie::{Cookie, CookieJar, Key, SameSite},
|
|
||||||
dev::ServiceResponse,
|
|
||||||
http::{header, StatusCode},
|
|
||||||
test::{self, TestRequest},
|
|
||||||
web, App, HttpResponse,
|
|
||||||
};
|
|
||||||
use time::Duration;
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
use crate::{tests::*, Identity, IdentityService};
|
|
||||||
|
|
||||||
fn login_cookie(
|
|
||||||
identity: &'static str,
|
|
||||||
login_timestamp: Option<SystemTime>,
|
|
||||||
visit_timestamp: Option<SystemTime>,
|
|
||||||
) -> Cookie<'static> {
|
|
||||||
let mut jar = CookieJar::new();
|
|
||||||
let key: Vec<u8> = COOKIE_KEY_MASTER
|
|
||||||
.iter()
|
|
||||||
.chain([1, 0, 0, 0].iter())
|
|
||||||
.copied()
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
jar.private_mut(&Key::derive_from(&key)).add(Cookie::new(
|
|
||||||
COOKIE_NAME,
|
|
||||||
serde_json::to_string(&CookieValue {
|
|
||||||
identity: identity.to_string(),
|
|
||||||
login_timestamp,
|
|
||||||
visit_timestamp,
|
|
||||||
})
|
|
||||||
.unwrap(),
|
|
||||||
));
|
|
||||||
|
|
||||||
jar.get(COOKIE_NAME).unwrap().clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
fn assert_login_cookie(
|
|
||||||
response: &mut ServiceResponse<EitherBody<BoxBody>>,
|
|
||||||
identity: &str,
|
|
||||||
login_timestamp: LoginTimestampCheck,
|
|
||||||
visit_timestamp: VisitTimeStampCheck,
|
|
||||||
) {
|
|
||||||
let mut cookies = CookieJar::new();
|
|
||||||
|
|
||||||
for cookie in response.headers().get_all(header::SET_COOKIE) {
|
|
||||||
cookies.add(Cookie::parse(cookie.to_str().unwrap().to_string()).unwrap());
|
|
||||||
}
|
|
||||||
|
|
||||||
let key: Vec<u8> = COOKIE_KEY_MASTER
|
|
||||||
.iter()
|
|
||||||
.chain([1, 0, 0, 0].iter())
|
|
||||||
.copied()
|
|
||||||
.collect();
|
|
||||||
|
|
||||||
let cookie = cookies
|
|
||||||
.private(&Key::derive_from(&key))
|
|
||||||
.get(COOKIE_NAME)
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
let cv: CookieValue = serde_json::from_str(cookie.value()).unwrap();
|
|
||||||
assert_eq!(cv.identity, identity);
|
|
||||||
|
|
||||||
let now = SystemTime::now();
|
|
||||||
let t30sec_ago = now - Duration::seconds(30);
|
|
||||||
|
|
||||||
match login_timestamp {
|
|
||||||
LoginTimestampCheck::NoTimestamp => assert_eq!(cv.login_timestamp, None),
|
|
||||||
LoginTimestampCheck::NewTimestamp => assert!(
|
|
||||||
t30sec_ago <= cv.login_timestamp.unwrap() && cv.login_timestamp.unwrap() <= now
|
|
||||||
),
|
|
||||||
LoginTimestampCheck::OldTimestamp(old_timestamp) => {
|
|
||||||
assert_eq!(cv.login_timestamp, Some(old_timestamp))
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
match visit_timestamp {
|
|
||||||
VisitTimeStampCheck::NoTimestamp => assert_eq!(cv.visit_timestamp, None),
|
|
||||||
VisitTimeStampCheck::NewTimestamp => assert!(
|
|
||||||
t30sec_ago <= cv.visit_timestamp.unwrap() && cv.visit_timestamp.unwrap() <= now
|
|
||||||
),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[actix_web::test]
|
|
||||||
async fn test_identity_flow() {
|
|
||||||
let srv = test::init_service(
|
|
||||||
App::new()
|
|
||||||
.wrap(IdentityService::new(
|
|
||||||
CookieIdentityPolicy::new(&COOKIE_KEY_MASTER)
|
|
||||||
.domain("www.rust-lang.org")
|
|
||||||
.name(COOKIE_NAME)
|
|
||||||
.path("/")
|
|
||||||
.secure(true),
|
|
||||||
))
|
|
||||||
.service(web::resource("/index").to(|id: Identity| {
|
|
||||||
if id.identity().is_some() {
|
|
||||||
HttpResponse::Created()
|
|
||||||
} else {
|
|
||||||
HttpResponse::Ok()
|
|
||||||
}
|
|
||||||
}))
|
|
||||||
.service(web::resource("/login").to(|id: Identity| {
|
|
||||||
id.remember(COOKIE_LOGIN.to_string());
|
|
||||||
HttpResponse::Ok()
|
|
||||||
}))
|
|
||||||
.service(web::resource("/logout").to(|id: Identity| {
|
|
||||||
if id.identity().is_some() {
|
|
||||||
id.forget();
|
|
||||||
HttpResponse::Ok()
|
|
||||||
} else {
|
|
||||||
HttpResponse::BadRequest()
|
|
||||||
}
|
|
||||||
})),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
let resp = test::call_service(&srv, TestRequest::with_uri("/index").to_request()).await;
|
|
||||||
assert_eq!(resp.status(), StatusCode::OK);
|
|
||||||
|
|
||||||
let resp = test::call_service(&srv, TestRequest::with_uri("/login").to_request()).await;
|
|
||||||
assert_eq!(resp.status(), StatusCode::OK);
|
|
||||||
let c = resp.response().cookies().next().unwrap().to_owned();
|
|
||||||
|
|
||||||
let resp = test::call_service(
|
|
||||||
&srv,
|
|
||||||
TestRequest::with_uri("/index")
|
|
||||||
.cookie(c.clone())
|
|
||||||
.to_request(),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
assert_eq!(resp.status(), StatusCode::CREATED);
|
|
||||||
|
|
||||||
let resp = test::call_service(
|
|
||||||
&srv,
|
|
||||||
TestRequest::with_uri("/logout")
|
|
||||||
.cookie(c.clone())
|
|
||||||
.to_request(),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
assert_eq!(resp.status(), StatusCode::OK);
|
|
||||||
assert!(resp.headers().contains_key(header::SET_COOKIE))
|
|
||||||
}
|
|
||||||
|
|
||||||
#[actix_web::test]
|
|
||||||
async fn test_identity_max_age_time() {
|
|
||||||
let duration = Duration::days(1);
|
|
||||||
|
|
||||||
let srv = test::init_service(
|
|
||||||
App::new()
|
|
||||||
.wrap(IdentityService::new(
|
|
||||||
CookieIdentityPolicy::new(&COOKIE_KEY_MASTER)
|
|
||||||
.domain("www.rust-lang.org")
|
|
||||||
.name(COOKIE_NAME)
|
|
||||||
.path("/")
|
|
||||||
.max_age(duration)
|
|
||||||
.secure(true),
|
|
||||||
))
|
|
||||||
.service(web::resource("/login").to(|id: Identity| {
|
|
||||||
id.remember("test".to_string());
|
|
||||||
HttpResponse::Ok()
|
|
||||||
})),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let resp = test::call_service(&srv, TestRequest::with_uri("/login").to_request()).await;
|
|
||||||
assert_eq!(resp.status(), StatusCode::OK);
|
|
||||||
assert!(resp.headers().contains_key(header::SET_COOKIE));
|
|
||||||
let c = resp.response().cookies().next().unwrap().to_owned();
|
|
||||||
assert_eq!(duration, c.max_age().unwrap());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[actix_web::test]
|
|
||||||
async fn test_http_only_same_site() {
|
|
||||||
let srv = test::init_service(
|
|
||||||
App::new()
|
|
||||||
.wrap(IdentityService::new(
|
|
||||||
CookieIdentityPolicy::new(&COOKIE_KEY_MASTER)
|
|
||||||
.domain("www.rust-lang.org")
|
|
||||||
.name(COOKIE_NAME)
|
|
||||||
.path("/")
|
|
||||||
.http_only(true)
|
|
||||||
.same_site(SameSite::None),
|
|
||||||
))
|
|
||||||
.service(web::resource("/login").to(|id: Identity| {
|
|
||||||
id.remember("test".to_string());
|
|
||||||
HttpResponse::Ok()
|
|
||||||
})),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
|
|
||||||
let resp = test::call_service(&srv, TestRequest::with_uri("/login").to_request()).await;
|
|
||||||
|
|
||||||
assert_eq!(resp.status(), StatusCode::OK);
|
|
||||||
assert!(resp.headers().contains_key(header::SET_COOKIE));
|
|
||||||
|
|
||||||
let c = resp.response().cookies().next().unwrap().to_owned();
|
|
||||||
assert!(c.http_only().unwrap());
|
|
||||||
assert_eq!(SameSite::None, c.same_site().unwrap());
|
|
||||||
}
|
|
||||||
|
|
||||||
fn legacy_login_cookie(identity: &'static str) -> Cookie<'static> {
|
|
||||||
let mut jar = CookieJar::new();
|
|
||||||
jar.private_mut(&Key::derive_from(&COOKIE_KEY_MASTER))
|
|
||||||
.add(Cookie::new(COOKIE_NAME, identity));
|
|
||||||
jar.get(COOKIE_NAME).unwrap().clone()
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn assert_logged_in(
|
|
||||||
response: ServiceResponse<EitherBody<BoxBody>>,
|
|
||||||
identity: Option<&str>,
|
|
||||||
) {
|
|
||||||
let bytes = test::read_body(response).await;
|
|
||||||
let resp: Option<String> = serde_json::from_slice(&bytes[..]).unwrap();
|
|
||||||
assert_eq!(resp.as_ref().map(|s| s.borrow()), identity);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn assert_legacy_login_cookie(
|
|
||||||
response: &mut ServiceResponse<EitherBody<BoxBody>>,
|
|
||||||
identity: &str,
|
|
||||||
) {
|
|
||||||
let mut cookies = CookieJar::new();
|
|
||||||
for cookie in response.headers().get_all(header::SET_COOKIE) {
|
|
||||||
cookies.add(Cookie::parse(cookie.to_str().unwrap().to_string()).unwrap());
|
|
||||||
}
|
|
||||||
let cookie = cookies
|
|
||||||
.private_mut(&Key::derive_from(&COOKIE_KEY_MASTER))
|
|
||||||
.get(COOKIE_NAME)
|
|
||||||
.unwrap();
|
|
||||||
assert_eq!(cookie.value(), identity);
|
|
||||||
}
|
|
||||||
|
|
||||||
fn assert_no_login_cookie(response: &mut ServiceResponse<EitherBody<BoxBody>>) {
|
|
||||||
let mut cookies = CookieJar::new();
|
|
||||||
for cookie in response.headers().get_all(header::SET_COOKIE) {
|
|
||||||
cookies.add(Cookie::parse(cookie.to_str().unwrap().to_string()).unwrap());
|
|
||||||
}
|
|
||||||
assert!(cookies.get(COOKIE_NAME).is_none());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[actix_web::test]
|
|
||||||
async fn test_identity_max_age() {
|
|
||||||
let seconds = 60;
|
|
||||||
let srv = test::init_service(
|
|
||||||
App::new()
|
|
||||||
.wrap(IdentityService::new(
|
|
||||||
CookieIdentityPolicy::new(&COOKIE_KEY_MASTER)
|
|
||||||
.domain("www.rust-lang.org")
|
|
||||||
.name(COOKIE_NAME)
|
|
||||||
.path("/")
|
|
||||||
.max_age_secs(seconds)
|
|
||||||
.secure(true),
|
|
||||||
))
|
|
||||||
.service(web::resource("/login").to(|id: Identity| {
|
|
||||||
id.remember("test".to_string());
|
|
||||||
HttpResponse::Ok()
|
|
||||||
})),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
let resp = test::call_service(&srv, TestRequest::with_uri("/login").to_request()).await;
|
|
||||||
assert_eq!(resp.status(), StatusCode::OK);
|
|
||||||
assert!(resp.headers().contains_key(header::SET_COOKIE));
|
|
||||||
let c = resp.response().cookies().next().unwrap().to_owned();
|
|
||||||
assert_eq!(Duration::seconds(seconds as i64), c.max_age().unwrap());
|
|
||||||
}
|
|
||||||
|
|
||||||
#[actix_web::test]
|
|
||||||
async fn test_identity_legacy_cookie_is_set() {
|
|
||||||
let srv = create_identity_server(|c| c).await;
|
|
||||||
let mut resp = test::call_service(&srv, TestRequest::with_uri("/").to_request()).await;
|
|
||||||
assert_legacy_login_cookie(&mut resp, COOKIE_LOGIN);
|
|
||||||
assert_logged_in(resp, None).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[actix_web::test]
|
|
||||||
async fn test_identity_legacy_cookie_works() {
|
|
||||||
let srv = create_identity_server(|c| c).await;
|
|
||||||
let cookie = legacy_login_cookie(COOKIE_LOGIN);
|
|
||||||
let mut resp = test::call_service(
|
|
||||||
&srv,
|
|
||||||
TestRequest::with_uri("/")
|
|
||||||
.cookie(cookie.clone())
|
|
||||||
.to_request(),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
assert_no_login_cookie(&mut resp);
|
|
||||||
assert_logged_in(resp, Some(COOKIE_LOGIN)).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[actix_web::test]
|
|
||||||
async fn test_identity_legacy_cookie_rejected_if_visit_timestamp_needed() {
|
|
||||||
let srv = create_identity_server(|c| c.visit_deadline(Duration::days(90))).await;
|
|
||||||
let cookie = legacy_login_cookie(COOKIE_LOGIN);
|
|
||||||
let mut resp = test::call_service(
|
|
||||||
&srv,
|
|
||||||
TestRequest::with_uri("/")
|
|
||||||
.cookie(cookie.clone())
|
|
||||||
.to_request(),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
assert_login_cookie(
|
|
||||||
&mut resp,
|
|
||||||
COOKIE_LOGIN,
|
|
||||||
LoginTimestampCheck::NoTimestamp,
|
|
||||||
VisitTimeStampCheck::NewTimestamp,
|
|
||||||
);
|
|
||||||
assert_logged_in(resp, None).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[actix_web::test]
|
|
||||||
async fn test_identity_legacy_cookie_rejected_if_login_timestamp_needed() {
|
|
||||||
let srv = create_identity_server(|c| c.login_deadline(Duration::days(90))).await;
|
|
||||||
let cookie = legacy_login_cookie(COOKIE_LOGIN);
|
|
||||||
let mut resp = test::call_service(
|
|
||||||
&srv,
|
|
||||||
TestRequest::with_uri("/")
|
|
||||||
.cookie(cookie.clone())
|
|
||||||
.to_request(),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
assert_login_cookie(
|
|
||||||
&mut resp,
|
|
||||||
COOKIE_LOGIN,
|
|
||||||
LoginTimestampCheck::NewTimestamp,
|
|
||||||
VisitTimeStampCheck::NoTimestamp,
|
|
||||||
);
|
|
||||||
assert_logged_in(resp, None).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[actix_web::test]
|
|
||||||
async fn test_identity_cookie_rejected_if_login_timestamp_needed() {
|
|
||||||
let srv = create_identity_server(|c| c.login_deadline(Duration::days(90))).await;
|
|
||||||
let cookie = login_cookie(COOKIE_LOGIN, None, Some(SystemTime::now()));
|
|
||||||
let mut resp = test::call_service(
|
|
||||||
&srv,
|
|
||||||
TestRequest::with_uri("/")
|
|
||||||
.cookie(cookie.clone())
|
|
||||||
.to_request(),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
assert_login_cookie(
|
|
||||||
&mut resp,
|
|
||||||
COOKIE_LOGIN,
|
|
||||||
LoginTimestampCheck::NewTimestamp,
|
|
||||||
VisitTimeStampCheck::NoTimestamp,
|
|
||||||
);
|
|
||||||
assert_logged_in(resp, None).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[actix_web::test]
|
|
||||||
async fn test_identity_cookie_rejected_if_visit_timestamp_needed() {
|
|
||||||
let srv = create_identity_server(|c| c.visit_deadline(Duration::days(90))).await;
|
|
||||||
let cookie = login_cookie(COOKIE_LOGIN, Some(SystemTime::now()), None);
|
|
||||||
let mut resp = test::call_service(
|
|
||||||
&srv,
|
|
||||||
TestRequest::with_uri("/")
|
|
||||||
.cookie(cookie.clone())
|
|
||||||
.to_request(),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
assert_login_cookie(
|
|
||||||
&mut resp,
|
|
||||||
COOKIE_LOGIN,
|
|
||||||
LoginTimestampCheck::NoTimestamp,
|
|
||||||
VisitTimeStampCheck::NewTimestamp,
|
|
||||||
);
|
|
||||||
assert_logged_in(resp, None).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[actix_web::test]
|
|
||||||
async fn test_identity_cookie_rejected_if_login_timestamp_too_old() {
|
|
||||||
let srv = create_identity_server(|c| c.login_deadline(Duration::days(90))).await;
|
|
||||||
let cookie = login_cookie(
|
|
||||||
COOKIE_LOGIN,
|
|
||||||
Some(SystemTime::now() - Duration::days(180)),
|
|
||||||
None,
|
|
||||||
);
|
|
||||||
let mut resp = test::call_service(
|
|
||||||
&srv,
|
|
||||||
TestRequest::with_uri("/")
|
|
||||||
.cookie(cookie.clone())
|
|
||||||
.to_request(),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
assert_login_cookie(
|
|
||||||
&mut resp,
|
|
||||||
COOKIE_LOGIN,
|
|
||||||
LoginTimestampCheck::NewTimestamp,
|
|
||||||
VisitTimeStampCheck::NoTimestamp,
|
|
||||||
);
|
|
||||||
assert_logged_in(resp, None).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[actix_web::test]
|
|
||||||
async fn test_identity_cookie_rejected_if_visit_timestamp_too_old() {
|
|
||||||
let srv = create_identity_server(|c| c.visit_deadline(Duration::days(90))).await;
|
|
||||||
let cookie = login_cookie(
|
|
||||||
COOKIE_LOGIN,
|
|
||||||
None,
|
|
||||||
Some(SystemTime::now() - Duration::days(180)),
|
|
||||||
);
|
|
||||||
let mut resp = test::call_service(
|
|
||||||
&srv,
|
|
||||||
TestRequest::with_uri("/")
|
|
||||||
.cookie(cookie.clone())
|
|
||||||
.to_request(),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
assert_login_cookie(
|
|
||||||
&mut resp,
|
|
||||||
COOKIE_LOGIN,
|
|
||||||
LoginTimestampCheck::NoTimestamp,
|
|
||||||
VisitTimeStampCheck::NewTimestamp,
|
|
||||||
);
|
|
||||||
assert_logged_in(resp, None).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[actix_web::test]
|
|
||||||
async fn test_identity_cookie_not_updated_on_login_deadline() {
|
|
||||||
let srv = create_identity_server(|c| c.login_deadline(Duration::days(90))).await;
|
|
||||||
let cookie = login_cookie(COOKIE_LOGIN, Some(SystemTime::now()), None);
|
|
||||||
let mut resp = test::call_service(
|
|
||||||
&srv,
|
|
||||||
TestRequest::with_uri("/")
|
|
||||||
.cookie(cookie.clone())
|
|
||||||
.to_request(),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
assert_no_login_cookie(&mut resp);
|
|
||||||
assert_logged_in(resp, Some(COOKIE_LOGIN)).await;
|
|
||||||
}
|
|
||||||
|
|
||||||
#[actix_web::test]
|
|
||||||
async fn test_identity_cookie_updated_on_visit_deadline() {
|
|
||||||
let srv = create_identity_server(|c| {
|
|
||||||
c.visit_deadline(Duration::days(90))
|
|
||||||
.login_deadline(Duration::days(90))
|
|
||||||
})
|
|
||||||
.await;
|
|
||||||
let timestamp = SystemTime::now() - Duration::days(1);
|
|
||||||
let cookie = login_cookie(COOKIE_LOGIN, Some(timestamp), Some(timestamp));
|
|
||||||
let mut resp = test::call_service(
|
|
||||||
&srv,
|
|
||||||
TestRequest::with_uri("/")
|
|
||||||
.cookie(cookie.clone())
|
|
||||||
.to_request(),
|
|
||||||
)
|
|
||||||
.await;
|
|
||||||
assert_login_cookie(
|
|
||||||
&mut resp,
|
|
||||||
COOKIE_LOGIN,
|
|
||||||
LoginTimestampCheck::OldTimestamp(timestamp),
|
|
||||||
VisitTimeStampCheck::NewTimestamp,
|
|
||||||
);
|
|
||||||
assert_logged_in(resp, Some(COOKIE_LOGIN)).await;
|
|
||||||
}
|
|
||||||
}
|
|
70
actix-identity/src/error.rs
Normal file
70
actix-identity/src/error.rs
Normal file
@ -0,0 +1,70 @@
|
|||||||
|
//! Failure modes of identity operations.
|
||||||
|
|
||||||
|
use actix_session::{SessionGetError, SessionInsertError};
|
||||||
|
use actix_web::{cookie::time::error::ComponentRange, http::StatusCode, ResponseError};
|
||||||
|
use derive_more::derive::{Display, Error, From};
|
||||||
|
|
||||||
|
/// Error that can occur during login attempts.
|
||||||
|
#[derive(Debug, Display, Error, From)]
|
||||||
|
#[display("{_0}")]
|
||||||
|
pub struct LoginError(SessionInsertError);
|
||||||
|
|
||||||
|
impl ResponseError for LoginError {
|
||||||
|
fn status_code(&self) -> StatusCode {
|
||||||
|
StatusCode::UNAUTHORIZED
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Error encountered when working with a session that has expired.
|
||||||
|
#[derive(Debug, Display, Error)]
|
||||||
|
#[display("The given session has expired and is no longer valid")]
|
||||||
|
pub struct SessionExpiryError(#[error(not(source))] pub(crate) ComponentRange);
|
||||||
|
|
||||||
|
/// The identity information has been lost.
|
||||||
|
///
|
||||||
|
/// Seeing this error in user code indicates a bug in actix-identity.
|
||||||
|
#[derive(Debug, Display, Error)]
|
||||||
|
#[display(
|
||||||
|
"The identity information in the current session has disappeared after having been \
|
||||||
|
successfully validated. This is likely to be a bug."
|
||||||
|
)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub struct LostIdentityError;
|
||||||
|
|
||||||
|
/// There is no identity information attached to the current session.
|
||||||
|
#[derive(Debug, Display, Error)]
|
||||||
|
#[display("There is no identity information attached to the current session")]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub struct MissingIdentityError;
|
||||||
|
|
||||||
|
/// Errors that can occur while retrieving an identity.
|
||||||
|
#[derive(Debug, Display, Error, From)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub enum GetIdentityError {
|
||||||
|
/// The session has expired.
|
||||||
|
#[display("{_0}")]
|
||||||
|
SessionExpiryError(SessionExpiryError),
|
||||||
|
|
||||||
|
/// No identity is found in a session.
|
||||||
|
#[display("{_0}")]
|
||||||
|
MissingIdentityError(MissingIdentityError),
|
||||||
|
|
||||||
|
/// Failed to accessing the session store.
|
||||||
|
#[display("{_0}")]
|
||||||
|
SessionGetError(SessionGetError),
|
||||||
|
|
||||||
|
/// Identity info was lost after being validated.
|
||||||
|
///
|
||||||
|
/// Seeing this error indicates a bug in actix-identity.
|
||||||
|
#[display("{_0}")]
|
||||||
|
LostIdentityError(LostIdentityError),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ResponseError for GetIdentityError {
|
||||||
|
fn status_code(&self) -> StatusCode {
|
||||||
|
match self {
|
||||||
|
Self::LostIdentityError(_) => StatusCode::INTERNAL_SERVER_ERROR,
|
||||||
|
_ => StatusCode::UNAUTHORIZED,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
@ -1,89 +1,254 @@
|
|||||||
|
use actix_session::Session;
|
||||||
use actix_utils::future::{ready, Ready};
|
use actix_utils::future::{ready, Ready};
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
|
cookie::time::OffsetDateTime,
|
||||||
dev::{Extensions, Payload},
|
dev::{Extensions, Payload},
|
||||||
Error, FromRequest, HttpMessage as _, HttpRequest,
|
http::StatusCode,
|
||||||
|
Error, FromRequest, HttpMessage, HttpRequest, HttpResponse,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub(crate) struct IdentityItem {
|
use crate::{
|
||||||
pub(crate) id: Option<String>,
|
config::LogoutBehaviour,
|
||||||
pub(crate) changed: bool,
|
error::{
|
||||||
}
|
GetIdentityError, LoginError, LostIdentityError, MissingIdentityError, SessionExpiryError,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
/// The extractor type to obtain your identity from a request.
|
/// A verified user identity. It can be used as a request extractor.
|
||||||
///
|
///
|
||||||
|
/// The lifecycle of a user identity is tied to the lifecycle of the underlying session. If the
|
||||||
|
/// session is destroyed (e.g. the session expired), the user identity will be forgotten, de-facto
|
||||||
|
/// forcing a user log out.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
/// ```
|
/// ```
|
||||||
/// use actix_web::*;
|
/// use actix_web::{
|
||||||
|
/// get, post, Responder, HttpRequest, HttpMessage, HttpResponse
|
||||||
|
/// };
|
||||||
/// use actix_identity::Identity;
|
/// use actix_identity::Identity;
|
||||||
///
|
///
|
||||||
/// #[get("/")]
|
/// #[get("/")]
|
||||||
/// async fn index(id: Identity) -> impl Responder {
|
/// async fn index(user: Option<Identity>) -> impl Responder {
|
||||||
/// // access request identity
|
/// if let Some(user) = user {
|
||||||
/// if let Some(id) = id.identity() {
|
/// format!("Welcome! {}", user.id().unwrap())
|
||||||
/// format!("Welcome! {}", id)
|
|
||||||
/// } else {
|
/// } else {
|
||||||
/// "Welcome Anonymous!".to_owned()
|
/// "Welcome Anonymous!".to_owned()
|
||||||
/// }
|
/// }
|
||||||
/// }
|
/// }
|
||||||
///
|
///
|
||||||
/// #[post("/login")]
|
/// #[post("/login")]
|
||||||
/// async fn login(id: Identity) -> impl Responder {
|
/// async fn login(request: HttpRequest) -> impl Responder {
|
||||||
/// // remember identity
|
/// Identity::login(&request.extensions(), "User1".into());
|
||||||
/// id.remember("User1".to_owned());
|
|
||||||
///
|
|
||||||
/// HttpResponse::Ok()
|
/// HttpResponse::Ok()
|
||||||
/// }
|
/// }
|
||||||
///
|
///
|
||||||
/// #[post("/logout")]
|
/// #[post("/logout")]
|
||||||
/// async fn logout(id: Identity) -> impl Responder {
|
/// async fn logout(user: Identity) -> impl Responder {
|
||||||
/// // remove identity
|
/// user.logout();
|
||||||
/// id.forget();
|
|
||||||
///
|
|
||||||
/// HttpResponse::Ok()
|
/// HttpResponse::Ok()
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
#[derive(Clone)]
|
|
||||||
pub struct Identity(HttpRequest);
|
|
||||||
|
|
||||||
impl Identity {
|
|
||||||
/// Return the claimed identity of the user associated request or `None` if no identity can be
|
|
||||||
/// found associated with the request.
|
|
||||||
pub fn identity(&self) -> Option<String> {
|
|
||||||
Identity::get_identity(&self.0.extensions())
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Remember identity.
|
|
||||||
pub fn remember(&self, identity: String) {
|
|
||||||
if let Some(id) = self.0.extensions_mut().get_mut::<IdentityItem>() {
|
|
||||||
id.id = Some(identity);
|
|
||||||
id.changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// This method is used to 'forget' the current identity on subsequent requests.
|
|
||||||
pub fn forget(&self) {
|
|
||||||
if let Some(id) = self.0.extensions_mut().get_mut::<IdentityItem>() {
|
|
||||||
id.id = None;
|
|
||||||
id.changed = true;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) fn get_identity(extensions: &Extensions) -> Option<String> {
|
|
||||||
let id = extensions.get::<IdentityItem>()?;
|
|
||||||
id.id.clone()
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Extractor implementation for Identity type.
|
|
||||||
///
|
///
|
||||||
|
/// # Extractor Behaviour
|
||||||
|
/// What happens if you try to extract an `Identity` out of a request that does not have a valid
|
||||||
|
/// identity attached? The API will return a `401 UNAUTHORIZED` to the caller.
|
||||||
|
///
|
||||||
|
/// If you want to customise this behaviour, consider extracting `Option<Identity>` or
|
||||||
|
/// `Result<Identity, actix_web::Error>` instead of a bare `Identity`: you will then be fully in
|
||||||
|
/// control of the error path.
|
||||||
|
///
|
||||||
|
/// ## Examples
|
||||||
/// ```
|
/// ```
|
||||||
/// # use actix_web::*;
|
/// use actix_web::{http::header::LOCATION, get, HttpResponse, Responder};
|
||||||
/// use actix_identity::Identity;
|
/// use actix_identity::Identity;
|
||||||
///
|
///
|
||||||
/// #[get("/")]
|
/// #[get("/")]
|
||||||
/// async fn index(id: Identity) -> impl Responder {
|
/// async fn index(user: Option<Identity>) -> impl Responder {
|
||||||
/// // access request identity
|
/// if let Some(user) = user {
|
||||||
/// if let Some(id) = id.identity() {
|
/// HttpResponse::Ok().finish()
|
||||||
/// format!("Welcome! {}", id)
|
/// } else {
|
||||||
|
/// // Redirect to login page if unauthenticated
|
||||||
|
/// HttpResponse::TemporaryRedirect()
|
||||||
|
/// .insert_header((LOCATION, "/login"))
|
||||||
|
/// .finish()
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
pub struct Identity(IdentityInner);
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub(crate) struct IdentityInner {
|
||||||
|
pub(crate) session: Session,
|
||||||
|
pub(crate) logout_behaviour: LogoutBehaviour,
|
||||||
|
pub(crate) is_login_deadline_enabled: bool,
|
||||||
|
pub(crate) is_visit_deadline_enabled: bool,
|
||||||
|
pub(crate) id_key: &'static str,
|
||||||
|
pub(crate) last_visit_unix_timestamp_key: &'static str,
|
||||||
|
pub(crate) login_unix_timestamp_key: &'static str,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IdentityInner {
|
||||||
|
fn extract(ext: &Extensions) -> Self {
|
||||||
|
ext.get::<Self>()
|
||||||
|
.expect(
|
||||||
|
"No `IdentityInner` instance was found in the extensions attached to the \
|
||||||
|
incoming request. This usually means that `IdentityMiddleware` has not been \
|
||||||
|
registered as an application middleware via `App::wrap`. `Identity` cannot be used \
|
||||||
|
unless the identity machine is properly mounted: register `IdentityMiddleware` as \
|
||||||
|
a middleware for your application to fix this panic. If the problem persists, \
|
||||||
|
please file an issue on GitHub.",
|
||||||
|
)
|
||||||
|
.to_owned()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Retrieve the user id attached to the current session.
|
||||||
|
fn get_identity(&self) -> Result<String, GetIdentityError> {
|
||||||
|
self.session
|
||||||
|
.get::<String>(self.id_key)?
|
||||||
|
.ok_or_else(|| MissingIdentityError.into())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Identity {
|
||||||
|
/// Return the user id associated to the current session.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
/// ```
|
||||||
|
/// use actix_web::{get, Responder};
|
||||||
|
/// use actix_identity::Identity;
|
||||||
|
///
|
||||||
|
/// #[get("/")]
|
||||||
|
/// async fn index(user: Option<Identity>) -> impl Responder {
|
||||||
|
/// if let Some(user) = user {
|
||||||
|
/// format!("Welcome! {}", user.id().unwrap())
|
||||||
|
/// } else {
|
||||||
|
/// "Welcome Anonymous!".to_owned()
|
||||||
|
/// }
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
pub fn id(&self) -> Result<String, GetIdentityError> {
|
||||||
|
self.0
|
||||||
|
.session
|
||||||
|
.get(self.0.id_key)?
|
||||||
|
.ok_or_else(|| LostIdentityError.into())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Attach a valid user identity to the current session.
|
||||||
|
///
|
||||||
|
/// This method should be called after you have successfully authenticated the user. After
|
||||||
|
/// `login` has been called, the user will be able to access all routes that require a valid
|
||||||
|
/// [`Identity`].
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
/// ```
|
||||||
|
/// use actix_web::{post, Responder, HttpRequest, HttpMessage, HttpResponse};
|
||||||
|
/// use actix_identity::Identity;
|
||||||
|
///
|
||||||
|
/// #[post("/login")]
|
||||||
|
/// async fn login(request: HttpRequest) -> impl Responder {
|
||||||
|
/// Identity::login(&request.extensions(), "User1".into());
|
||||||
|
/// HttpResponse::Ok()
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
pub fn login(ext: &Extensions, id: String) -> Result<Self, LoginError> {
|
||||||
|
let inner = IdentityInner::extract(ext);
|
||||||
|
inner.session.insert(inner.id_key, id)?;
|
||||||
|
let now = OffsetDateTime::now_utc().unix_timestamp();
|
||||||
|
if inner.is_login_deadline_enabled {
|
||||||
|
inner.session.insert(inner.login_unix_timestamp_key, now)?;
|
||||||
|
}
|
||||||
|
if inner.is_visit_deadline_enabled {
|
||||||
|
inner
|
||||||
|
.session
|
||||||
|
.insert(inner.last_visit_unix_timestamp_key, now)?;
|
||||||
|
}
|
||||||
|
inner.session.renew();
|
||||||
|
Ok(Self(inner))
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Remove the user identity from the current session.
|
||||||
|
///
|
||||||
|
/// After `logout` has been called, the user will no longer be able to access routes that
|
||||||
|
/// require a valid [`Identity`].
|
||||||
|
///
|
||||||
|
/// The behaviour on logout is determined by [`IdentityMiddlewareBuilder::logout_behaviour`].
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
/// ```
|
||||||
|
/// use actix_web::{post, Responder, HttpResponse};
|
||||||
|
/// use actix_identity::Identity;
|
||||||
|
///
|
||||||
|
/// #[post("/logout")]
|
||||||
|
/// async fn logout(user: Identity) -> impl Responder {
|
||||||
|
/// user.logout();
|
||||||
|
/// HttpResponse::Ok()
|
||||||
|
/// }
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// [`IdentityMiddlewareBuilder::logout_behaviour`]: crate::config::IdentityMiddlewareBuilder::logout_behaviour
|
||||||
|
pub fn logout(self) {
|
||||||
|
match self.0.logout_behaviour {
|
||||||
|
LogoutBehaviour::PurgeSession => {
|
||||||
|
self.0.session.purge();
|
||||||
|
}
|
||||||
|
LogoutBehaviour::DeleteIdentityKeys => {
|
||||||
|
self.0.session.remove(self.0.id_key);
|
||||||
|
if self.0.is_login_deadline_enabled {
|
||||||
|
self.0.session.remove(self.0.login_unix_timestamp_key);
|
||||||
|
}
|
||||||
|
if self.0.is_visit_deadline_enabled {
|
||||||
|
self.0.session.remove(self.0.last_visit_unix_timestamp_key);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn extract(ext: &Extensions) -> Result<Self, GetIdentityError> {
|
||||||
|
let inner = IdentityInner::extract(ext);
|
||||||
|
inner.get_identity()?;
|
||||||
|
Ok(Self(inner))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn logged_at(&self) -> Result<Option<OffsetDateTime>, GetIdentityError> {
|
||||||
|
Ok(self
|
||||||
|
.0
|
||||||
|
.session
|
||||||
|
.get(self.0.login_unix_timestamp_key)?
|
||||||
|
.map(OffsetDateTime::from_unix_timestamp)
|
||||||
|
.transpose()
|
||||||
|
.map_err(SessionExpiryError)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn last_visited_at(&self) -> Result<Option<OffsetDateTime>, GetIdentityError> {
|
||||||
|
Ok(self
|
||||||
|
.0
|
||||||
|
.session
|
||||||
|
.get(self.0.last_visit_unix_timestamp_key)?
|
||||||
|
.map(OffsetDateTime::from_unix_timestamp)
|
||||||
|
.transpose()
|
||||||
|
.map_err(SessionExpiryError)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn set_last_visited_at(&self) -> Result<(), LoginError> {
|
||||||
|
let now = OffsetDateTime::now_utc().unix_timestamp();
|
||||||
|
self.0
|
||||||
|
.session
|
||||||
|
.insert(self.0.last_visit_unix_timestamp_key, now)?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extractor implementation for [`Identity`].
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
/// ```
|
||||||
|
/// use actix_web::{get, Responder};
|
||||||
|
/// use actix_identity::Identity;
|
||||||
|
///
|
||||||
|
/// #[get("/")]
|
||||||
|
/// async fn index(user: Option<Identity>) -> impl Responder {
|
||||||
|
/// if let Some(user) = user {
|
||||||
|
/// format!("Welcome! {}", user.id().unwrap())
|
||||||
/// } else {
|
/// } else {
|
||||||
/// "Welcome Anonymous!".to_owned()
|
/// "Welcome Anonymous!".to_owned()
|
||||||
/// }
|
/// }
|
||||||
@ -91,10 +256,17 @@ impl Identity {
|
|||||||
/// ```
|
/// ```
|
||||||
impl FromRequest for Identity {
|
impl FromRequest for Identity {
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Future = Ready<Result<Identity, Error>>;
|
type Future = Ready<Result<Self, Self::Error>>;
|
||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
||||||
ready(Ok(Identity(req.clone())))
|
ready(Identity::extract(&req.extensions()).map_err(|err| {
|
||||||
|
let res = actix_web::error::InternalError::from_response(
|
||||||
|
err,
|
||||||
|
HttpResponse::new(StatusCode::UNAUTHORIZED),
|
||||||
|
);
|
||||||
|
|
||||||
|
actix_web::Error::from(res)
|
||||||
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
27
actix-identity/src/identity_ext.rs
Normal file
27
actix-identity/src/identity_ext.rs
Normal file
@ -0,0 +1,27 @@
|
|||||||
|
use actix_web::{dev::ServiceRequest, guard::GuardContext, HttpMessage, HttpRequest};
|
||||||
|
|
||||||
|
use crate::{error::GetIdentityError, Identity};
|
||||||
|
|
||||||
|
/// Helper trait to retrieve an [`Identity`] instance from various `actix-web`'s types.
|
||||||
|
pub trait IdentityExt {
|
||||||
|
/// Retrieve the identity attached to the current session, if available.
|
||||||
|
fn get_identity(&self) -> Result<Identity, GetIdentityError>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IdentityExt for HttpRequest {
|
||||||
|
fn get_identity(&self) -> Result<Identity, GetIdentityError> {
|
||||||
|
Identity::extract(&self.extensions())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IdentityExt for ServiceRequest {
|
||||||
|
fn get_identity(&self) -> Result<Identity, GetIdentityError> {
|
||||||
|
Identity::extract(&self.extensions())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl IdentityExt for GuardContext<'_> {
|
||||||
|
fn get_identity(&self) -> Result<Identity, GetIdentityError> {
|
||||||
|
Identity::extract(&self.req_data())
|
||||||
|
}
|
||||||
|
}
|
@ -1,163 +1,109 @@
|
|||||||
//! Opinionated request identity service for Actix Web apps.
|
/*!
|
||||||
//!
|
Identity management for Actix Web.
|
||||||
//! [`IdentityService`] middleware can be used with different policies types to store
|
|
||||||
//! identity information.
|
|
||||||
//!
|
|
||||||
//! A cookie based policy is provided. [`CookieIdentityPolicy`] uses cookies as identity storage.
|
|
||||||
//!
|
|
||||||
//! To access current request identity, use the [`Identity`] extractor.
|
|
||||||
//!
|
|
||||||
//! ```
|
|
||||||
//! use actix_web::*;
|
|
||||||
//! use actix_identity::{Identity, CookieIdentityPolicy, IdentityService};
|
|
||||||
//!
|
|
||||||
//! #[get("/")]
|
|
||||||
//! async fn index(id: Identity) -> String {
|
|
||||||
//! // access request identity
|
|
||||||
//! if let Some(id) = id.identity() {
|
|
||||||
//! format!("Welcome! {}", id)
|
|
||||||
//! } else {
|
|
||||||
//! "Welcome Anonymous!".to_owned()
|
|
||||||
//! }
|
|
||||||
//! }
|
|
||||||
//!
|
|
||||||
//! #[post("/login")]
|
|
||||||
//! async fn login(id: Identity) -> HttpResponse {
|
|
||||||
//! // remember identity
|
|
||||||
//! id.remember("User1".to_owned());
|
|
||||||
//! HttpResponse::Ok().finish()
|
|
||||||
//! }
|
|
||||||
//!
|
|
||||||
//! #[post("/logout")]
|
|
||||||
//! async fn logout(id: Identity) -> HttpResponse {
|
|
||||||
//! // remove identity
|
|
||||||
//! id.forget();
|
|
||||||
//! HttpResponse::Ok().finish()
|
|
||||||
//! }
|
|
||||||
//!
|
|
||||||
//! HttpServer::new(move || {
|
|
||||||
//! // create cookie identity backend (inside closure, since policy is not Clone)
|
|
||||||
//! let policy = CookieIdentityPolicy::new(&[0; 32])
|
|
||||||
//! .name("auth-cookie")
|
|
||||||
//! .secure(false);
|
|
||||||
//!
|
|
||||||
//! App::new()
|
|
||||||
//! // wrap policy into middleware identity middleware
|
|
||||||
//! .wrap(IdentityService::new(policy))
|
|
||||||
//! .service(services![index, login, logout])
|
|
||||||
//! })
|
|
||||||
//! # ;
|
|
||||||
//! ```
|
|
||||||
|
|
||||||
#![deny(rust_2018_idioms, nonstandard_style)]
|
`actix-identity` can be used to track identity of a user across multiple requests. It is built
|
||||||
#![warn(future_incompatible)]
|
on top of HTTP sessions, via [`actix-session`](https://docs.rs/actix-session).
|
||||||
|
|
||||||
use std::future::Future;
|
# Getting started
|
||||||
|
To start using identity management in your Actix Web application you must register
|
||||||
|
[`IdentityMiddleware`] and `SessionMiddleware` as middleware on your `App`:
|
||||||
|
|
||||||
use actix_web::{
|
```no_run
|
||||||
dev::{ServiceRequest, ServiceResponse},
|
# use actix_web::web;
|
||||||
Error, HttpMessage, Result,
|
use actix_web::{cookie::Key, App, HttpServer, HttpResponse};
|
||||||
};
|
use actix_identity::IdentityMiddleware;
|
||||||
|
use actix_session::{storage::RedisSessionStore, SessionMiddleware};
|
||||||
|
|
||||||
mod cookie;
|
#[actix_web::main]
|
||||||
|
async fn main() {
|
||||||
|
// When using `Key::generate()` it is important to initialize outside of the
|
||||||
|
// `HttpServer::new` closure. When deployed the secret key should be read from a
|
||||||
|
// configuration file or environment variables.
|
||||||
|
let secret_key = Key::generate();
|
||||||
|
|
||||||
|
let redis_store = RedisSessionStore::new("redis://127.0.0.1:6379")
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
HttpServer::new(move || {
|
||||||
|
App::new()
|
||||||
|
// Install the identity framework first.
|
||||||
|
.wrap(IdentityMiddleware::default())
|
||||||
|
// The identity system is built on top of sessions. You must install the session
|
||||||
|
// middleware to leverage `actix-identity`. The session middleware must be mounted
|
||||||
|
// AFTER the identity middleware: `actix-web` invokes middleware in the OPPOSITE
|
||||||
|
// order of registration when it receives an incoming request.
|
||||||
|
.wrap(SessionMiddleware::new(
|
||||||
|
redis_store.clone(),
|
||||||
|
secret_key.clone(),
|
||||||
|
))
|
||||||
|
// Your request handlers [...]
|
||||||
|
# .default_service(web::to(|| HttpResponse::Ok()))
|
||||||
|
})
|
||||||
|
# ;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
User identities can be created, accessed and destroyed using the [`Identity`] extractor in your
|
||||||
|
request handlers:
|
||||||
|
|
||||||
|
```no_run
|
||||||
|
use actix_web::{get, post, HttpResponse, Responder, HttpRequest, HttpMessage};
|
||||||
|
use actix_identity::Identity;
|
||||||
|
use actix_session::storage::RedisSessionStore;
|
||||||
|
|
||||||
|
#[get("/")]
|
||||||
|
async fn index(user: Option<Identity>) -> impl Responder {
|
||||||
|
if let Some(user) = user {
|
||||||
|
format!("Welcome! {}", user.id().unwrap())
|
||||||
|
} else {
|
||||||
|
"Welcome Anonymous!".to_owned()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[post("/login")]
|
||||||
|
async fn login(request: HttpRequest) -> impl Responder {
|
||||||
|
// Some kind of authentication should happen here
|
||||||
|
// e.g. password-based, biometric, etc.
|
||||||
|
// [...]
|
||||||
|
|
||||||
|
// attach a verified user identity to the active session
|
||||||
|
Identity::login(&request.extensions(), "User1".into()).unwrap();
|
||||||
|
|
||||||
|
HttpResponse::Ok()
|
||||||
|
}
|
||||||
|
|
||||||
|
#[post("/logout")]
|
||||||
|
async fn logout(user: Option<Identity>) -> impl Responder {
|
||||||
|
if let Some(user) = user {
|
||||||
|
user.logout();
|
||||||
|
}
|
||||||
|
HttpResponse::Ok()
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
# Advanced configuration
|
||||||
|
By default, `actix-identity` does not automatically log out users. You can change this behaviour
|
||||||
|
by customising the configuration for [`IdentityMiddleware`] via [`IdentityMiddleware::builder`].
|
||||||
|
|
||||||
|
In particular, you can automatically log out users who:
|
||||||
|
- have been inactive for a while (see [`IdentityMiddlewareBuilder::visit_deadline`]);
|
||||||
|
- logged in too long ago (see [`IdentityMiddlewareBuilder::login_deadline`]).
|
||||||
|
|
||||||
|
[`IdentityMiddlewareBuilder::visit_deadline`]: config::IdentityMiddlewareBuilder::visit_deadline
|
||||||
|
[`IdentityMiddlewareBuilder::login_deadline`]: config::IdentityMiddlewareBuilder::login_deadline
|
||||||
|
*/
|
||||||
|
|
||||||
|
#![forbid(unsafe_code)]
|
||||||
|
#![deny(missing_docs)]
|
||||||
|
#![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))]
|
||||||
|
|
||||||
|
pub mod config;
|
||||||
|
pub mod error;
|
||||||
mod identity;
|
mod identity;
|
||||||
|
mod identity_ext;
|
||||||
mod middleware;
|
mod middleware;
|
||||||
|
|
||||||
pub use self::cookie::CookieIdentityPolicy;
|
pub use self::{identity::Identity, identity_ext::IdentityExt, middleware::IdentityMiddleware};
|
||||||
pub use self::identity::Identity;
|
|
||||||
pub use self::middleware::IdentityService;
|
|
||||||
|
|
||||||
/// Identity policy.
|
|
||||||
pub trait IdentityPolicy: Sized + 'static {
|
|
||||||
/// The return type of the middleware
|
|
||||||
type Future: Future<Output = Result<Option<String>, Error>>;
|
|
||||||
|
|
||||||
/// The return type of the middleware
|
|
||||||
type ResponseFuture: Future<Output = Result<(), Error>>;
|
|
||||||
|
|
||||||
/// Parse the session from request and load data from a service identity.
|
|
||||||
#[allow(clippy::wrong_self_convention)]
|
|
||||||
fn from_request(&self, req: &mut ServiceRequest) -> Self::Future;
|
|
||||||
|
|
||||||
/// Write changes to response
|
|
||||||
fn to_response<B>(
|
|
||||||
&self,
|
|
||||||
identity: Option<String>,
|
|
||||||
changed: bool,
|
|
||||||
response: &mut ServiceResponse<B>,
|
|
||||||
) -> Self::ResponseFuture;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Helper trait that allows to get Identity.
|
|
||||||
///
|
|
||||||
/// It could be used in middleware but identity policy must be set before any other middleware that
|
|
||||||
/// needs identity. RequestIdentity is implemented both for `ServiceRequest` and `HttpRequest`.
|
|
||||||
pub trait RequestIdentity {
|
|
||||||
fn get_identity(&self) -> Option<String>;
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<T> RequestIdentity for T
|
|
||||||
where
|
|
||||||
T: HttpMessage,
|
|
||||||
{
|
|
||||||
fn get_identity(&self) -> Option<String> {
|
|
||||||
Identity::get_identity(&self.extensions())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(test)]
|
|
||||||
mod tests {
|
|
||||||
use std::time::SystemTime;
|
|
||||||
|
|
||||||
use actix_web::{
|
|
||||||
body::{BoxBody, EitherBody},
|
|
||||||
dev::ServiceResponse,
|
|
||||||
test, web, App, Error,
|
|
||||||
};
|
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
pub(crate) const COOKIE_KEY_MASTER: [u8; 32] = [0; 32];
|
|
||||||
pub(crate) const COOKIE_NAME: &str = "actix_auth";
|
|
||||||
pub(crate) const COOKIE_LOGIN: &str = "test";
|
|
||||||
|
|
||||||
#[allow(clippy::enum_variant_names)]
|
|
||||||
pub(crate) enum LoginTimestampCheck {
|
|
||||||
NoTimestamp,
|
|
||||||
NewTimestamp,
|
|
||||||
OldTimestamp(SystemTime),
|
|
||||||
}
|
|
||||||
|
|
||||||
#[allow(clippy::enum_variant_names)]
|
|
||||||
pub(crate) enum VisitTimeStampCheck {
|
|
||||||
NoTimestamp,
|
|
||||||
NewTimestamp,
|
|
||||||
}
|
|
||||||
|
|
||||||
pub(crate) async fn create_identity_server<
|
|
||||||
F: Fn(CookieIdentityPolicy) -> CookieIdentityPolicy + Sync + Send + Clone + 'static,
|
|
||||||
>(
|
|
||||||
f: F,
|
|
||||||
) -> impl actix_service::Service<
|
|
||||||
actix_http::Request,
|
|
||||||
Response = ServiceResponse<EitherBody<BoxBody>>,
|
|
||||||
Error = Error,
|
|
||||||
> {
|
|
||||||
test::init_service(
|
|
||||||
App::new()
|
|
||||||
.wrap(IdentityService::new(f(CookieIdentityPolicy::new(
|
|
||||||
&COOKIE_KEY_MASTER,
|
|
||||||
)
|
|
||||||
.secure(false)
|
|
||||||
.name(COOKIE_NAME))))
|
|
||||||
.service(web::resource("/").to(|id: Identity| async move {
|
|
||||||
let identity = id.identity();
|
|
||||||
if identity.is_none() {
|
|
||||||
id.remember(COOKIE_LOGIN.to_string())
|
|
||||||
}
|
|
||||||
web::Json(identity)
|
|
||||||
})),
|
|
||||||
)
|
|
||||||
.await
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
@ -1,171 +1,259 @@
|
|||||||
use std::rc::Rc;
|
use std::rc::Rc;
|
||||||
|
|
||||||
|
use actix_session::SessionExt;
|
||||||
use actix_utils::future::{ready, Ready};
|
use actix_utils::future::{ready, Ready};
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
body::{EitherBody, MessageBody},
|
body::MessageBody,
|
||||||
|
cookie::time::{format_description::well_known::Rfc3339, OffsetDateTime},
|
||||||
dev::{Service, ServiceRequest, ServiceResponse, Transform},
|
dev::{Service, ServiceRequest, ServiceResponse, Transform},
|
||||||
Error, HttpMessage, Result,
|
Error, HttpMessage as _, Result,
|
||||||
};
|
};
|
||||||
use futures_util::future::{FutureExt as _, LocalBoxFuture};
|
use futures_core::future::LocalBoxFuture;
|
||||||
|
|
||||||
use crate::{identity::IdentityItem, IdentityPolicy};
|
use crate::{
|
||||||
|
config::{Configuration, IdentityMiddlewareBuilder},
|
||||||
|
identity::IdentityInner,
|
||||||
|
Identity,
|
||||||
|
};
|
||||||
|
|
||||||
/// Request identity middleware
|
/// Identity management middleware.
|
||||||
///
|
///
|
||||||
|
/// ```no_run
|
||||||
|
/// use actix_web::{cookie::Key, App, HttpServer};
|
||||||
|
/// use actix_session::storage::RedisSessionStore;
|
||||||
|
/// use actix_identity::{Identity, IdentityMiddleware};
|
||||||
|
/// use actix_session::{Session, SessionMiddleware};
|
||||||
|
///
|
||||||
|
/// #[actix_web::main]
|
||||||
|
/// async fn main() {
|
||||||
|
/// let secret_key = Key::generate();
|
||||||
|
/// let redis_store = RedisSessionStore::new("redis://127.0.0.1:6379").await.unwrap();
|
||||||
|
///
|
||||||
|
/// HttpServer::new(move || {
|
||||||
|
/// App::new()
|
||||||
|
/// // Install the identity framework first.
|
||||||
|
/// .wrap(IdentityMiddleware::default())
|
||||||
|
/// // The identity system is built on top of sessions.
|
||||||
|
/// // You must install the session middleware to leverage `actix-identity`.
|
||||||
|
/// .wrap(SessionMiddleware::new(redis_store.clone(), secret_key.clone()))
|
||||||
|
/// })
|
||||||
|
/// # ;
|
||||||
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
/// use actix_web::App;
|
#[derive(Default, Clone)]
|
||||||
/// use actix_identity::{CookieIdentityPolicy, IdentityService};
|
pub struct IdentityMiddleware {
|
||||||
///
|
configuration: Rc<Configuration>,
|
||||||
/// // create cookie identity backend
|
|
||||||
/// let policy = CookieIdentityPolicy::new(&[0; 32])
|
|
||||||
/// .name("auth-cookie")
|
|
||||||
/// .secure(false);
|
|
||||||
///
|
|
||||||
/// let app = App::new()
|
|
||||||
/// // wrap policy into identity middleware
|
|
||||||
/// .wrap(IdentityService::new(policy));
|
|
||||||
/// ```
|
|
||||||
pub struct IdentityService<T> {
|
|
||||||
backend: Rc<T>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<T> IdentityService<T> {
|
impl IdentityMiddleware {
|
||||||
/// Create new identity service with specified backend.
|
pub(crate) fn new(configuration: Configuration) -> Self {
|
||||||
pub fn new(backend: T) -> Self {
|
Self {
|
||||||
IdentityService {
|
configuration: Rc::new(configuration),
|
||||||
backend: Rc::new(backend),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// A fluent API to configure [`IdentityMiddleware`].
|
||||||
|
pub fn builder() -> IdentityMiddlewareBuilder {
|
||||||
|
IdentityMiddlewareBuilder::new()
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S, T, B> Transform<S, ServiceRequest> for IdentityService<T>
|
impl<S, B> Transform<S, ServiceRequest> for IdentityMiddleware
|
||||||
where
|
where
|
||||||
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
|
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
T: IdentityPolicy,
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
{
|
{
|
||||||
type Response = ServiceResponse<EitherBody<B>>;
|
type Response = ServiceResponse<B>;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
|
type Transform = InnerIdentityMiddleware<S>;
|
||||||
type InitError = ();
|
type InitError = ();
|
||||||
type Transform = IdentityServiceMiddleware<S, T>;
|
|
||||||
type Future = Ready<Result<Self::Transform, Self::InitError>>;
|
type Future = Ready<Result<Self::Transform, Self::InitError>>;
|
||||||
|
|
||||||
fn new_transform(&self, service: S) -> Self::Future {
|
fn new_transform(&self, service: S) -> Self::Future {
|
||||||
ready(Ok(IdentityServiceMiddleware {
|
ready(Ok(InnerIdentityMiddleware {
|
||||||
backend: self.backend.clone(),
|
|
||||||
service: Rc::new(service),
|
service: Rc::new(service),
|
||||||
|
configuration: Rc::clone(&self.configuration),
|
||||||
}))
|
}))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
pub struct IdentityServiceMiddleware<S, T> {
|
#[doc(hidden)]
|
||||||
pub(crate) service: Rc<S>,
|
pub struct InnerIdentityMiddleware<S> {
|
||||||
pub(crate) backend: Rc<T>,
|
service: Rc<S>,
|
||||||
|
configuration: Rc<Configuration>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S, T> Clone for IdentityServiceMiddleware<S, T> {
|
impl<S> Clone for InnerIdentityMiddleware<S> {
|
||||||
fn clone(&self) -> Self {
|
fn clone(&self) -> Self {
|
||||||
Self {
|
Self {
|
||||||
backend: Rc::clone(&self.backend),
|
|
||||||
service: Rc::clone(&self.service),
|
service: Rc::clone(&self.service),
|
||||||
|
configuration: Rc::clone(&self.configuration),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<S, T, B> Service<ServiceRequest> for IdentityServiceMiddleware<S, T>
|
impl<S, B> Service<ServiceRequest> for InnerIdentityMiddleware<S>
|
||||||
where
|
where
|
||||||
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
|
S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error> + 'static,
|
||||||
S::Future: 'static,
|
S::Future: 'static,
|
||||||
T: IdentityPolicy,
|
|
||||||
B: MessageBody + 'static,
|
B: MessageBody + 'static,
|
||||||
{
|
{
|
||||||
type Response = ServiceResponse<EitherBody<B>>;
|
type Response = ServiceResponse<B>;
|
||||||
type Error = Error;
|
type Error = Error;
|
||||||
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
|
type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>;
|
||||||
|
|
||||||
actix_service::forward_ready!(service);
|
actix_service::forward_ready!(service);
|
||||||
|
|
||||||
fn call(&self, mut req: ServiceRequest) -> Self::Future {
|
fn call(&self, req: ServiceRequest) -> Self::Future {
|
||||||
let srv = Rc::clone(&self.service);
|
let srv = Rc::clone(&self.service);
|
||||||
let backend = Rc::clone(&self.backend);
|
let configuration = Rc::clone(&self.configuration);
|
||||||
let fut = self.backend.from_request(&mut req);
|
Box::pin(async move {
|
||||||
|
let identity_inner = IdentityInner {
|
||||||
async move {
|
session: req.get_session(),
|
||||||
match fut.await {
|
logout_behaviour: configuration.on_logout.clone(),
|
||||||
Ok(id) => {
|
is_login_deadline_enabled: configuration.login_deadline.is_some(),
|
||||||
req.extensions_mut()
|
is_visit_deadline_enabled: configuration.visit_deadline.is_some(),
|
||||||
.insert(IdentityItem { id, changed: false });
|
id_key: configuration.id_key,
|
||||||
|
last_visit_unix_timestamp_key: configuration.last_visit_unix_timestamp_key,
|
||||||
let mut res = srv.call(req).await?;
|
login_unix_timestamp_key: configuration.login_unix_timestamp_key,
|
||||||
let id = res.request().extensions_mut().remove::<IdentityItem>();
|
};
|
||||||
|
req.extensions_mut().insert(identity_inner);
|
||||||
if let Some(id) = id {
|
enforce_policies(&req, &configuration);
|
||||||
match backend.to_response(id.id, id.changed, &mut res).await {
|
srv.call(req).await
|
||||||
Ok(_) => Ok(res.map_into_left_body()),
|
})
|
||||||
Err(err) => Ok(res.error_response(err).map_into_right_body()),
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
Ok(res.map_into_left_body())
|
|
||||||
}
|
|
||||||
}
|
|
||||||
Err(err) => Ok(req.error_response(err).map_into_right_body()),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
.boxed_local()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
// easier to scan with returns where they are
|
||||||
mod tests {
|
// especially if the function body were to evolve in the future
|
||||||
use std::{rc::Rc, time::Duration};
|
#[allow(clippy::needless_return)]
|
||||||
|
fn enforce_policies(req: &ServiceRequest, configuration: &Configuration) {
|
||||||
|
let must_extract_identity =
|
||||||
|
configuration.login_deadline.is_some() || configuration.visit_deadline.is_some();
|
||||||
|
|
||||||
use actix_service::into_service;
|
if !must_extract_identity {
|
||||||
use actix_web::{dev, error, test, Error, Result};
|
return;
|
||||||
|
|
||||||
use super::*;
|
|
||||||
|
|
||||||
#[actix_web::test]
|
|
||||||
async fn test_borrowed_mut_error() {
|
|
||||||
use actix_utils::future::{ok, Ready};
|
|
||||||
use futures_util::future::lazy;
|
|
||||||
|
|
||||||
struct Ident;
|
|
||||||
impl IdentityPolicy for Ident {
|
|
||||||
type Future = Ready<Result<Option<String>, Error>>;
|
|
||||||
type ResponseFuture = Ready<Result<(), Error>>;
|
|
||||||
|
|
||||||
fn from_request(&self, _: &mut dev::ServiceRequest) -> Self::Future {
|
|
||||||
ok(Some("test".to_string()))
|
|
||||||
}
|
}
|
||||||
|
|
||||||
fn to_response<B>(
|
let identity = match Identity::extract(&req.extensions()) {
|
||||||
&self,
|
Ok(identity) => identity,
|
||||||
_: Option<String>,
|
Err(err) => {
|
||||||
_: bool,
|
tracing::debug!(
|
||||||
_: &mut dev::ServiceResponse<B>,
|
error.display = %err,
|
||||||
) -> Self::ResponseFuture {
|
error.debug = ?err,
|
||||||
ok(())
|
"Failed to extract an `Identity` from the incoming request."
|
||||||
|
);
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
|
||||||
let srv = crate::middleware::IdentityServiceMiddleware {
|
|
||||||
backend: Rc::new(Ident),
|
|
||||||
service: Rc::new(into_service(|_: dev::ServiceRequest| async move {
|
|
||||||
actix_web::rt::time::sleep(Duration::from_secs(100)).await;
|
|
||||||
Err::<dev::ServiceResponse, _>(error::ErrorBadRequest("error"))
|
|
||||||
})),
|
|
||||||
};
|
};
|
||||||
|
|
||||||
let srv2 = srv.clone();
|
if let Some(login_deadline) = configuration.login_deadline {
|
||||||
let req = test::TestRequest::default().to_srv_request();
|
if matches!(
|
||||||
|
enforce_login_deadline(&identity, login_deadline),
|
||||||
|
PolicyDecision::LogOut
|
||||||
|
) {
|
||||||
|
identity.logout();
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
actix_web::rt::spawn(async move {
|
if let Some(visit_deadline) = configuration.visit_deadline {
|
||||||
let _ = srv2.call(req).await;
|
if matches!(
|
||||||
});
|
enforce_visit_deadline(&identity, visit_deadline),
|
||||||
|
PolicyDecision::LogOut
|
||||||
actix_web::rt::time::sleep(Duration::from_millis(50)).await;
|
) {
|
||||||
|
identity.logout();
|
||||||
let _ = lazy(|cx| srv.poll_ready(cx)).await;
|
return;
|
||||||
|
} else if let Err(err) = identity.set_last_visited_at() {
|
||||||
|
tracing::warn!(
|
||||||
|
error.display = %err,
|
||||||
|
error.debug = ?err,
|
||||||
|
"Failed to set the last visited timestamp on `Identity` for an incoming request."
|
||||||
|
);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
fn enforce_login_deadline(
|
||||||
|
identity: &Identity,
|
||||||
|
login_deadline: std::time::Duration,
|
||||||
|
) -> PolicyDecision {
|
||||||
|
match identity.logged_at() {
|
||||||
|
Ok(None) => {
|
||||||
|
tracing::info!(
|
||||||
|
"Login deadline is enabled, but there is no login timestamp in the session \
|
||||||
|
state attached to the incoming request. Logging the user out."
|
||||||
|
);
|
||||||
|
PolicyDecision::LogOut
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
tracing::info!(
|
||||||
|
error.display = %err,
|
||||||
|
error.debug = ?err,
|
||||||
|
"Login deadline is enabled but we failed to extract the login timestamp from the \
|
||||||
|
session state attached to the incoming request. Logging the user out."
|
||||||
|
);
|
||||||
|
PolicyDecision::LogOut
|
||||||
|
}
|
||||||
|
Ok(Some(logged_in_at)) => {
|
||||||
|
let elapsed = OffsetDateTime::now_utc() - logged_in_at;
|
||||||
|
if elapsed > login_deadline {
|
||||||
|
tracing::info!(
|
||||||
|
user.logged_in_at = %logged_in_at.format(&Rfc3339).unwrap_or_default(),
|
||||||
|
identity.login_deadline_seconds = login_deadline.as_secs(),
|
||||||
|
identity.elapsed_since_login_seconds = elapsed.whole_seconds(),
|
||||||
|
"Login deadline is enabled and too much time has passed since the user logged \
|
||||||
|
in. Logging the user out."
|
||||||
|
);
|
||||||
|
PolicyDecision::LogOut
|
||||||
|
} else {
|
||||||
|
PolicyDecision::StayLoggedIn
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
fn enforce_visit_deadline(
|
||||||
|
identity: &Identity,
|
||||||
|
visit_deadline: std::time::Duration,
|
||||||
|
) -> PolicyDecision {
|
||||||
|
match identity.last_visited_at() {
|
||||||
|
Ok(None) => {
|
||||||
|
tracing::info!(
|
||||||
|
"Last visit deadline is enabled, but there is no last visit timestamp in the \
|
||||||
|
session state attached to the incoming request. Logging the user out."
|
||||||
|
);
|
||||||
|
PolicyDecision::LogOut
|
||||||
|
}
|
||||||
|
Err(err) => {
|
||||||
|
tracing::info!(
|
||||||
|
error.display = %err,
|
||||||
|
error.debug = ?err,
|
||||||
|
"Last visit deadline is enabled but we failed to extract the last visit timestamp \
|
||||||
|
from the session state attached to the incoming request. Logging the user out."
|
||||||
|
);
|
||||||
|
PolicyDecision::LogOut
|
||||||
|
}
|
||||||
|
Ok(Some(last_visited_at)) => {
|
||||||
|
let elapsed = OffsetDateTime::now_utc() - last_visited_at;
|
||||||
|
if elapsed > visit_deadline {
|
||||||
|
tracing::info!(
|
||||||
|
user.last_visited_at = %last_visited_at.format(&Rfc3339).unwrap_or_default(),
|
||||||
|
identity.visit_deadline_seconds = visit_deadline.as_secs(),
|
||||||
|
identity.elapsed_since_last_visit_seconds = elapsed.whole_seconds(),
|
||||||
|
"Last visit deadline is enabled and too much time has passed since the last \
|
||||||
|
time the user visited. Logging the user out."
|
||||||
|
);
|
||||||
|
PolicyDecision::LogOut
|
||||||
|
} else {
|
||||||
|
PolicyDecision::StayLoggedIn
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
enum PolicyDecision {
|
||||||
|
StayLoggedIn,
|
||||||
|
LogOut,
|
||||||
|
}
|
||||||
|
17
actix-identity/tests/integration/fixtures.rs
Normal file
17
actix-identity/tests/integration/fixtures.rs
Normal file
@ -0,0 +1,17 @@
|
|||||||
|
use actix_session::{storage::CookieSessionStore, SessionMiddleware};
|
||||||
|
use actix_web::cookie::Key;
|
||||||
|
use uuid::Uuid;
|
||||||
|
|
||||||
|
pub fn store() -> CookieSessionStore {
|
||||||
|
CookieSessionStore::default()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn user_id() -> String {
|
||||||
|
Uuid::new_v4().to_string()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub fn session_middleware() -> SessionMiddleware<CookieSessionStore> {
|
||||||
|
SessionMiddleware::builder(store(), Key::generate())
|
||||||
|
.cookie_domain(Some("localhost".into()))
|
||||||
|
.build()
|
||||||
|
}
|
212
actix-identity/tests/integration/integration.rs
Normal file
212
actix-identity/tests/integration/integration.rs
Normal file
@ -0,0 +1,212 @@
|
|||||||
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use actix_identity::{config::LogoutBehaviour, IdentityMiddleware};
|
||||||
|
use reqwest::StatusCode;
|
||||||
|
|
||||||
|
use crate::{fixtures::user_id, test_app::TestApp};
|
||||||
|
|
||||||
|
#[actix_web::test]
|
||||||
|
async fn opaque_401_is_returned_for_unauthenticated_users() {
|
||||||
|
let app = TestApp::spawn();
|
||||||
|
|
||||||
|
let response = app.get_identity_required().await;
|
||||||
|
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
|
||||||
|
assert!(response.bytes().await.unwrap().is_empty());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_web::test]
|
||||||
|
async fn login_works() {
|
||||||
|
let app = TestApp::spawn();
|
||||||
|
let user_id = user_id();
|
||||||
|
|
||||||
|
// Log-in
|
||||||
|
let body = app.post_login(user_id.clone()).await;
|
||||||
|
assert_eq!(body.user_id, Some(user_id.clone()));
|
||||||
|
|
||||||
|
// Access identity-restricted route successfully
|
||||||
|
let response = app.get_identity_required().await;
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_web::test]
|
||||||
|
async fn custom_keys_work_as_expected() {
|
||||||
|
let custom_id_key = "custom.user_id";
|
||||||
|
let custom_last_visited_key = "custom.last_visited_at";
|
||||||
|
let custom_logged_in_key = "custom.logged_in_at";
|
||||||
|
|
||||||
|
let app = TestApp::spawn_with_config(
|
||||||
|
IdentityMiddleware::builder()
|
||||||
|
.id_key(custom_id_key)
|
||||||
|
.last_visit_unix_timestamp_key(custom_last_visited_key)
|
||||||
|
.login_unix_timestamp_key(custom_logged_in_key),
|
||||||
|
);
|
||||||
|
let user_id = user_id();
|
||||||
|
|
||||||
|
let body = app.post_login(user_id.clone()).await;
|
||||||
|
assert_eq!(body.user_id, Some(user_id.clone()));
|
||||||
|
|
||||||
|
let response = app.get_identity_required().await;
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
let response = app.post_logout().await;
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
let response = app.get_identity_required().await;
|
||||||
|
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_web::test]
|
||||||
|
async fn logging_in_again_replaces_the_current_identity() {
|
||||||
|
let app = TestApp::spawn();
|
||||||
|
let first_user_id = user_id();
|
||||||
|
let second_user_id = user_id();
|
||||||
|
|
||||||
|
// Log-in
|
||||||
|
let body = app.post_login(first_user_id.clone()).await;
|
||||||
|
assert_eq!(body.user_id, Some(first_user_id.clone()));
|
||||||
|
|
||||||
|
// Log-in again
|
||||||
|
let body = app.post_login(second_user_id.clone()).await;
|
||||||
|
assert_eq!(body.user_id, Some(second_user_id.clone()));
|
||||||
|
|
||||||
|
let body = app.get_current().await;
|
||||||
|
assert_eq!(body.user_id, Some(second_user_id.clone()));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_web::test]
|
||||||
|
async fn session_key_is_renewed_on_login() {
|
||||||
|
let app = TestApp::spawn();
|
||||||
|
let user_id = user_id();
|
||||||
|
|
||||||
|
// Create an anonymous session
|
||||||
|
let body = app.post_increment().await;
|
||||||
|
assert_eq!(body.user_id, None);
|
||||||
|
assert_eq!(body.counter, 1);
|
||||||
|
assert_eq!(body.session_status, "changed");
|
||||||
|
|
||||||
|
// Log-in
|
||||||
|
let body = app.post_login(user_id.clone()).await;
|
||||||
|
assert_eq!(body.user_id, Some(user_id.clone()));
|
||||||
|
assert_eq!(body.counter, 1);
|
||||||
|
assert_eq!(body.session_status, "renewed");
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_web::test]
|
||||||
|
async fn logout_works() {
|
||||||
|
let app = TestApp::spawn();
|
||||||
|
let user_id = user_id();
|
||||||
|
|
||||||
|
// Log-in
|
||||||
|
let body = app.post_login(user_id.clone()).await;
|
||||||
|
assert_eq!(body.user_id, Some(user_id.clone()));
|
||||||
|
|
||||||
|
// Log-out
|
||||||
|
let response = app.post_logout().await;
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
// Try to access identity-restricted route
|
||||||
|
let response = app.get_identity_required().await;
|
||||||
|
assert_eq!(response.status(), StatusCode::UNAUTHORIZED);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_web::test]
|
||||||
|
async fn logout_can_avoid_destroying_the_whole_session() {
|
||||||
|
let app = TestApp::spawn_with_config(
|
||||||
|
IdentityMiddleware::builder().logout_behaviour(LogoutBehaviour::DeleteIdentityKeys),
|
||||||
|
);
|
||||||
|
let user_id = user_id();
|
||||||
|
|
||||||
|
// Log-in
|
||||||
|
let body = app.post_login(user_id.clone()).await;
|
||||||
|
assert_eq!(body.user_id, Some(user_id.clone()));
|
||||||
|
assert_eq!(body.counter, 0);
|
||||||
|
|
||||||
|
// Increment counter
|
||||||
|
let body = app.post_increment().await;
|
||||||
|
assert_eq!(body.user_id, Some(user_id.clone()));
|
||||||
|
assert_eq!(body.counter, 1);
|
||||||
|
|
||||||
|
// Log-out
|
||||||
|
let response = app.post_logout().await;
|
||||||
|
assert!(response.status().is_success());
|
||||||
|
|
||||||
|
// Check the state of the counter attached to the session state
|
||||||
|
let body = app.get_current().await;
|
||||||
|
assert_eq!(body.user_id, None);
|
||||||
|
// It would be 0 if the session state had been entirely lost!
|
||||||
|
assert_eq!(body.counter, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_web::test]
|
||||||
|
async fn user_is_logged_out_when_login_deadline_is_elapsed() {
|
||||||
|
let login_deadline = Duration::from_millis(10);
|
||||||
|
let app = TestApp::spawn_with_config(
|
||||||
|
IdentityMiddleware::builder().login_deadline(Some(login_deadline)),
|
||||||
|
);
|
||||||
|
let user_id = user_id();
|
||||||
|
|
||||||
|
// Log-in
|
||||||
|
let body = app.post_login(user_id.clone()).await;
|
||||||
|
assert_eq!(body.user_id, Some(user_id.clone()));
|
||||||
|
|
||||||
|
// Wait for deadline to pass
|
||||||
|
actix_web::rt::time::sleep(login_deadline * 2).await;
|
||||||
|
|
||||||
|
let body = app.get_current().await;
|
||||||
|
// We have been logged out!
|
||||||
|
assert_eq!(body.user_id, None);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_web::test]
|
||||||
|
async fn login_deadline_does_not_log_users_out_before_their_time() {
|
||||||
|
// 1 hour
|
||||||
|
let login_deadline = Duration::from_secs(60 * 60);
|
||||||
|
let app = TestApp::spawn_with_config(
|
||||||
|
IdentityMiddleware::builder().login_deadline(Some(login_deadline)),
|
||||||
|
);
|
||||||
|
let user_id = user_id();
|
||||||
|
|
||||||
|
// Log-in
|
||||||
|
let body = app.post_login(user_id.clone()).await;
|
||||||
|
assert_eq!(body.user_id, Some(user_id.clone()));
|
||||||
|
|
||||||
|
let body = app.get_current().await;
|
||||||
|
assert_eq!(body.user_id, Some(user_id));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_web::test]
|
||||||
|
async fn visit_deadline_does_not_log_users_out_before_their_time() {
|
||||||
|
// 1 hour
|
||||||
|
let visit_deadline = Duration::from_secs(60 * 60);
|
||||||
|
let app = TestApp::spawn_with_config(
|
||||||
|
IdentityMiddleware::builder().visit_deadline(Some(visit_deadline)),
|
||||||
|
);
|
||||||
|
let user_id = user_id();
|
||||||
|
|
||||||
|
// Log-in
|
||||||
|
let body = app.post_login(user_id.clone()).await;
|
||||||
|
assert_eq!(body.user_id, Some(user_id.clone()));
|
||||||
|
|
||||||
|
let body = app.get_current().await;
|
||||||
|
assert_eq!(body.user_id, Some(user_id));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_web::test]
|
||||||
|
async fn user_is_logged_out_when_visit_deadline_is_elapsed() {
|
||||||
|
let visit_deadline = Duration::from_millis(10);
|
||||||
|
let app = TestApp::spawn_with_config(
|
||||||
|
IdentityMiddleware::builder().visit_deadline(Some(visit_deadline)),
|
||||||
|
);
|
||||||
|
let user_id = user_id();
|
||||||
|
|
||||||
|
// Log-in
|
||||||
|
let body = app.post_login(user_id.clone()).await;
|
||||||
|
assert_eq!(body.user_id, Some(user_id.clone()));
|
||||||
|
|
||||||
|
// Wait for deadline to pass
|
||||||
|
actix_web::rt::time::sleep(visit_deadline * 2).await;
|
||||||
|
|
||||||
|
let body = app.get_current().await;
|
||||||
|
// We have been logged out!
|
||||||
|
assert_eq!(body.user_id, None);
|
||||||
|
}
|
3
actix-identity/tests/integration/main.rs
Normal file
3
actix-identity/tests/integration/main.rs
Normal file
@ -0,0 +1,3 @@
|
|||||||
|
pub mod fixtures;
|
||||||
|
mod integration;
|
||||||
|
pub mod test_app;
|
187
actix-identity/tests/integration/test_app.rs
Normal file
187
actix-identity/tests/integration/test_app.rs
Normal file
@ -0,0 +1,187 @@
|
|||||||
|
use std::net::TcpListener;
|
||||||
|
|
||||||
|
use actix_identity::{config::IdentityMiddlewareBuilder, Identity, IdentityMiddleware};
|
||||||
|
use actix_session::{Session, SessionStatus};
|
||||||
|
use actix_web::{web, App, HttpMessage, HttpRequest, HttpResponse, HttpServer};
|
||||||
|
use serde::{Deserialize, Serialize};
|
||||||
|
|
||||||
|
use crate::fixtures::session_middleware;
|
||||||
|
|
||||||
|
pub struct TestApp {
|
||||||
|
port: u16,
|
||||||
|
api_client: reqwest::Client,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl TestApp {
|
||||||
|
/// Spawn a test application using a custom configuration for `IdentityMiddleware`.
|
||||||
|
pub fn spawn_with_config(builder: IdentityMiddlewareBuilder) -> Self {
|
||||||
|
// Random OS port
|
||||||
|
let listener = TcpListener::bind("localhost:0").unwrap();
|
||||||
|
let port = listener.local_addr().unwrap().port();
|
||||||
|
let server = HttpServer::new(move || {
|
||||||
|
App::new()
|
||||||
|
.wrap(builder.clone().build())
|
||||||
|
.wrap(session_middleware())
|
||||||
|
.route("/increment", web::post().to(increment))
|
||||||
|
.route("/current", web::get().to(show))
|
||||||
|
.route("/login", web::post().to(login))
|
||||||
|
.route("/logout", web::post().to(logout))
|
||||||
|
.route("/identity_required", web::get().to(identity_required))
|
||||||
|
})
|
||||||
|
.workers(1)
|
||||||
|
.listen(listener)
|
||||||
|
.unwrap()
|
||||||
|
.run();
|
||||||
|
|
||||||
|
actix_web::rt::spawn(server);
|
||||||
|
|
||||||
|
let client = reqwest::Client::builder()
|
||||||
|
.cookie_store(true)
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
TestApp {
|
||||||
|
port,
|
||||||
|
api_client: client,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Spawn a test application using the default configuration settings for `IdentityMiddleware`.
|
||||||
|
pub fn spawn() -> Self {
|
||||||
|
Self::spawn_with_config(IdentityMiddleware::builder())
|
||||||
|
}
|
||||||
|
|
||||||
|
fn url(&self) -> String {
|
||||||
|
format!("http://localhost:{}", self.port)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_identity_required(&self) -> reqwest::Response {
|
||||||
|
self.api_client
|
||||||
|
.get(format!("{}/identity_required", &self.url()))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn get_current(&self) -> EndpointResponse {
|
||||||
|
self.api_client
|
||||||
|
.get(format!("{}/current", &self.url()))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.json()
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn post_increment(&self) -> EndpointResponse {
|
||||||
|
let response = self
|
||||||
|
.api_client
|
||||||
|
.post(format!("{}/increment", &self.url()))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
response.json().await.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn post_login(&self, user_id: String) -> EndpointResponse {
|
||||||
|
let response = self
|
||||||
|
.api_client
|
||||||
|
.post(format!("{}/login", &self.url()))
|
||||||
|
.json(&LoginRequest { user_id })
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
response.json().await.unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
pub async fn post_logout(&self) -> reqwest::Response {
|
||||||
|
self.api_client
|
||||||
|
.post(format!("{}/logout", &self.url()))
|
||||||
|
.send()
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
pub struct EndpointResponse {
|
||||||
|
pub user_id: Option<String>,
|
||||||
|
pub counter: i32,
|
||||||
|
pub session_status: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
|
struct LoginRequest {
|
||||||
|
user_id: String,
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn show(user: Option<Identity>, session: Session) -> HttpResponse {
|
||||||
|
let user_id = user.map(|u| u.id().unwrap());
|
||||||
|
let counter: i32 = session
|
||||||
|
.get::<i32>("counter")
|
||||||
|
.unwrap_or(Some(0))
|
||||||
|
.unwrap_or(0);
|
||||||
|
|
||||||
|
HttpResponse::Ok().json(&EndpointResponse {
|
||||||
|
user_id,
|
||||||
|
counter,
|
||||||
|
session_status: session_status(session),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn increment(session: Session, user: Option<Identity>) -> HttpResponse {
|
||||||
|
let user_id = user.map(|u| u.id().unwrap());
|
||||||
|
let counter: i32 = session
|
||||||
|
.get::<i32>("counter")
|
||||||
|
.unwrap_or(Some(0))
|
||||||
|
.map_or(1, |inner| inner + 1);
|
||||||
|
session.insert("counter", counter).unwrap();
|
||||||
|
|
||||||
|
HttpResponse::Ok().json(&EndpointResponse {
|
||||||
|
user_id,
|
||||||
|
counter,
|
||||||
|
session_status: session_status(session),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn login(
|
||||||
|
user_id: web::Json<LoginRequest>,
|
||||||
|
request: HttpRequest,
|
||||||
|
session: Session,
|
||||||
|
) -> HttpResponse {
|
||||||
|
let id = user_id.into_inner().user_id;
|
||||||
|
let user = Identity::login(&request.extensions(), id).unwrap();
|
||||||
|
|
||||||
|
let counter: i32 = session
|
||||||
|
.get::<i32>("counter")
|
||||||
|
.unwrap_or(Some(0))
|
||||||
|
.unwrap_or(0);
|
||||||
|
|
||||||
|
HttpResponse::Ok().json(&EndpointResponse {
|
||||||
|
user_id: Some(user.id().unwrap()),
|
||||||
|
counter,
|
||||||
|
session_status: session_status(session),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn logout(user: Option<Identity>) -> HttpResponse {
|
||||||
|
if let Some(user) = user {
|
||||||
|
user.logout();
|
||||||
|
}
|
||||||
|
HttpResponse::Ok().finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn identity_required(_identity: Identity) -> HttpResponse {
|
||||||
|
HttpResponse::Ok().finish()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn session_status(session: Session) -> String {
|
||||||
|
match session.status() {
|
||||||
|
SessionStatus::Changed => "changed",
|
||||||
|
SessionStatus::Purged => "purged",
|
||||||
|
SessionStatus::Renewed => "renewed",
|
||||||
|
SessionStatus::Unchanged => "unchanged",
|
||||||
|
}
|
||||||
|
.into()
|
||||||
|
}
|
@ -1,18 +1,41 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## Unreleased - 2022-xx-xx
|
## Unreleased
|
||||||
|
|
||||||
|
- Update `redis` dependency to `0.29`.
|
||||||
|
- Update `actix-session` dependency to `0.9`.
|
||||||
|
|
||||||
## 0.2.0 - 2022-03-22
|
## 0.5.1
|
||||||
- Update Actix Web dependency to v4 ecosystem. [#229]
|
|
||||||
- Update Tokio dependencies to v1 ecosystem. [#229]
|
|
||||||
- Rename `Limiter::{build => builder}()`. [#232]
|
|
||||||
- Rename `Builder::{finish => build}()`. [#232]
|
|
||||||
- Exceeding the rate limit now returns a 429 Too Many Requests response. [#232]
|
|
||||||
|
|
||||||
[#229]: https://github.com/actix/actix-extras/pull/229
|
- No significant changes since `0.5.0`.
|
||||||
[#232]: https://github.com/actix/actix-extras/pull/232
|
|
||||||
|
|
||||||
|
## 0.5.0
|
||||||
|
|
||||||
|
- Update `redis` dependency to `0.23`.
|
||||||
|
- Update `actix-session` dependency to `0.8`.
|
||||||
|
|
||||||
|
## 0.4.0
|
||||||
|
|
||||||
|
- Add `Builder::key_by` for setting a custom rate limit key function.
|
||||||
|
- Implement `Default` for `RateLimiter`.
|
||||||
|
- `RateLimiter` is marked `#[non_exhaustive]`; use `RateLimiter::default()` instead.
|
||||||
|
- In the middleware errors from the count function are matched and respond with `INTERNAL_SERVER_ERROR` if it's an unexpected error, instead of the default `TOO_MANY_REQUESTS`.
|
||||||
|
- Minimum supported Rust version (MSRV) is now 1.59 due to transitive `time` dependency.
|
||||||
|
|
||||||
|
## 0.3.0
|
||||||
|
|
||||||
|
- `Limiter::builder` now takes an `impl Into<String>`.
|
||||||
|
- Removed lifetime from `Builder`.
|
||||||
|
- Updated `actix-session` dependency to `0.7`.
|
||||||
|
|
||||||
|
## 0.2.0
|
||||||
|
|
||||||
|
- Update Actix Web dependency to v4 ecosystem.
|
||||||
|
- Update Tokio dependencies to v1 ecosystem.
|
||||||
|
- Rename `Limiter::{build => builder}()`.
|
||||||
|
- Rename `Builder::{finish => build}()`.
|
||||||
|
- Exceeding the rate limit now returns a 429 Too Many Requests response.
|
||||||
|
|
||||||
|
## 0.1.4
|
||||||
|
|
||||||
## 0.1.4 - 2022-03-18
|
|
||||||
- Adopted into @actix org from <https://github.com/0xmad/actix-limitation>.
|
- Adopted into @actix org from <https://github.com/0xmad/actix-limitation>.
|
||||||
|
@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-limitation"
|
name = "actix-limitation"
|
||||||
version = "0.2.0"
|
version = "0.5.1"
|
||||||
authors = [
|
authors = [
|
||||||
"0xmad <0xmad@users.noreply.github.com>",
|
"0xmad <0xmad@users.noreply.github.com>",
|
||||||
"Rob Ede <robjtede@icloud.com>",
|
"Rob Ede <robjtede@icloud.com>",
|
||||||
@ -8,22 +8,36 @@ authors = [
|
|||||||
description = "Rate limiter using a fixed window counter for arbitrary keys, backed by Redis for Actix Web"
|
description = "Rate limiter using a fixed window counter for arbitrary keys, backed by Redis for Actix Web"
|
||||||
keywords = ["actix-web", "rate-api", "rate-limit", "limitation"]
|
keywords = ["actix-web", "rate-api", "rate-limit", "limitation"]
|
||||||
categories = ["asynchronous", "web-programming"]
|
categories = ["asynchronous", "web-programming"]
|
||||||
repository = "https://github.com/actix/actix-extras.git"
|
repository = "https://github.com/actix/actix-extras"
|
||||||
license = "MIT OR Apache-2.0"
|
license.workspace = true
|
||||||
edition = "2018"
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
|
||||||
|
[package.metadata.docs.rs]
|
||||||
|
rustdoc-args = ["--cfg", "docsrs"]
|
||||||
|
all-features = true
|
||||||
|
|
||||||
|
[features]
|
||||||
|
default = ["session"]
|
||||||
|
session = ["actix-session"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-session = "0.5"
|
|
||||||
actix-utils = "3"
|
actix-utils = "3"
|
||||||
actix-web = { version = "4", default-features = false }
|
actix-web = { version = "4", default-features = false, features = ["cookies"] }
|
||||||
|
|
||||||
chrono = "0.4"
|
chrono = "0.4"
|
||||||
derive_more = "0.99.5"
|
derive_more = { version = "2", features = ["display", "error", "from"] }
|
||||||
log = "0.4"
|
log = "0.4"
|
||||||
redis = { version = "0.21", default-features = false, features = ["tokio-comp"] }
|
redis = { version = "0.29", default-features = false, features = ["tokio-comp"] }
|
||||||
time = "0.3"
|
time = "0.3"
|
||||||
|
|
||||||
|
# session
|
||||||
|
actix-session = { version = "0.10", optional = true }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-web = "4"
|
actix-web = "4"
|
||||||
uuid = { version = "0.8", features = ["v4"] }
|
|
||||||
static_assertions = "1"
|
static_assertions = "1"
|
||||||
|
uuid = { version = "1", features = ["v4"] }
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
|
@ -3,23 +3,28 @@
|
|||||||
> Rate limiter using a fixed window counter for arbitrary keys, backed by Redis for Actix Web.
|
> Rate limiter using a fixed window counter for arbitrary keys, backed by Redis for Actix Web.
|
||||||
> Originally based on <https://github.com/fnichol/limitation>.
|
> Originally based on <https://github.com/fnichol/limitation>.
|
||||||
|
|
||||||
|
<!-- prettier-ignore-start -->
|
||||||
|
|
||||||
[](https://crates.io/crates/actix-limitation)
|
[](https://crates.io/crates/actix-limitation)
|
||||||
[](https://docs.rs/actix-limitation/0.2.0)
|
[](https://docs.rs/actix-limitation/0.5.1)
|
||||||

|

|
||||||
[](https://deps.rs/crate/actix-limitation/0.2.0)
|
[](https://deps.rs/crate/actix-limitation/0.5.1)
|
||||||
|
|
||||||
|
<!-- prettier-ignore-end -->
|
||||||
|
|
||||||
## Examples
|
## Examples
|
||||||
|
|
||||||
```toml
|
```toml
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = "4"
|
actix-web = "4"
|
||||||
actix-limitation = "0.1.4"
|
actix-limitation = "0.5"
|
||||||
```
|
```
|
||||||
|
|
||||||
```rust
|
```rust
|
||||||
use std::time::Duration;
|
|
||||||
use actix_web::{get, web, App, HttpServer, Responder};
|
|
||||||
use actix_limitation::{Limiter, RateLimiter};
|
use actix_limitation::{Limiter, RateLimiter};
|
||||||
|
use actix_session::SessionExt as _;
|
||||||
|
use actix_web::{dev::ServiceRequest, get, web, App, HttpServer, Responder};
|
||||||
|
use std::{sync::Arc, time::Duration};
|
||||||
|
|
||||||
#[get("/{id}/{name}")]
|
#[get("/{id}/{name}")]
|
||||||
async fn index(info: web::Path<(u32, String)>) -> impl Responder {
|
async fn index(info: web::Path<(u32, String)>) -> impl Responder {
|
||||||
@ -29,22 +34,24 @@ async fn index(info: web::Path<(u32, String)>) -> impl Responder {
|
|||||||
#[actix_web::main]
|
#[actix_web::main]
|
||||||
async fn main() -> std::io::Result<()> {
|
async fn main() -> std::io::Result<()> {
|
||||||
let limiter = web::Data::new(
|
let limiter = web::Data::new(
|
||||||
Limiter::build("redis://127.0.0.1")
|
Limiter::builder("redis://127.0.0.1")
|
||||||
.cookie_name("session-id".to_owned())
|
.key_by(|req: &ServiceRequest| {
|
||||||
.session_key("rate-api-id".to_owned())
|
req.get_session()
|
||||||
|
.get(&"session-id")
|
||||||
|
.unwrap_or_else(|_| req.cookie(&"rate-api-id").map(|c| c.to_string()))
|
||||||
|
})
|
||||||
.limit(5000)
|
.limit(5000)
|
||||||
.period(Duration::from_secs(3600)) // 60 minutes
|
.period(Duration::from_secs(3600)) // 60 minutes
|
||||||
.finish()
|
.build()
|
||||||
.expect("Can't build actix-limiter"),
|
.unwrap(),
|
||||||
);
|
);
|
||||||
|
|
||||||
HttpServer::new(move || {
|
HttpServer::new(move || {
|
||||||
App::new()
|
App::new()
|
||||||
.wrap(RateLimiter)
|
.wrap(RateLimiter::default())
|
||||||
.app_data(limiter.clone())
|
.app_data(limiter.clone())
|
||||||
.service(index)
|
.service(index)
|
||||||
})
|
})
|
||||||
.bind("127.0.0.1:8080")?
|
.bind(("127.0.0.1", 8080))?
|
||||||
.run()
|
.run()
|
||||||
.await
|
.await
|
||||||
}
|
}
|
||||||
|
@ -1,20 +1,25 @@
|
|||||||
use std::{borrow::Cow, time::Duration};
|
use std::{borrow::Cow, sync::Arc, time::Duration};
|
||||||
|
|
||||||
|
#[cfg(feature = "session")]
|
||||||
|
use actix_session::SessionExt as _;
|
||||||
|
use actix_web::dev::ServiceRequest;
|
||||||
use redis::Client;
|
use redis::Client;
|
||||||
|
|
||||||
use crate::{errors::Error, Limiter};
|
use crate::{errors::Error, GetArcBoxKeyFn, Limiter};
|
||||||
|
|
||||||
/// Rate limit builder.
|
/// Rate limiter builder.
|
||||||
#[derive(Debug)]
|
#[derive(Debug)]
|
||||||
pub struct Builder<'a> {
|
pub struct Builder {
|
||||||
pub(crate) redis_url: &'a str,
|
pub(crate) redis_url: String,
|
||||||
pub(crate) limit: usize,
|
pub(crate) limit: usize,
|
||||||
pub(crate) period: Duration,
|
pub(crate) period: Duration,
|
||||||
|
pub(crate) get_key_fn: Option<GetArcBoxKeyFn>,
|
||||||
pub(crate) cookie_name: Cow<'static, str>,
|
pub(crate) cookie_name: Cow<'static, str>,
|
||||||
|
#[cfg(feature = "session")]
|
||||||
pub(crate) session_key: Cow<'static, str>,
|
pub(crate) session_key: Cow<'static, str>,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Builder<'_> {
|
impl Builder {
|
||||||
/// Set upper limit.
|
/// Set upper limit.
|
||||||
pub fn limit(&mut self, limit: usize) -> &mut Self {
|
pub fn limit(&mut self, limit: usize) -> &mut Self {
|
||||||
self.limit = limit;
|
self.limit = limit;
|
||||||
@ -27,14 +32,38 @@ impl Builder<'_> {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set name of cookie to be sent.
|
/// Sets rate limit key derivation function.
|
||||||
|
///
|
||||||
|
/// Should not be used in combination with `cookie_name` or `session_key` as they conflict.
|
||||||
|
pub fn key_by<F>(&mut self, resolver: F) -> &mut Self
|
||||||
|
where
|
||||||
|
F: Fn(&ServiceRequest) -> Option<String> + Send + Sync + 'static,
|
||||||
|
{
|
||||||
|
self.get_key_fn = Some(Arc::new(resolver));
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Sets name of cookie to be sent.
|
||||||
|
///
|
||||||
|
/// This method should not be used in combination of `key_by` as they conflict.
|
||||||
|
#[deprecated = "Prefer `key_by`."]
|
||||||
pub fn cookie_name(&mut self, cookie_name: impl Into<Cow<'static, str>>) -> &mut Self {
|
pub fn cookie_name(&mut self, cookie_name: impl Into<Cow<'static, str>>) -> &mut Self {
|
||||||
|
if self.get_key_fn.is_some() {
|
||||||
|
panic!("This method should not be used in combination of get_key as they overwrite each other")
|
||||||
|
}
|
||||||
self.cookie_name = cookie_name.into();
|
self.cookie_name = cookie_name.into();
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Set session key to be used in backend.
|
/// Sets session key to be used in backend.
|
||||||
|
///
|
||||||
|
/// This method should not be used in combination of `key_by` as they conflict.
|
||||||
|
#[deprecated = "Prefer `key_by`."]
|
||||||
|
#[cfg(feature = "session")]
|
||||||
pub fn session_key(&mut self, session_key: impl Into<Cow<'static, str>>) -> &mut Self {
|
pub fn session_key(&mut self, session_key: impl Into<Cow<'static, str>>) -> &mut Self {
|
||||||
|
if self.get_key_fn.is_some() {
|
||||||
|
panic!("This method should not be used in combination of get_key as they overwrite each other")
|
||||||
|
}
|
||||||
self.session_key = session_key.into();
|
self.session_key = session_key.into();
|
||||||
self
|
self
|
||||||
}
|
}
|
||||||
@ -43,13 +72,35 @@ impl Builder<'_> {
|
|||||||
///
|
///
|
||||||
/// Note that this method will connect to the Redis server to test its connection which is a
|
/// Note that this method will connect to the Redis server to test its connection which is a
|
||||||
/// **synchronous** operation.
|
/// **synchronous** operation.
|
||||||
pub fn build(&self) -> Result<Limiter, Error> {
|
pub fn build(&mut self) -> Result<Limiter, Error> {
|
||||||
|
let get_key = if let Some(resolver) = self.get_key_fn.clone() {
|
||||||
|
resolver
|
||||||
|
} else {
|
||||||
|
let cookie_name = self.cookie_name.clone();
|
||||||
|
|
||||||
|
#[cfg(feature = "session")]
|
||||||
|
let session_key = self.session_key.clone();
|
||||||
|
|
||||||
|
let closure: GetArcBoxKeyFn = Arc::new(Box::new(move |req: &ServiceRequest| {
|
||||||
|
#[cfg(feature = "session")]
|
||||||
|
let res = req
|
||||||
|
.get_session()
|
||||||
|
.get(&session_key)
|
||||||
|
.unwrap_or_else(|_| req.cookie(&cookie_name).map(|c| c.to_string()));
|
||||||
|
|
||||||
|
#[cfg(not(feature = "session"))]
|
||||||
|
let res = req.cookie(&cookie_name).map(|c| c.to_string());
|
||||||
|
|
||||||
|
res
|
||||||
|
}));
|
||||||
|
closure
|
||||||
|
};
|
||||||
|
|
||||||
Ok(Limiter {
|
Ok(Limiter {
|
||||||
client: Client::open(self.redis_url)?,
|
client: Client::open(self.redis_url.as_str())?,
|
||||||
limit: self.limit,
|
limit: self.limit,
|
||||||
period: self.period,
|
period: self.period,
|
||||||
cookie_name: self.cookie_name.clone(),
|
get_key_fn: get_key,
|
||||||
session_key: self.session_key.clone(),
|
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -63,16 +114,19 @@ mod tests {
|
|||||||
let redis_url = "redis://127.0.0.1";
|
let redis_url = "redis://127.0.0.1";
|
||||||
let period = Duration::from_secs(10);
|
let period = Duration::from_secs(10);
|
||||||
let builder = Builder {
|
let builder = Builder {
|
||||||
redis_url,
|
redis_url: redis_url.to_owned(),
|
||||||
limit: 100,
|
limit: 100,
|
||||||
period,
|
period,
|
||||||
|
get_key_fn: Some(Arc::new(|_| None)),
|
||||||
cookie_name: Cow::Owned("session".to_string()),
|
cookie_name: Cow::Owned("session".to_string()),
|
||||||
|
#[cfg(feature = "session")]
|
||||||
session_key: Cow::Owned("rate-api".to_string()),
|
session_key: Cow::Owned("rate-api".to_string()),
|
||||||
};
|
};
|
||||||
|
|
||||||
assert_eq!(builder.redis_url, redis_url);
|
assert_eq!(builder.redis_url, redis_url);
|
||||||
assert_eq!(builder.limit, 100);
|
assert_eq!(builder.limit, 100);
|
||||||
assert_eq!(builder.period, period);
|
assert_eq!(builder.period, period);
|
||||||
|
#[cfg(feature = "session")]
|
||||||
assert_eq!(builder.session_key, "rate-api");
|
assert_eq!(builder.session_key, "rate-api");
|
||||||
assert_eq!(builder.cookie_name, "session");
|
assert_eq!(builder.cookie_name, "session");
|
||||||
}
|
}
|
||||||
@ -82,25 +136,19 @@ mod tests {
|
|||||||
let redis_url = "redis://127.0.0.1";
|
let redis_url = "redis://127.0.0.1";
|
||||||
let period = Duration::from_secs(20);
|
let period = Duration::from_secs(20);
|
||||||
let mut builder = Builder {
|
let mut builder = Builder {
|
||||||
redis_url,
|
redis_url: redis_url.to_owned(),
|
||||||
limit: 100,
|
limit: 100,
|
||||||
period: Duration::from_secs(10),
|
period: Duration::from_secs(10),
|
||||||
session_key: Cow::Borrowed("key"),
|
get_key_fn: Some(Arc::new(|_| None)),
|
||||||
cookie_name: Cow::Borrowed("sid"),
|
cookie_name: Cow::Borrowed("sid"),
|
||||||
|
#[cfg(feature = "session")]
|
||||||
|
session_key: Cow::Borrowed("key"),
|
||||||
};
|
};
|
||||||
|
|
||||||
let limiter = builder
|
let limiter = builder.limit(200).period(period).build().unwrap();
|
||||||
.limit(200)
|
|
||||||
.period(period)
|
|
||||||
.cookie_name("session".to_string())
|
|
||||||
.session_key("rate-api".to_string())
|
|
||||||
.build()
|
|
||||||
.unwrap();
|
|
||||||
|
|
||||||
assert_eq!(limiter.limit, 200);
|
assert_eq!(limiter.limit, 200);
|
||||||
assert_eq!(limiter.period, period);
|
assert_eq!(limiter.period, period);
|
||||||
assert_eq!(limiter.session_key, "rate-api");
|
|
||||||
assert_eq!(limiter.cookie_name, "session");
|
|
||||||
}
|
}
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
@ -109,11 +157,13 @@ mod tests {
|
|||||||
let redis_url = "127.0.0.1";
|
let redis_url = "127.0.0.1";
|
||||||
let period = Duration::from_secs(20);
|
let period = Duration::from_secs(20);
|
||||||
let mut builder = Builder {
|
let mut builder = Builder {
|
||||||
redis_url,
|
redis_url: redis_url.to_owned(),
|
||||||
limit: 100,
|
limit: 100,
|
||||||
period: Duration::from_secs(10),
|
period: Duration::from_secs(10),
|
||||||
session_key: Cow::Borrowed("key"),
|
get_key_fn: Some(Arc::new(|_| None)),
|
||||||
cookie_name: Cow::Borrowed("sid"),
|
cookie_name: Cow::Borrowed("sid"),
|
||||||
|
#[cfg(feature = "session")]
|
||||||
|
session_key: Cow::Borrowed("key"),
|
||||||
};
|
};
|
||||||
|
|
||||||
builder.limit(200).period(period).build().unwrap();
|
builder.limit(200).period(period).build().unwrap();
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
use derive_more::{Display, Error, From};
|
use derive_more::derive::{Display, Error, From};
|
||||||
|
|
||||||
use crate::status::Status;
|
use crate::status::Status;
|
||||||
|
|
||||||
@ -6,20 +6,20 @@ use crate::status::Status;
|
|||||||
#[derive(Debug, Display, Error, From)]
|
#[derive(Debug, Display, Error, From)]
|
||||||
pub enum Error {
|
pub enum Error {
|
||||||
/// Redis client failed to connect or run a query.
|
/// Redis client failed to connect or run a query.
|
||||||
#[display(fmt = "Redis client failed to connect or run a query")]
|
#[display("Redis client failed to connect or run a query")]
|
||||||
Client(redis::RedisError),
|
Client(redis::RedisError),
|
||||||
|
|
||||||
/// Limit is exceeded for a key.
|
/// Limit is exceeded for a key.
|
||||||
#[display(fmt = "Limit is exceeded for a key")]
|
#[display("Limit is exceeded for a key")]
|
||||||
#[from(ignore)]
|
#[from(ignore)]
|
||||||
LimitExceeded(#[error(not(source))] Status),
|
LimitExceeded(#[error(not(source))] Status),
|
||||||
|
|
||||||
/// Time conversion failed.
|
/// Time conversion failed.
|
||||||
#[display(fmt = "Time conversion failed")]
|
#[display("Time conversion failed")]
|
||||||
Time(time::error::ComponentRange),
|
Time(time::error::ComponentRange),
|
||||||
|
|
||||||
/// Generic error.
|
/// Generic error.
|
||||||
#[display(fmt = "Generic error")]
|
#[display("Generic error")]
|
||||||
#[from(ignore)]
|
#[from(ignore)]
|
||||||
Other(#[error(not(source))] String),
|
Other(#[error(not(source))] String),
|
||||||
}
|
}
|
||||||
|
@ -3,12 +3,13 @@
|
|||||||
//! ```toml
|
//! ```toml
|
||||||
//! [dependencies]
|
//! [dependencies]
|
||||||
//! actix-web = "4"
|
//! actix-web = "4"
|
||||||
//! actix-limitation = "0.1.4"
|
#![doc = concat!("actix-limitation = \"", env!("CARGO_PKG_VERSION_MAJOR"), ".", env!("CARGO_PKG_VERSION_MINOR"),"\"")]
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! ```no_run
|
//! ```no_run
|
||||||
//! use std::time::Duration;
|
//! use std::{sync::Arc, time::Duration};
|
||||||
//! use actix_web::{get, web, App, HttpServer, Responder};
|
//! use actix_web::{dev::ServiceRequest, get, web, App, HttpServer, Responder};
|
||||||
|
//! use actix_session::SessionExt as _;
|
||||||
//! use actix_limitation::{Limiter, RateLimiter};
|
//! use actix_limitation::{Limiter, RateLimiter};
|
||||||
//!
|
//!
|
||||||
//! #[get("/{id}/{name}")]
|
//! #[get("/{id}/{name}")]
|
||||||
@ -20,8 +21,11 @@
|
|||||||
//! async fn main() -> std::io::Result<()> {
|
//! async fn main() -> std::io::Result<()> {
|
||||||
//! let limiter = web::Data::new(
|
//! let limiter = web::Data::new(
|
||||||
//! Limiter::builder("redis://127.0.0.1")
|
//! Limiter::builder("redis://127.0.0.1")
|
||||||
//! .cookie_name("session-id".to_owned())
|
//! .key_by(|req: &ServiceRequest| {
|
||||||
//! .session_key("rate-api-id".to_owned())
|
//! req.get_session()
|
||||||
|
//! .get(&"session-id")
|
||||||
|
//! .unwrap_or_else(|_| req.cookie(&"rate-api-id").map(|c| c.to_string()))
|
||||||
|
//! })
|
||||||
//! .limit(5000)
|
//! .limit(5000)
|
||||||
//! .period(Duration::from_secs(3600)) // 60 minutes
|
//! .period(Duration::from_secs(3600)) // 60 minutes
|
||||||
//! .build()
|
//! .build()
|
||||||
@ -30,24 +34,25 @@
|
|||||||
//!
|
//!
|
||||||
//! HttpServer::new(move || {
|
//! HttpServer::new(move || {
|
||||||
//! App::new()
|
//! App::new()
|
||||||
//! .wrap(RateLimiter)
|
//! .wrap(RateLimiter::default())
|
||||||
//! .app_data(limiter.clone())
|
//! .app_data(limiter.clone())
|
||||||
//! .service(index)
|
//! .service(index)
|
||||||
//! })
|
//! })
|
||||||
//! .bind("127.0.0.1:8080")?
|
//! .bind(("127.0.0.1", 8080))?
|
||||||
//! .run()
|
//! .run()
|
||||||
//! .await
|
//! .await
|
||||||
//! }
|
//! }
|
||||||
//! ```
|
//! ```
|
||||||
|
|
||||||
#![forbid(unsafe_code)]
|
#![forbid(unsafe_code)]
|
||||||
#![deny(rust_2018_idioms, nonstandard_style)]
|
#![warn(missing_docs, missing_debug_implementations)]
|
||||||
#![warn(future_incompatible, missing_docs, missing_debug_implementations)]
|
|
||||||
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
|
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
|
||||||
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
|
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
|
||||||
|
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||||
|
|
||||||
use std::{borrow::Cow, time::Duration};
|
use std::{borrow::Cow, fmt, sync::Arc, time::Duration};
|
||||||
|
|
||||||
|
use actix_web::dev::ServiceRequest;
|
||||||
use redis::Client;
|
use redis::Client;
|
||||||
|
|
||||||
mod builder;
|
mod builder;
|
||||||
@ -55,10 +60,7 @@ mod errors;
|
|||||||
mod middleware;
|
mod middleware;
|
||||||
mod status;
|
mod status;
|
||||||
|
|
||||||
pub use self::builder::Builder;
|
pub use self::{builder::Builder, errors::Error, middleware::RateLimiter, status::Status};
|
||||||
pub use self::errors::Error;
|
|
||||||
pub use self::middleware::RateLimiter;
|
|
||||||
pub use self::status::Status;
|
|
||||||
|
|
||||||
/// Default request limit.
|
/// Default request limit.
|
||||||
pub const DEFAULT_REQUEST_LIMIT: usize = 5000;
|
pub const DEFAULT_REQUEST_LIMIT: usize = 5000;
|
||||||
@ -70,16 +72,34 @@ pub const DEFAULT_PERIOD_SECS: u64 = 3600;
|
|||||||
pub const DEFAULT_COOKIE_NAME: &str = "sid";
|
pub const DEFAULT_COOKIE_NAME: &str = "sid";
|
||||||
|
|
||||||
/// Default session key.
|
/// Default session key.
|
||||||
|
#[cfg(feature = "session")]
|
||||||
pub const DEFAULT_SESSION_KEY: &str = "rate-api-id";
|
pub const DEFAULT_SESSION_KEY: &str = "rate-api-id";
|
||||||
|
|
||||||
|
/// Helper trait to impl Debug on GetKeyFn type
|
||||||
|
trait GetKeyFnT: Fn(&ServiceRequest) -> Option<String> {}
|
||||||
|
|
||||||
|
impl<T> GetKeyFnT for T where T: Fn(&ServiceRequest) -> Option<String> {}
|
||||||
|
|
||||||
|
/// Get key function type with auto traits
|
||||||
|
type GetKeyFn = dyn GetKeyFnT + Send + Sync;
|
||||||
|
|
||||||
|
/// Get key resolver function type
|
||||||
|
impl fmt::Debug for GetKeyFn {
|
||||||
|
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
|
||||||
|
write!(f, "GetKeyFn")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Wrapped Get key function Trait
|
||||||
|
type GetArcBoxKeyFn = Arc<GetKeyFn>;
|
||||||
|
|
||||||
/// Rate limiter.
|
/// Rate limiter.
|
||||||
#[derive(Clone, Debug)]
|
#[derive(Debug, Clone)]
|
||||||
pub struct Limiter {
|
pub struct Limiter {
|
||||||
client: Client,
|
client: Client,
|
||||||
limit: usize,
|
limit: usize,
|
||||||
period: Duration,
|
period: Duration,
|
||||||
cookie_name: Cow<'static, str>,
|
get_key_fn: GetArcBoxKeyFn,
|
||||||
session_key: Cow<'static, str>,
|
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Limiter {
|
impl Limiter {
|
||||||
@ -88,12 +108,14 @@ impl Limiter {
|
|||||||
/// See [`redis-rs` docs](https://docs.rs/redis/0.21/redis/#connection-parameters) on connection
|
/// See [`redis-rs` docs](https://docs.rs/redis/0.21/redis/#connection-parameters) on connection
|
||||||
/// parameters for how to set the Redis URL.
|
/// parameters for how to set the Redis URL.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub fn builder(redis_url: &str) -> Builder<'_> {
|
pub fn builder(redis_url: impl Into<String>) -> Builder {
|
||||||
Builder {
|
Builder {
|
||||||
redis_url,
|
redis_url: redis_url.into(),
|
||||||
limit: DEFAULT_REQUEST_LIMIT,
|
limit: DEFAULT_REQUEST_LIMIT,
|
||||||
period: Duration::from_secs(DEFAULT_PERIOD_SECS),
|
period: Duration::from_secs(DEFAULT_PERIOD_SECS),
|
||||||
|
get_key_fn: None,
|
||||||
cookie_name: Cow::Borrowed(DEFAULT_COOKIE_NAME),
|
cookie_name: Cow::Borrowed(DEFAULT_COOKIE_NAME),
|
||||||
|
#[cfg(feature = "session")]
|
||||||
session_key: Cow::Borrowed(DEFAULT_SESSION_KEY),
|
session_key: Cow::Borrowed(DEFAULT_SESSION_KEY),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -115,7 +137,7 @@ impl Limiter {
|
|||||||
let key = key.into();
|
let key = key.into();
|
||||||
let expires = self.period.as_secs();
|
let expires = self.period.as_secs();
|
||||||
|
|
||||||
let mut connection = self.client.get_tokio_connection().await?;
|
let mut connection = self.client.get_multiplexed_tokio_connection().await?;
|
||||||
|
|
||||||
// The seed of this approach is outlined Atul R in a blog post about rate limiting using
|
// The seed of this approach is outlined Atul R in a blog post about rate limiting using
|
||||||
// NodeJS and Redis. For more details, see https://blog.atulr.com/rate-limiter
|
// NodeJS and Redis. For more details, see https://blog.atulr.com/rate-limiter
|
||||||
@ -146,14 +168,12 @@ mod tests {
|
|||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
fn test_create_limiter() {
|
fn test_create_limiter() {
|
||||||
let builder = Limiter::builder("redis://127.0.0.1:6379/1");
|
let mut builder = Limiter::builder("redis://127.0.0.1:6379/1");
|
||||||
let limiter = builder.build();
|
let limiter = builder.build();
|
||||||
assert!(limiter.is_ok());
|
assert!(limiter.is_ok());
|
||||||
|
|
||||||
let limiter = limiter.unwrap();
|
let limiter = limiter.unwrap();
|
||||||
assert_eq!(limiter.limit, 5000);
|
assert_eq!(limiter.limit, 5000);
|
||||||
assert_eq!(limiter.period, Duration::from_secs(3600));
|
assert_eq!(limiter.period, Duration::from_secs(3600));
|
||||||
assert_eq!(limiter.cookie_name, DEFAULT_COOKIE_NAME);
|
|
||||||
assert_eq!(limiter.session_key, DEFAULT_SESSION_KEY);
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,19 +1,18 @@
|
|||||||
use std::{future::Future, pin::Pin, rc::Rc};
|
use std::{future::Future, pin::Pin, rc::Rc};
|
||||||
|
|
||||||
use actix_session::UserSession;
|
|
||||||
use actix_utils::future::{ok, Ready};
|
use actix_utils::future::{ok, Ready};
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
body::EitherBody,
|
body::EitherBody,
|
||||||
cookie::Cookie,
|
|
||||||
dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
|
dev::{forward_ready, Service, ServiceRequest, ServiceResponse, Transform},
|
||||||
http::{header::COOKIE, StatusCode},
|
http::StatusCode,
|
||||||
web, Error, HttpResponse,
|
web, Error, HttpResponse,
|
||||||
};
|
};
|
||||||
|
|
||||||
use crate::Limiter;
|
use crate::{Error as LimitationError, Limiter};
|
||||||
|
|
||||||
/// Rate limit middleware.
|
/// Rate limit middleware.
|
||||||
#[derive(Debug)]
|
#[derive(Debug, Default)]
|
||||||
|
#[non_exhaustive]
|
||||||
pub struct RateLimiter;
|
pub struct RateLimiter;
|
||||||
|
|
||||||
impl<S, B> Transform<S, ServiceRequest> for RateLimiter
|
impl<S, B> Transform<S, ServiceRequest> for RateLimiter
|
||||||
@ -54,20 +53,17 @@ where
|
|||||||
forward_ready!(service);
|
forward_ready!(service);
|
||||||
|
|
||||||
fn call(&self, req: ServiceRequest) -> Self::Future {
|
fn call(&self, req: ServiceRequest) -> Self::Future {
|
||||||
// A mis-configuration of the Actix App will result in a **runtime** failure, so the expect
|
// A misconfiguration of the Actix App will result in a **runtime** failure, so the expect
|
||||||
// method description is important context for the developer.
|
// method description is important context for the developer.
|
||||||
let limiter = req
|
let limiter = req
|
||||||
.app_data::<web::Data<Limiter>>()
|
.app_data::<web::Data<Limiter>>()
|
||||||
.expect("web::Data<Limiter> should be set in app data for RateLimiter middleware")
|
.expect("web::Data<Limiter> should be set in app data for RateLimiter middleware")
|
||||||
.clone();
|
.clone();
|
||||||
|
|
||||||
let (key, fallback) = key(&req, limiter.clone());
|
let key = (limiter.get_key_fn)(&req);
|
||||||
|
|
||||||
let service = Rc::clone(&self.service);
|
let service = Rc::clone(&self.service);
|
||||||
|
|
||||||
let key = match key {
|
let key = match key {
|
||||||
Some(key) => key,
|
|
||||||
None => match fallback {
|
|
||||||
Some(key) => key,
|
Some(key) => key,
|
||||||
None => {
|
None => {
|
||||||
return Box::pin(async move {
|
return Box::pin(async move {
|
||||||
@ -77,18 +73,37 @@ where
|
|||||||
.map(ServiceResponse::map_into_left_body)
|
.map(ServiceResponse::map_into_left_body)
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
},
|
|
||||||
};
|
};
|
||||||
|
|
||||||
Box::pin(async move {
|
Box::pin(async move {
|
||||||
let status = limiter.count(key.to_string()).await;
|
let status = limiter.count(key.to_string()).await;
|
||||||
|
|
||||||
if status.is_err() {
|
if let Err(err) = status {
|
||||||
|
match err {
|
||||||
|
LimitationError::LimitExceeded(_) => {
|
||||||
log::warn!("Rate limit exceed error for {}", key);
|
log::warn!("Rate limit exceed error for {}", key);
|
||||||
|
|
||||||
Ok(req.into_response(
|
Ok(req.into_response(
|
||||||
HttpResponse::new(StatusCode::TOO_MANY_REQUESTS).map_into_right_body(),
|
HttpResponse::new(StatusCode::TOO_MANY_REQUESTS).map_into_right_body(),
|
||||||
))
|
))
|
||||||
|
}
|
||||||
|
LimitationError::Client(e) => {
|
||||||
|
log::error!("Client request failed, redis error: {}", e);
|
||||||
|
|
||||||
|
Ok(req.into_response(
|
||||||
|
HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
.map_into_right_body(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
_ => {
|
||||||
|
log::error!("Count failed: {}", err);
|
||||||
|
|
||||||
|
Ok(req.into_response(
|
||||||
|
HttpResponse::new(StatusCode::INTERNAL_SERVER_ERROR)
|
||||||
|
.map_into_right_body(),
|
||||||
|
))
|
||||||
|
}
|
||||||
|
}
|
||||||
} else {
|
} else {
|
||||||
service
|
service
|
||||||
.call(req)
|
.call(req)
|
||||||
@ -98,19 +113,3 @@ where
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
fn key(req: &ServiceRequest, limiter: web::Data<Limiter>) -> (Option<String>, Option<String>) {
|
|
||||||
let session = req.get_session();
|
|
||||||
let result: Option<String> = session.get(&limiter.session_key).unwrap_or(None);
|
|
||||||
let cookies = req.headers().get_all(COOKIE);
|
|
||||||
let cookie = cookies
|
|
||||||
.filter_map(|i| i.to_str().ok())
|
|
||||||
.find(|i| i.contains(limiter.cookie_name.as_ref()));
|
|
||||||
|
|
||||||
let fallback = match cookie {
|
|
||||||
Some(value) => Cookie::parse(value).ok().map(|i| i.to_string()),
|
|
||||||
None => None,
|
|
||||||
};
|
|
||||||
|
|
||||||
(result, fallback)
|
|
||||||
}
|
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
use std::{convert::TryInto, ops::Add, time::Duration};
|
use std::{ops::Add, time::Duration};
|
||||||
|
|
||||||
use chrono::SubsecRound as _;
|
use chrono::SubsecRound as _;
|
||||||
|
|
||||||
@ -16,7 +16,7 @@ impl Status {
|
|||||||
/// Constructs status limit status from parts.
|
/// Constructs status limit status from parts.
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub(crate) fn new(count: usize, limit: usize, reset_epoch_utc: usize) -> Self {
|
pub(crate) fn new(count: usize, limit: usize, reset_epoch_utc: usize) -> Self {
|
||||||
let remaining = if count >= limit { 0 } else { limit - count };
|
let remaining = limit.saturating_sub(count);
|
||||||
|
|
||||||
Status {
|
Status {
|
||||||
limit,
|
limit,
|
||||||
|
@ -1,9 +1,12 @@
|
|||||||
use actix_limitation::{Error, Limiter};
|
use std::time::Duration;
|
||||||
|
|
||||||
|
use actix_limitation::{Error, Limiter, RateLimiter};
|
||||||
|
use actix_web::{dev::ServiceRequest, http::StatusCode, test, web, App, HttpRequest, HttpResponse};
|
||||||
use uuid::Uuid;
|
use uuid::Uuid;
|
||||||
|
|
||||||
#[test]
|
#[test]
|
||||||
#[should_panic = "Redis URL did not parse"]
|
#[should_panic = "Redis URL did not parse"]
|
||||||
fn test_create_limiter_error() {
|
async fn test_create_limiter_error() {
|
||||||
Limiter::builder("127.0.0.1").build().unwrap();
|
Limiter::builder("127.0.0.1").build().unwrap();
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -18,7 +21,7 @@ async fn test_limiter_count() -> Result<(), Error> {
|
|||||||
|
|
||||||
for i in 0..20 {
|
for i in 0..20 {
|
||||||
let status = limiter.count(id.to_string()).await?;
|
let status = limiter.count(id.to_string()).await?;
|
||||||
println!("status: {:?}", status);
|
println!("status: {status:?}");
|
||||||
assert_eq!(20 - status.remaining(), i + 1);
|
assert_eq!(20 - status.remaining(), i + 1);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -51,3 +54,39 @@ async fn test_limiter_count_error() -> Result<(), Error> {
|
|||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[actix_web::test]
|
||||||
|
async fn test_limiter_key_by() -> Result<(), Error> {
|
||||||
|
let cooldown_period = Duration::from_secs(1);
|
||||||
|
let limiter = Limiter::builder("redis://127.0.0.1:6379/3")
|
||||||
|
.limit(2)
|
||||||
|
.period(cooldown_period)
|
||||||
|
.key_by(|_: &ServiceRequest| Some("fix_key".to_string()))
|
||||||
|
.build()
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
let app = test::init_service(
|
||||||
|
App::new()
|
||||||
|
.wrap(RateLimiter::default())
|
||||||
|
.app_data(web::Data::new(limiter))
|
||||||
|
.route(
|
||||||
|
"/",
|
||||||
|
web::get().to(|_: HttpRequest| async { HttpResponse::Ok().body("ok") }),
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
for _ in 1..2 {
|
||||||
|
for index in 1..4 {
|
||||||
|
let req = test::TestRequest::default().to_request();
|
||||||
|
let resp = test::call_service(&app, req).await;
|
||||||
|
if index <= 2 {
|
||||||
|
assert!(resp.status().is_success());
|
||||||
|
} else {
|
||||||
|
assert_eq!(resp.status(), StatusCode::TOO_MANY_REQUESTS);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
std::thread::sleep(cooldown_period);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
@ -1,28 +1,48 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## Unreleased - 2021-xx-xx
|
## Unreleased
|
||||||
|
|
||||||
|
## 0.11.0
|
||||||
|
|
||||||
|
- Updated `prost` dependency to `0.13`.
|
||||||
|
- Minimum supported Rust version (MSRV) is now 1.75.
|
||||||
|
|
||||||
|
## 0.10.0
|
||||||
|
|
||||||
|
- Updated `prost` dependency to `0.12`.
|
||||||
|
- Minimum supported Rust version (MSRV) is now 1.68.
|
||||||
|
|
||||||
|
## 0.9.0
|
||||||
|
|
||||||
|
- Added `application/x-protobuf` as an acceptable header.
|
||||||
|
- Updated `prost` dependency to `0.11`.
|
||||||
|
|
||||||
|
## 0.8.0
|
||||||
|
|
||||||
|
- Update `prost` dependency to `0.10`.
|
||||||
|
- Minimum supported Rust version (MSRV) is now 1.57 due to transitive `time` dependency.
|
||||||
|
|
||||||
|
## 0.7.0
|
||||||
|
|
||||||
## 0.7.0 - 2022-03-01
|
|
||||||
- Update `actix-web` dependency to `4`.
|
- Update `actix-web` dependency to `4`.
|
||||||
|
|
||||||
|
## 0.7.0-beta.5
|
||||||
|
|
||||||
## 0.7.0-beta.5 - 2022-02-03
|
|
||||||
- Update `prost` dependency to `0.9`.
|
- Update `prost` dependency to `0.9`.
|
||||||
- Update `actix-web` dependency to `4.0.0-rc.1`.
|
- Update `actix-web` dependency to `4.0.0-rc.1`.
|
||||||
|
|
||||||
|
## 0.7.0-beta.4
|
||||||
|
|
||||||
## 0.7.0-beta.4 - 2021-12-29
|
|
||||||
- Minimum supported Rust version (MSRV) is now 1.54.
|
- Minimum supported Rust version (MSRV) is now 1.54.
|
||||||
|
|
||||||
|
## 0.7.0-beta.3
|
||||||
|
|
||||||
## 0.7.0-beta.3 - 2021-12-12
|
|
||||||
- Update `actix-web` dependency to `4.0.0.beta-14`. [#209]
|
- Update `actix-web` dependency to `4.0.0.beta-14`. [#209]
|
||||||
|
|
||||||
[#209]: https://github.com/actix/actix-extras/pull/209
|
[#209]: https://github.com/actix/actix-extras/pull/209
|
||||||
|
|
||||||
|
## 0.7.0-beta.2
|
||||||
|
|
||||||
## 0.7.0-beta.2 - 2021-10-21
|
|
||||||
- Bump `prost` version to 0.8. [#197]
|
- Bump `prost` version to 0.8. [#197]
|
||||||
- Update `actix-web` dependency to v4.0.0-beta.10. [#203]
|
- Update `actix-web` dependency to v4.0.0-beta.10. [#203]
|
||||||
- Minimum supported Rust version (MSRV) is now 1.52.
|
- Minimum supported Rust version (MSRV) is now 1.52.
|
||||||
@ -30,52 +50,52 @@
|
|||||||
[#197]: https://github.com/actix/actix-extras/pull/197
|
[#197]: https://github.com/actix/actix-extras/pull/197
|
||||||
[#203]: https://github.com/actix/actix-extras/pull/203
|
[#203]: https://github.com/actix/actix-extras/pull/203
|
||||||
|
|
||||||
|
## 0.7.0-beta.1
|
||||||
|
|
||||||
## 0.7.0-beta.1 - 2021-06-27
|
|
||||||
- Bump `prost` version to 0.7. [#144]
|
- Bump `prost` version to 0.7. [#144]
|
||||||
- Update `actix-web` dependency to 4.0.0 beta.
|
- Update `actix-web` dependency to 4.0.0 beta.
|
||||||
- Minimum supported Rust version (MSRV) is now 1.46.0.
|
- Minimum supported Rust version (MSRV) is now 1.46.0.
|
||||||
|
|
||||||
[#144]: https://github.com/actix/actix-extras/pull/144
|
[#144]: https://github.com/actix/actix-extras/pull/144
|
||||||
|
|
||||||
|
## 0.6.0
|
||||||
|
|
||||||
## 0.6.0 - 2020-09-11
|
|
||||||
- Update `actix-web` dependency to 3.0.0.
|
- Update `actix-web` dependency to 3.0.0.
|
||||||
- Minimum supported Rust version (MSRV) is now 1.42.0 to use `matches!` macro.
|
- Minimum supported Rust version (MSRV) is now 1.42.0 to use `matches!` macro.
|
||||||
|
|
||||||
|
## 0.6.0-alpha.1
|
||||||
|
|
||||||
## 0.6.0-alpha.1 - 2020-07-06
|
|
||||||
- Update `actix-web` to 3.0.0-alpha.3
|
- Update `actix-web` to 3.0.0-alpha.3
|
||||||
- Minimum supported Rust version(MSRV) is now 1.40.0.
|
- Minimum supported Rust version(MSRV) is now 1.40.0.
|
||||||
- Minimize `futures` dependency
|
- Minimize `futures` dependency
|
||||||
|
|
||||||
|
|
||||||
## 0.5.1 - 2019-02-17
|
## 0.5.1 - 2019-02-17
|
||||||
|
|
||||||
- Move repository to actix-extras
|
- Move repository to actix-extras
|
||||||
|
|
||||||
|
|
||||||
## 0.5.0 - 2019-01-24
|
## 0.5.0 - 2019-01-24
|
||||||
|
|
||||||
- Migrate to actix-web 2.0.0 and std::future
|
- Migrate to actix-web 2.0.0 and std::future
|
||||||
- Update prost to 0.6
|
- Update prost to 0.6
|
||||||
- Update bytes to 0.5
|
- Update bytes to 0.5
|
||||||
|
|
||||||
|
|
||||||
## 0.4.1 - 2019-10-03
|
## 0.4.1 - 2019-10-03
|
||||||
|
|
||||||
- Upgrade prost and prost-derive to 0.5.0
|
- Upgrade prost and prost-derive to 0.5.0
|
||||||
|
|
||||||
|
|
||||||
## 0.4.0 - 2019-05-18
|
## 0.4.0 - 2019-05-18
|
||||||
|
|
||||||
- Upgrade to actix-web 1.0.0-rc
|
- Upgrade to actix-web 1.0.0-rc
|
||||||
- Removed `protobuf` method for `HttpRequest` (use `ProtoBuf` extractor instead)
|
- Removed `protobuf` method for `HttpRequest` (use `ProtoBuf` extractor instead)
|
||||||
|
|
||||||
|
|
||||||
## 0.3.0 - 2019-03-07
|
## 0.3.0 - 2019-03-07
|
||||||
|
|
||||||
- Upgrade to actix-web 0.7.18
|
- Upgrade to actix-web 0.7.18
|
||||||
|
|
||||||
|
|
||||||
## 0.2.0 - 2018-04-10
|
## 0.2.0 - 2018-04-10
|
||||||
|
|
||||||
- Provide protobuf extractor
|
- Provide protobuf extractor
|
||||||
|
|
||||||
|
|
||||||
## 0.1.0 - 2018-03-21
|
## 0.1.0 - 2018-03-21
|
||||||
|
|
||||||
- First release
|
- First release
|
||||||
|
@ -1,28 +1,31 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-protobuf"
|
name = "actix-protobuf"
|
||||||
version = "0.7.0"
|
version = "0.11.0"
|
||||||
edition = "2018"
|
|
||||||
authors = [
|
authors = [
|
||||||
"kingxsp <jin.hb.zh@outlook.com>",
|
"kingxsp <jin.hb.zh@outlook.com>",
|
||||||
"Yuki Okushi <huyuumi.dev@gmail.com>"
|
"Yuki Okushi <huyuumi.dev@gmail.com>",
|
||||||
]
|
]
|
||||||
description = "Protobuf support for Actix web"
|
description = "Protobuf payload extractor for Actix Web"
|
||||||
keywords = ["actix", "protobuf", "protocol", "rpc"]
|
keywords = ["actix", "web", "protobuf", "protocol", "rpc"]
|
||||||
homepage = "https://actix.rs"
|
repository.workspace = true
|
||||||
repository = "https://github.com/actix/actix-extras.git"
|
homepage.workspace = true
|
||||||
license = "MIT OR Apache-2.0"
|
license.workspace = true
|
||||||
exclude = [".cargo/config", "/examples/**"]
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
|
||||||
[lib]
|
[package.metadata.docs.rs]
|
||||||
name = "actix_protobuf"
|
rustdoc-args = ["--cfg", "docsrs"]
|
||||||
path = "src/lib.rs"
|
all-features = true
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-web = { version = "4", default_features = false }
|
actix-web = { version = "4", default-features = false }
|
||||||
derive_more = "0.99.5"
|
derive_more = { version = "2", features = ["display"] }
|
||||||
futures-util = { version = "0.3.7", default-features = false }
|
futures-util = { version = "0.3.17", default-features = false, features = ["std"] }
|
||||||
prost = { version = "0.9", default_features = false }
|
prost = { version = "0.13", default-features = false }
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-web = { version = "4", default_features = false, features = ["macros"] }
|
actix-web = { version = "4", default-features = false, features = ["macros"] }
|
||||||
prost = { version = "0.9", default_features = false, features = ["prost-derive"] }
|
prost = { version = "0.13", default-features = false, features = ["prost-derive"] }
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
|
@ -1,17 +1,21 @@
|
|||||||
# actix-protobuf
|
# actix-protobuf
|
||||||
|
|
||||||
> Protobuf support for Actix Web.
|
> Protobuf payload extractor for Actix Web.
|
||||||
|
|
||||||
|
<!-- prettier-ignore-start -->
|
||||||
|
|
||||||
[](https://crates.io/crates/actix-protobuf)
|
[](https://crates.io/crates/actix-protobuf)
|
||||||
[](https://docs.rs/actix-protobuf/0.7.0)
|
[](https://docs.rs/actix-protobuf/0.11.0)
|
||||||

|

|
||||||
[](https://deps.rs/crate/actix-protobuf/0.7.0)
|
[](https://deps.rs/crate/actix-protobuf/0.11.0)
|
||||||
|
|
||||||
|
<!-- prettier-ignore-end -->
|
||||||
|
|
||||||
## Documentation & Resources
|
## Documentation & Resources
|
||||||
|
|
||||||
- [API Documentation](https://docs.rs/actix-protobuf)
|
- [API Documentation](https://docs.rs/actix-protobuf)
|
||||||
- [Example Project](https://github.com/actix/examples/tree/master/protobuf)
|
- [Example Project](https://github.com/actix/examples/tree/master/protobuf)
|
||||||
- Minimum Supported Rust Version (MSRV): 1.54
|
- Minimum Supported Rust Version (MSRV): 1.57
|
||||||
|
|
||||||
## Example
|
## Example
|
||||||
|
|
||||||
@ -23,6 +27,7 @@ use actix_web::*;
|
|||||||
pub struct MyObj {
|
pub struct MyObj {
|
||||||
#[prost(int32, tag = "1")]
|
#[prost(int32, tag = "1")]
|
||||||
pub number: i32,
|
pub number: i32,
|
||||||
|
|
||||||
#[prost(string, tag = "2")]
|
#[prost(string, tag = "2")]
|
||||||
pub name: String,
|
pub name: String,
|
||||||
}
|
}
|
||||||
@ -33,7 +38,7 @@ async fn index(msg: ProtoBuf<MyObj>) -> Result<HttpResponse> {
|
|||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
See [here](https://github.com/actix/actix-extras/tree/master/actix-protobuf/examples/prost-example) for the complete example.
|
See [here](https://github.com/actix/examples/tree/master/protobuf) for the complete example.
|
||||||
|
|
||||||
## License
|
## License
|
||||||
|
|
||||||
|
@ -1,15 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "prost-example"
|
|
||||||
version = "0.5.1"
|
|
||||||
edition = "2018"
|
|
||||||
authors = [
|
|
||||||
"kingxsp <jin.hb.zh@outlook.com>",
|
|
||||||
"Yuki Okushi <huyuumi.dev@gmail.com>"
|
|
||||||
]
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
actix-web = "4"
|
|
||||||
actix-protobuf = { path = "../../" }
|
|
||||||
|
|
||||||
env_logger = "0.8"
|
|
||||||
prost = { version = "0.8", default_features = false, features = ["prost-derive"] }
|
|
@ -1,68 +0,0 @@
|
|||||||
#!/usr/bin/env python3
|
|
||||||
# just start server and run client.py
|
|
||||||
|
|
||||||
# wget https://github.com/protocolbuffers/protobuf/releases/download/v3.11.2/protobuf-python-3.11.2.zip
|
|
||||||
# unzip protobuf-python-3.11.2.zip
|
|
||||||
# cd protobuf-3.11.2/python/
|
|
||||||
# python3 setup.py install
|
|
||||||
|
|
||||||
# pip3 install --upgrade pip
|
|
||||||
# pip3 install aiohttp
|
|
||||||
|
|
||||||
# python3 client.py
|
|
||||||
|
|
||||||
import test_pb2
|
|
||||||
import traceback
|
|
||||||
import sys
|
|
||||||
|
|
||||||
import asyncio
|
|
||||||
import aiohttp
|
|
||||||
|
|
||||||
def op():
|
|
||||||
try:
|
|
||||||
obj = test_pb2.MyObj()
|
|
||||||
obj.number = 9
|
|
||||||
obj.name = 'USB'
|
|
||||||
|
|
||||||
#Serialize
|
|
||||||
sendDataStr = obj.SerializeToString()
|
|
||||||
#print serialized string value
|
|
||||||
print('serialized string:', sendDataStr)
|
|
||||||
#------------------------#
|
|
||||||
# message transmission #
|
|
||||||
#------------------------#
|
|
||||||
receiveDataStr = sendDataStr
|
|
||||||
receiveData = test_pb2.MyObj()
|
|
||||||
|
|
||||||
#Deserialize
|
|
||||||
receiveData.ParseFromString(receiveDataStr)
|
|
||||||
print('pares serialize string, return: devId = ', receiveData.number, ', name = ', receiveData.name)
|
|
||||||
except(Exception, e):
|
|
||||||
print(Exception, ':', e)
|
|
||||||
print(traceback.print_exc())
|
|
||||||
errInfo = sys.exc_info()
|
|
||||||
print(errInfo[0], ':', errInfo[1])
|
|
||||||
|
|
||||||
|
|
||||||
async def fetch(session):
|
|
||||||
obj = test_pb2.MyObj()
|
|
||||||
obj.number = 9
|
|
||||||
obj.name = 'USB'
|
|
||||||
async with session.post('http://127.0.0.1:8081/', data=obj.SerializeToString(),
|
|
||||||
headers={"content-type": "application/protobuf"}) as resp:
|
|
||||||
print(resp.status)
|
|
||||||
data = await resp.read()
|
|
||||||
receiveObj = test_pb2.MyObj()
|
|
||||||
receiveObj.ParseFromString(data)
|
|
||||||
print(receiveObj)
|
|
||||||
|
|
||||||
async def go(loop):
|
|
||||||
obj = test_pb2.MyObj()
|
|
||||||
obj.number = 9
|
|
||||||
obj.name = 'USB'
|
|
||||||
async with aiohttp.ClientSession(loop=loop) as session:
|
|
||||||
await fetch(session)
|
|
||||||
|
|
||||||
loop = asyncio.get_event_loop()
|
|
||||||
loop.run_until_complete(go(loop))
|
|
||||||
loop.close()
|
|
@ -1,33 +0,0 @@
|
|||||||
use actix_protobuf::*;
|
|
||||||
use actix_web::*;
|
|
||||||
use prost::Message;
|
|
||||||
|
|
||||||
#[derive(Clone, PartialEq, Message)]
|
|
||||||
pub struct MyObj {
|
|
||||||
#[prost(int32, tag = "1")]
|
|
||||||
pub number: i32,
|
|
||||||
|
|
||||||
#[prost(string, tag = "2")]
|
|
||||||
pub name: String,
|
|
||||||
}
|
|
||||||
|
|
||||||
async fn index(msg: ProtoBuf<MyObj>) -> Result<HttpResponse> {
|
|
||||||
println!("model: {:?}", msg);
|
|
||||||
HttpResponse::Ok().protobuf(msg.0) // <- send response
|
|
||||||
}
|
|
||||||
|
|
||||||
#[actix_web::main]
|
|
||||||
async fn main() -> std::io::Result<()> {
|
|
||||||
std::env::set_var("RUST_LOG", "actix_web=debug,actix_server=info");
|
|
||||||
env_logger::init();
|
|
||||||
|
|
||||||
HttpServer::new(|| {
|
|
||||||
App::new()
|
|
||||||
.wrap(middleware::Logger::default())
|
|
||||||
.service(web::resource("/").route(web::post().to(index)))
|
|
||||||
})
|
|
||||||
.bind("127.0.0.1:8081")?
|
|
||||||
.shutdown_timeout(1)
|
|
||||||
.run()
|
|
||||||
.await
|
|
||||||
}
|
|
@ -1,6 +0,0 @@
|
|||||||
syntax = "proto3";
|
|
||||||
|
|
||||||
message MyObj {
|
|
||||||
int32 number = 1;
|
|
||||||
string name = 2;
|
|
||||||
}
|
|
@ -1,75 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
# Generated by the protocol buffer compiler. DO NOT EDIT!
|
|
||||||
# source: test.proto
|
|
||||||
|
|
||||||
from google.protobuf import descriptor as _descriptor
|
|
||||||
from google.protobuf import message as _message
|
|
||||||
from google.protobuf import reflection as _reflection
|
|
||||||
from google.protobuf import symbol_database as _symbol_database
|
|
||||||
# @@protoc_insertion_point(imports)
|
|
||||||
|
|
||||||
_sym_db = _symbol_database.Default()
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
DESCRIPTOR = _descriptor.FileDescriptor(
|
|
||||||
name='test.proto',
|
|
||||||
package='',
|
|
||||||
syntax='proto3',
|
|
||||||
serialized_options=None,
|
|
||||||
serialized_pb=b'\n\ntest.proto\"%\n\x05MyObj\x12\x0e\n\x06number\x18\x01 \x01(\x05\x12\x0c\n\x04name\x18\x02 \x01(\tb\x06proto3'
|
|
||||||
)
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
_MYOBJ = _descriptor.Descriptor(
|
|
||||||
name='MyObj',
|
|
||||||
full_name='MyObj',
|
|
||||||
filename=None,
|
|
||||||
file=DESCRIPTOR,
|
|
||||||
containing_type=None,
|
|
||||||
fields=[
|
|
||||||
_descriptor.FieldDescriptor(
|
|
||||||
name='number', full_name='MyObj.number', index=0,
|
|
||||||
number=1, type=5, cpp_type=1, label=1,
|
|
||||||
has_default_value=False, default_value=0,
|
|
||||||
message_type=None, enum_type=None, containing_type=None,
|
|
||||||
is_extension=False, extension_scope=None,
|
|
||||||
serialized_options=None, file=DESCRIPTOR),
|
|
||||||
_descriptor.FieldDescriptor(
|
|
||||||
name='name', full_name='MyObj.name', index=1,
|
|
||||||
number=2, type=9, cpp_type=9, label=1,
|
|
||||||
has_default_value=False, default_value=b"".decode('utf-8'),
|
|
||||||
message_type=None, enum_type=None, containing_type=None,
|
|
||||||
is_extension=False, extension_scope=None,
|
|
||||||
serialized_options=None, file=DESCRIPTOR),
|
|
||||||
],
|
|
||||||
extensions=[
|
|
||||||
],
|
|
||||||
nested_types=[],
|
|
||||||
enum_types=[
|
|
||||||
],
|
|
||||||
serialized_options=None,
|
|
||||||
is_extendable=False,
|
|
||||||
syntax='proto3',
|
|
||||||
extension_ranges=[],
|
|
||||||
oneofs=[
|
|
||||||
],
|
|
||||||
serialized_start=14,
|
|
||||||
serialized_end=51,
|
|
||||||
)
|
|
||||||
|
|
||||||
DESCRIPTOR.message_types_by_name['MyObj'] = _MYOBJ
|
|
||||||
_sym_db.RegisterFileDescriptor(DESCRIPTOR)
|
|
||||||
|
|
||||||
MyObj = _reflection.GeneratedProtocolMessageType('MyObj', (_message.Message,), {
|
|
||||||
'DESCRIPTOR' : _MYOBJ,
|
|
||||||
'__module__' : 'test_pb2'
|
|
||||||
# @@protoc_insertion_point(class_scope:MyObj)
|
|
||||||
})
|
|
||||||
_sym_db.RegisterMessage(MyObj)
|
|
||||||
|
|
||||||
|
|
||||||
# @@protoc_insertion_point(module_scope)
|
|
@ -1,6 +1,9 @@
|
|||||||
|
//! Protobuf payload extractor for Actix Web.
|
||||||
|
|
||||||
#![forbid(unsafe_code)]
|
#![forbid(unsafe_code)]
|
||||||
#![deny(rust_2018_idioms, nonstandard_style)]
|
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
|
||||||
#![warn(future_incompatible)]
|
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
|
||||||
|
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||||
|
|
||||||
use std::{
|
use std::{
|
||||||
fmt,
|
fmt,
|
||||||
@ -19,7 +22,7 @@ use actix_web::{
|
|||||||
Error, FromRequest, HttpMessage, HttpRequest, HttpResponse, HttpResponseBuilder, Responder,
|
Error, FromRequest, HttpMessage, HttpRequest, HttpResponse, HttpResponseBuilder, Responder,
|
||||||
ResponseError,
|
ResponseError,
|
||||||
};
|
};
|
||||||
use derive_more::Display;
|
use derive_more::derive::Display;
|
||||||
use futures_util::{
|
use futures_util::{
|
||||||
future::{FutureExt as _, LocalBoxFuture},
|
future::{FutureExt as _, LocalBoxFuture},
|
||||||
stream::StreamExt as _,
|
stream::StreamExt as _,
|
||||||
@ -29,26 +32,28 @@ use prost::{DecodeError as ProtoBufDecodeError, EncodeError as ProtoBufEncodeErr
|
|||||||
#[derive(Debug, Display)]
|
#[derive(Debug, Display)]
|
||||||
pub enum ProtoBufPayloadError {
|
pub enum ProtoBufPayloadError {
|
||||||
/// Payload size is bigger than 256k
|
/// Payload size is bigger than 256k
|
||||||
#[display(fmt = "Payload size is bigger than 256k")]
|
#[display("Payload size is bigger than 256k")]
|
||||||
Overflow,
|
Overflow,
|
||||||
|
|
||||||
/// Content type error
|
/// Content type error
|
||||||
#[display(fmt = "Content type error")]
|
#[display("Content type error")]
|
||||||
ContentType,
|
ContentType,
|
||||||
|
|
||||||
/// Serialize error
|
/// Serialize error
|
||||||
#[display(fmt = "ProtoBuf serialize error: {}", _0)]
|
#[display("ProtoBuf serialize error: {_0}")]
|
||||||
Serialize(ProtoBufEncodeError),
|
Serialize(ProtoBufEncodeError),
|
||||||
|
|
||||||
/// Deserialize error
|
/// Deserialize error
|
||||||
#[display(fmt = "ProtoBuf deserialize error: {}", _0)]
|
#[display("ProtoBuf deserialize error: {_0}")]
|
||||||
Deserialize(ProtoBufDecodeError),
|
Deserialize(ProtoBufDecodeError),
|
||||||
|
|
||||||
/// Payload error
|
/// Payload error
|
||||||
#[display(fmt = "Error that occur during reading payload: {}", _0)]
|
#[display("Error that occur during reading payload: {_0}")]
|
||||||
Payload(PayloadError),
|
Payload(PayloadError),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// TODO: impl error for ProtoBufPayloadError
|
||||||
|
|
||||||
impl ResponseError for ProtoBufPayloadError {
|
impl ResponseError for ProtoBufPayloadError {
|
||||||
fn error_response(&self) -> HttpResponse {
|
fn error_response(&self) -> HttpResponse {
|
||||||
match *self {
|
match *self {
|
||||||
@ -170,7 +175,9 @@ pub struct ProtoBufMessage<T: Message + Default> {
|
|||||||
impl<T: Message + Default> ProtoBufMessage<T> {
|
impl<T: Message + Default> ProtoBufMessage<T> {
|
||||||
/// Create `ProtoBufMessage` for request.
|
/// Create `ProtoBufMessage` for request.
|
||||||
pub fn new(req: &HttpRequest, payload: &mut Payload) -> Self {
|
pub fn new(req: &HttpRequest, payload: &mut Payload) -> Self {
|
||||||
if req.content_type() != "application/protobuf" {
|
if req.content_type() != "application/protobuf"
|
||||||
|
&& req.content_type() != "application/x-protobuf"
|
||||||
|
{
|
||||||
return ProtoBufMessage {
|
return ProtoBufMessage {
|
||||||
limit: 262_144,
|
limit: 262_144,
|
||||||
length: None,
|
length: None,
|
||||||
@ -262,15 +269,16 @@ impl ProtoBufResponseBuilder for HttpResponseBuilder {
|
|||||||
value
|
value
|
||||||
.encode(&mut body)
|
.encode(&mut body)
|
||||||
.map_err(ProtoBufPayloadError::Serialize)?;
|
.map_err(ProtoBufPayloadError::Serialize)?;
|
||||||
|
|
||||||
Ok(self.body(body))
|
Ok(self.body(body))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod tests {
|
mod tests {
|
||||||
|
use actix_web::{http::header, test::TestRequest};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use actix_web::http::header;
|
|
||||||
use actix_web::test::TestRequest;
|
|
||||||
|
|
||||||
impl PartialEq for ProtoBufPayloadError {
|
impl PartialEq for ProtoBufPayloadError {
|
||||||
fn eq(&self, other: &ProtoBufPayloadError) -> bool {
|
fn eq(&self, other: &ProtoBufPayloadError) -> bool {
|
||||||
@ -286,7 +294,7 @@ mod tests {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone, PartialEq, Message)]
|
#[derive(Clone, PartialEq, Eq, Message)]
|
||||||
pub struct MyObject {
|
pub struct MyObject {
|
||||||
#[prost(int32, tag = "1")]
|
#[prost(int32, tag = "1")]
|
||||||
pub number: i32,
|
pub number: i32,
|
||||||
|
@ -1,145 +0,0 @@
|
|||||||
# Changes
|
|
||||||
|
|
||||||
## Unreleased - 2021-xx-xx
|
|
||||||
|
|
||||||
|
|
||||||
## 0.11.0 - 2022-03-15
|
|
||||||
### Removed
|
|
||||||
- `RedisSession` has been removed. Check out `RedisActorSessionStore` in `actix-session` for a session store backed by Redis using `actix-redis`. [#212]
|
|
||||||
|
|
||||||
### Changed
|
|
||||||
- Update `redis-async` dependency to `0.12`. [#212]
|
|
||||||
|
|
||||||
[#212]: https://github.com/actix/actix-extras/pull/212
|
|
||||||
|
|
||||||
|
|
||||||
## 0.10.0 - 2022-03-01
|
|
||||||
- Update `actix-web` dependency to `4`.
|
|
||||||
|
|
||||||
|
|
||||||
## 0.10.0-beta.6 - 2022-02-07
|
|
||||||
- Update `actix-web` dependency to `4.0.0-rc.1`.
|
|
||||||
|
|
||||||
|
|
||||||
## 0.10.0-beta.5 - 2021-12-29
|
|
||||||
- Update `actix-web` dependency to `4.0.0.beta-18`. [#218]
|
|
||||||
- Minimum supported Rust version (MSRV) is now 1.54.
|
|
||||||
|
|
||||||
[#218]: https://github.com/actix/actix-extras/pull/218
|
|
||||||
|
|
||||||
|
|
||||||
## 0.10.0-beta.4 - 2021-12-12
|
|
||||||
- A session will be created in Redis if and only if there is some data inside the session state. This reduces the performance impact of `RedisSession` on routes that do not leverage sessions. [#207]
|
|
||||||
- Update `actix-web` dependency to `4.0.0.beta-14`. [#209]
|
|
||||||
|
|
||||||
[#207]: https://github.com/actix/actix-extras/pull/207
|
|
||||||
[#209]: https://github.com/actix/actix-extras/pull/209
|
|
||||||
|
|
||||||
|
|
||||||
## 0.10.0-beta.3 - 2021-10-21
|
|
||||||
- Update `actix-web` dependency to v4.0.0-beta.10. [#203]
|
|
||||||
- Minimum supported Rust version (MSRV) is now 1.52.
|
|
||||||
|
|
||||||
[#203]: https://github.com/actix/actix-extras/pull/203
|
|
||||||
|
|
||||||
|
|
||||||
## 0.10.0-beta.2 - 2021-06-27
|
|
||||||
- No notable changes.
|
|
||||||
|
|
||||||
|
|
||||||
## 0.10.0-beta.1 - 2021-04-02
|
|
||||||
- Update `actix-web` dependency to 4.0.0 beta.
|
|
||||||
- Minimum supported Rust version (MSRV) is now 1.46.0.
|
|
||||||
|
|
||||||
|
|
||||||
## 0.9.2 - 2021-03-21
|
|
||||||
- Implement `std::error::Error` for `Error` [#135]
|
|
||||||
- Allow the removal of `Max-Age` for session-only cookies. [#161]
|
|
||||||
|
|
||||||
[#135]: https://github.com/actix/actix-extras/pull/135
|
|
||||||
[#161]: https://github.com/actix/actix-extras/pull/161
|
|
||||||
|
|
||||||
|
|
||||||
## 0.9.1 - 2020-09-12
|
|
||||||
- Enforce minimum redis-async version of 0.6.3 to workaround breaking patch change.
|
|
||||||
|
|
||||||
|
|
||||||
## 0.9.0 - 2020-09-11
|
|
||||||
- Update `actix-web` dependency to 3.0.0.
|
|
||||||
- Minimize `futures` dependency.
|
|
||||||
|
|
||||||
|
|
||||||
## 0.9.0-alpha.2 - 2020-05-17
|
|
||||||
- Add `cookie_http_only` functionality to RedisSession builder, setting this
|
|
||||||
to false allows JavaScript to access cookies. Defaults to true.
|
|
||||||
- Change type of parameter of ttl method to u32.
|
|
||||||
- Update `actix` to 0.10.0-alpha.3
|
|
||||||
- Update `tokio-util` to 0.3
|
|
||||||
- Minimum supported Rust version(MSRV) is now 1.40.0.
|
|
||||||
|
|
||||||
|
|
||||||
## 0.9.0-alpha.1 - 2020-03-28
|
|
||||||
- Update `actix` to 0.10.0-alpha.2
|
|
||||||
- Update `actix-session` to 0.4.0-alpha.1
|
|
||||||
- Update `actix-web` to 3.0.0-alpha.1
|
|
||||||
- Update `time` to 0.2.9
|
|
||||||
|
|
||||||
|
|
||||||
## 0.8.1 - 2020-02-18
|
|
||||||
- Move `env_logger` dependency to dev-dependencies and update to 0.7
|
|
||||||
- Update `actix_web` to 2.0.0 from 2.0.0-rc
|
|
||||||
- Move repository to actix-extras
|
|
||||||
|
|
||||||
|
|
||||||
## 0.8.0 - 2019-12-20
|
|
||||||
- Release
|
|
||||||
|
|
||||||
|
|
||||||
## 0.8.0-alpha.1 - 2019-12-16
|
|
||||||
- Migrate to actix 0.9
|
|
||||||
|
|
||||||
|
|
||||||
## 0.7.0 - 2019-09-25
|
|
||||||
- added cache_keygen functionality to RedisSession builder, enabling support for
|
|
||||||
customizable cache key creation
|
|
||||||
|
|
||||||
|
|
||||||
## 0.6.1 - 2019-07-19
|
|
||||||
- remove ClonableService usage
|
|
||||||
- added comprehensive tests for session workflow
|
|
||||||
|
|
||||||
|
|
||||||
## 0.6.0 - 2019-07-08
|
|
||||||
- actix-web 1.0.0 compatibility
|
|
||||||
- Upgraded logic that evaluates session state, including new SessionStatus field,
|
|
||||||
and introduced ``session.renew()`` and ``session.purge()`` functionality.
|
|
||||||
Use ``renew()`` to cycle the session key at successful login. ``renew()`` keeps a
|
|
||||||
session's state while replacing the old cookie and session key with new ones.
|
|
||||||
Use ``purge()`` at logout to invalidate the session cookie and remove the
|
|
||||||
session's redis cache entry.
|
|
||||||
|
|
||||||
|
|
||||||
## 0.5.1 - 2018-08-02
|
|
||||||
- Use cookie 0.11
|
|
||||||
|
|
||||||
|
|
||||||
## 0.5.0 - 2018-07-21
|
|
||||||
- Session cookie configuration
|
|
||||||
- Actix/Actix-web 0.7 compatibility
|
|
||||||
|
|
||||||
|
|
||||||
## 0.4.0 - 2018-05-08
|
|
||||||
- Actix web 0.6 compatibility
|
|
||||||
|
|
||||||
|
|
||||||
## 0.3.0 - 2018-04-10
|
|
||||||
- Actix web 0.5 compatibility
|
|
||||||
|
|
||||||
|
|
||||||
## 0.2.0 - 2018-02-28
|
|
||||||
- Use resolver actor from actix
|
|
||||||
- Use actix web 0.5
|
|
||||||
|
|
||||||
|
|
||||||
## 0.1.0 - 2018-01-23
|
|
||||||
- First release
|
|
@ -1,44 +0,0 @@
|
|||||||
[package]
|
|
||||||
name = "actix-redis"
|
|
||||||
version = "0.11.0"
|
|
||||||
authors = ["Nikolay Kim <fafhrd91@gmail.com>"]
|
|
||||||
description = "Redis integration for Actix"
|
|
||||||
license = "MIT OR Apache-2.0"
|
|
||||||
keywords = ["actix", "redis", "async", "session"]
|
|
||||||
homepage = "https://actix.rs"
|
|
||||||
repository = "https://github.com/actix/actix-extras.git"
|
|
||||||
categories = ["network-programming", "asynchronous"]
|
|
||||||
exclude = [".cargo/config"]
|
|
||||||
edition = "2018"
|
|
||||||
|
|
||||||
[lib]
|
|
||||||
name = "actix_redis"
|
|
||||||
path = "src/lib.rs"
|
|
||||||
|
|
||||||
[features]
|
|
||||||
default = ["web"]
|
|
||||||
|
|
||||||
# actix-web integration
|
|
||||||
web = ["actix-web"]
|
|
||||||
|
|
||||||
[dependencies]
|
|
||||||
actix = { version = "0.12", default-features = false }
|
|
||||||
actix-rt = { version = "2.1", default-features = false }
|
|
||||||
actix-service = "2"
|
|
||||||
actix-tls = { version = "3", default-features = false, features = ["connect"] }
|
|
||||||
|
|
||||||
log = "0.4.6"
|
|
||||||
backoff = "0.4.0"
|
|
||||||
derive_more = "0.99.5"
|
|
||||||
futures-core = { version = "0.3.7", default-features = false }
|
|
||||||
redis-async = { version = "0.12", default-features = false, features = ["tokio10"] }
|
|
||||||
time = "0.3"
|
|
||||||
tokio = { version = "1.13.1", features = ["sync"] }
|
|
||||||
tokio-util = "0.6.1"
|
|
||||||
actix-web = { version = "4", default_features = false, optional = true }
|
|
||||||
|
|
||||||
[dev-dependencies]
|
|
||||||
actix-test = "0.1.0-beta.12"
|
|
||||||
actix-web = { version = "4", default_features = false, features = ["macros"] }
|
|
||||||
env_logger = "0.9"
|
|
||||||
serde = { version = "1.0.101", features = ["derive"] }
|
|
@ -1,14 +0,0 @@
|
|||||||
# actix-redis
|
|
||||||
|
|
||||||
> Redis integration for Actix.
|
|
||||||
|
|
||||||
[](https://crates.io/crates/actix-redis)
|
|
||||||
[](https://docs.rs/actix-redis/0.11.0)
|
|
||||||

|
|
||||||
[](https://deps.rs/crate/actix-redis/0.11.0)
|
|
||||||
|
|
||||||
## Documentation & Resources
|
|
||||||
|
|
||||||
- [API Documentation](https://docs.rs/actix-redis)
|
|
||||||
- [Example Project](https://github.com/actix/examples/tree/master/auth/redis-session)
|
|
||||||
- Minimum Supported Rust Version (MSRV): 1.54
|
|
@ -1,30 +0,0 @@
|
|||||||
//! Redis integration for `actix`.
|
|
||||||
|
|
||||||
#![deny(rust_2018_idioms, nonstandard_style)]
|
|
||||||
#![warn(future_incompatible)]
|
|
||||||
|
|
||||||
mod redis;
|
|
||||||
pub use redis::{Command, RedisActor};
|
|
||||||
|
|
||||||
use derive_more::{Display, Error, From};
|
|
||||||
|
|
||||||
/// General purpose `actix-redis` error.
|
|
||||||
#[derive(Debug, Display, Error, From)]
|
|
||||||
pub enum Error {
|
|
||||||
#[display(fmt = "Redis error {}", _0)]
|
|
||||||
Redis(redis_async::error::Error),
|
|
||||||
/// Receiving message during reconnecting
|
|
||||||
#[display(fmt = "Redis: Not connected")]
|
|
||||||
NotConnected,
|
|
||||||
/// Cancel all waters when connection get dropped
|
|
||||||
#[display(fmt = "Redis: Disconnected")]
|
|
||||||
Disconnected,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[cfg(feature = "web")]
|
|
||||||
impl actix_web::ResponseError for Error {}
|
|
||||||
|
|
||||||
// re-export
|
|
||||||
pub use redis_async::error::Error as RespError;
|
|
||||||
pub use redis_async::resp::RespValue;
|
|
||||||
pub use redis_async::resp_array;
|
|
@ -1,141 +0,0 @@
|
|||||||
use std::collections::VecDeque;
|
|
||||||
use std::io;
|
|
||||||
|
|
||||||
use actix::prelude::*;
|
|
||||||
use actix_rt::net::TcpStream;
|
|
||||||
use actix_service::boxed::{self, BoxService};
|
|
||||||
use actix_tls::connect::{ConnectError, ConnectInfo, Connection, ConnectorService};
|
|
||||||
use backoff::backoff::Backoff;
|
|
||||||
use backoff::ExponentialBackoff;
|
|
||||||
use log::{error, info, warn};
|
|
||||||
use redis_async::error::Error as RespError;
|
|
||||||
use redis_async::resp::{RespCodec, RespValue};
|
|
||||||
use tokio::io::{split, WriteHalf};
|
|
||||||
use tokio::sync::oneshot;
|
|
||||||
use tokio_util::codec::FramedRead;
|
|
||||||
|
|
||||||
use crate::Error;
|
|
||||||
|
|
||||||
/// Command for send data to Redis
|
|
||||||
#[derive(Debug)]
|
|
||||||
pub struct Command(pub RespValue);
|
|
||||||
|
|
||||||
impl Message for Command {
|
|
||||||
type Result = Result<RespValue, Error>;
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Redis communication actor
|
|
||||||
pub struct RedisActor {
|
|
||||||
addr: String,
|
|
||||||
connector: BoxService<ConnectInfo<String>, Connection<String, TcpStream>, ConnectError>,
|
|
||||||
backoff: ExponentialBackoff,
|
|
||||||
cell: Option<actix::io::FramedWrite<RespValue, WriteHalf<TcpStream>, RespCodec>>,
|
|
||||||
queue: VecDeque<oneshot::Sender<Result<RespValue, Error>>>,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl RedisActor {
|
|
||||||
/// Start new `Supervisor` with `RedisActor`.
|
|
||||||
pub fn start<S: Into<String>>(addr: S) -> Addr<RedisActor> {
|
|
||||||
let addr = addr.into();
|
|
||||||
|
|
||||||
let backoff = ExponentialBackoff {
|
|
||||||
max_elapsed_time: None,
|
|
||||||
..Default::default()
|
|
||||||
};
|
|
||||||
|
|
||||||
Supervisor::start(|_| RedisActor {
|
|
||||||
addr,
|
|
||||||
connector: boxed::service(ConnectorService::default()),
|
|
||||||
cell: None,
|
|
||||||
backoff,
|
|
||||||
queue: VecDeque::new(),
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Actor for RedisActor {
|
|
||||||
type Context = Context<Self>;
|
|
||||||
|
|
||||||
fn started(&mut self, ctx: &mut Context<Self>) {
|
|
||||||
let req = ConnectInfo::new(self.addr.to_owned());
|
|
||||||
self.connector
|
|
||||||
.call(req)
|
|
||||||
.into_actor(self)
|
|
||||||
.map(|res, act, ctx| match res {
|
|
||||||
Ok(conn) => {
|
|
||||||
let stream = conn.into_parts().0;
|
|
||||||
info!("Connected to redis server: {}", act.addr);
|
|
||||||
|
|
||||||
let (r, w) = split(stream);
|
|
||||||
|
|
||||||
// configure write side of the connection
|
|
||||||
let framed = actix::io::FramedWrite::new(w, RespCodec, ctx);
|
|
||||||
act.cell = Some(framed);
|
|
||||||
|
|
||||||
// read side of the connection
|
|
||||||
ctx.add_stream(FramedRead::new(r, RespCodec));
|
|
||||||
|
|
||||||
act.backoff.reset();
|
|
||||||
}
|
|
||||||
Err(err) => {
|
|
||||||
error!("Can not connect to redis server: {}", err);
|
|
||||||
// re-connect with backoff time.
|
|
||||||
// we stop current context, supervisor will restart it.
|
|
||||||
if let Some(timeout) = act.backoff.next_backoff() {
|
|
||||||
ctx.run_later(timeout, |_, ctx| ctx.stop());
|
|
||||||
}
|
|
||||||
}
|
|
||||||
})
|
|
||||||
.wait(ctx);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Supervised for RedisActor {
|
|
||||||
fn restarting(&mut self, _: &mut Self::Context) {
|
|
||||||
self.cell.take();
|
|
||||||
for tx in self.queue.drain(..) {
|
|
||||||
let _ = tx.send(Err(Error::Disconnected));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl actix::io::WriteHandler<io::Error> for RedisActor {
|
|
||||||
fn error(&mut self, err: io::Error, _: &mut Self::Context) -> Running {
|
|
||||||
warn!("Redis connection dropped: {} error: {}", self.addr, err);
|
|
||||||
Running::Stop
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl StreamHandler<Result<RespValue, RespError>> for RedisActor {
|
|
||||||
fn handle(&mut self, msg: Result<RespValue, RespError>, ctx: &mut Self::Context) {
|
|
||||||
match msg {
|
|
||||||
Err(e) => {
|
|
||||||
if let Some(tx) = self.queue.pop_front() {
|
|
||||||
let _ = tx.send(Err(e.into()));
|
|
||||||
}
|
|
||||||
ctx.stop();
|
|
||||||
}
|
|
||||||
Ok(val) => {
|
|
||||||
if let Some(tx) = self.queue.pop_front() {
|
|
||||||
let _ = tx.send(Ok(val));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
impl Handler<Command> for RedisActor {
|
|
||||||
type Result = ResponseFuture<Result<RespValue, Error>>;
|
|
||||||
|
|
||||||
fn handle(&mut self, msg: Command, _: &mut Self::Context) -> Self::Result {
|
|
||||||
let (tx, rx) = oneshot::channel();
|
|
||||||
if let Some(ref mut cell) = self.cell {
|
|
||||||
self.queue.push_back(tx);
|
|
||||||
cell.write(msg.0);
|
|
||||||
} else {
|
|
||||||
let _ = tx.send(Err(Error::NotConnected));
|
|
||||||
}
|
|
||||||
|
|
||||||
Box::pin(async move { rx.await.map_err(|_| Error::Disconnected)? })
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,42 +0,0 @@
|
|||||||
#[macro_use]
|
|
||||||
extern crate redis_async;
|
|
||||||
|
|
||||||
use actix_redis::{Command, Error, RedisActor, RespValue};
|
|
||||||
|
|
||||||
#[actix_web::test]
|
|
||||||
async fn test_error_connect() {
|
|
||||||
let addr = RedisActor::start("localhost:54000");
|
|
||||||
let _addr2 = addr.clone();
|
|
||||||
|
|
||||||
let res = addr.send(Command(resp_array!["GET", "test"])).await;
|
|
||||||
match res {
|
|
||||||
Ok(Err(Error::NotConnected)) => (),
|
|
||||||
_ => panic!("Should not happen {:?}", res),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[actix_web::test]
|
|
||||||
async fn test_redis() {
|
|
||||||
env_logger::init();
|
|
||||||
|
|
||||||
let addr = RedisActor::start("127.0.0.1:6379");
|
|
||||||
let res = addr
|
|
||||||
.send(Command(resp_array!["SET", "test", "value"]))
|
|
||||||
.await;
|
|
||||||
|
|
||||||
match res {
|
|
||||||
Ok(Ok(resp)) => {
|
|
||||||
assert_eq!(resp, RespValue::SimpleString("OK".to_owned()));
|
|
||||||
|
|
||||||
let res = addr.send(Command(resp_array!["GET", "test"])).await;
|
|
||||||
match res {
|
|
||||||
Ok(Ok(resp)) => {
|
|
||||||
println!("RESP: {:?}", resp);
|
|
||||||
assert_eq!(resp, RespValue::BulkString((&b"value"[..]).into()));
|
|
||||||
}
|
|
||||||
_ => panic!("Should not happen {:?}", res),
|
|
||||||
}
|
|
||||||
}
|
|
||||||
_ => panic!("Should not happen {:?}", res),
|
|
||||||
}
|
|
||||||
}
|
|
@ -1,9 +1,68 @@
|
|||||||
# Changes
|
# Changes
|
||||||
|
|
||||||
## Unreleased - 2021-xx-xx
|
## Unreleased
|
||||||
|
|
||||||
|
- Add `Session::contains_key` method.
|
||||||
|
- Add `Session::update[_or]()` methods.
|
||||||
|
- Update `redis` dependency to `0.29`.
|
||||||
|
|
||||||
|
## 0.10.1
|
||||||
|
|
||||||
|
- Expose `storage::generate_session_key()` without needing to enable a crate feature.
|
||||||
|
|
||||||
|
## 0.10.0
|
||||||
|
|
||||||
|
- Add `redis-session-rustls` crate feature that enables `rustls`-secured Redis sessions.
|
||||||
|
- Add `redis-pool` crate feature (off-by-default) which enables `RedisSessionStore::{new, builder}_pooled()` constructors.
|
||||||
|
- Rename `redis-rs-session` crate feature to `redis-session`.
|
||||||
|
- Rename `redis-rs-tls-session` crate feature to `redis-session-native-tls`.
|
||||||
|
- Remove `redis-actor-session` crate feature (and, therefore, the `actix-redis` based storage backend).
|
||||||
|
- Expose `storage::generate_session_key()`.
|
||||||
|
- Update `redis` dependency to `0.26`.
|
||||||
|
|
||||||
|
## 0.9.0
|
||||||
|
|
||||||
|
- Remove use of `async-trait` on `SessionStore` trait.
|
||||||
|
- Minimum supported Rust version (MSRV) is now 1.75.
|
||||||
|
|
||||||
|
## 0.8.0
|
||||||
|
|
||||||
|
- Set secure attribute when adding a session removal cookie.
|
||||||
|
- Update `redis` dependency to `0.23`.
|
||||||
|
- Minimum supported Rust version (MSRV) is now 1.68.
|
||||||
|
|
||||||
|
## 0.7.2
|
||||||
|
|
||||||
|
- Set SameSite attribute when adding a session removal cookie. [#284]
|
||||||
|
- Minimum supported Rust version (MSRV) is now 1.59 due to transitive `time` dependency.
|
||||||
|
|
||||||
|
[#284]: https://github.com/actix/actix-extras/pull/284
|
||||||
|
|
||||||
|
## 0.7.1
|
||||||
|
|
||||||
|
- Fix interaction between session state changes and renewal. [#265]
|
||||||
|
|
||||||
|
[#265]: https://github.com/actix/actix-extras/pull/265
|
||||||
|
|
||||||
|
## 0.7.0
|
||||||
|
|
||||||
|
- Added `TtlExtensionPolicy` enum to support different strategies for extending the TTL attached to the session state. `TtlExtensionPolicy::OnEveryRequest` now allows for long-lived sessions that do not expire if the user remains active. [#233]
|
||||||
|
- `SessionLength` is now called `SessionLifecycle`. [#233]
|
||||||
|
- `SessionLength::Predetermined` is now called `SessionLifecycle::PersistentSession`. [#233]
|
||||||
|
- The fields for Both `SessionLength` variants have been extracted into separate types (`PersistentSession` and `BrowserSession`). All fields are now private, manipulated via methods, to allow adding more configuration parameters in the future in a non-breaking fashion. [#233]
|
||||||
|
- `SessionLength::Predetermined::max_session_length` is now called `PersistentSession::session_ttl`. [#233]
|
||||||
|
- `SessionLength::BrowserSession::state_ttl` is now called `BrowserSession::session_state_ttl`. [#233]
|
||||||
|
- `SessionMiddlewareBuilder::max_session_length` is now called `SessionMiddlewareBuilder::session_lifecycle`. [#233]
|
||||||
|
- The `SessionStore` trait requires the implementation of a new method, `SessionStore::update_ttl`. [#233]
|
||||||
|
- All types used to configure `SessionMiddleware` have been moved to the `config` sub-module. [#233]
|
||||||
|
- Update `actix` dependency to `0.13`.
|
||||||
|
- Update `actix-redis` dependency to `0.12`.
|
||||||
|
- Minimum supported Rust version (MSRV) is now 1.57 due to transitive `time` dependency.
|
||||||
|
|
||||||
|
[#233]: https://github.com/actix/actix-extras/pull/233
|
||||||
|
|
||||||
|
## 0.6.2
|
||||||
|
|
||||||
## 0.6.2 - 2022-03-25
|
|
||||||
- Implement `SessionExt` for `GuardContext`. [#234]
|
- Implement `SessionExt` for `GuardContext`. [#234]
|
||||||
- `RedisSessionStore` will prevent connection timeouts from causing user-visible errors. [#235]
|
- `RedisSessionStore` will prevent connection timeouts from causing user-visible errors. [#235]
|
||||||
- Do not leak internal implementation details to callers when errors occur. [#236]
|
- Do not leak internal implementation details to callers when errors occur. [#236]
|
||||||
@ -12,13 +71,14 @@
|
|||||||
[#236]: https://github.com/actix/actix-extras/pull/236
|
[#236]: https://github.com/actix/actix-extras/pull/236
|
||||||
[#235]: https://github.com/actix/actix-extras/pull/235
|
[#235]: https://github.com/actix/actix-extras/pull/235
|
||||||
|
|
||||||
|
## 0.6.1
|
||||||
|
|
||||||
## 0.6.1 - 2022-03-21
|
|
||||||
- No significant changes since `0.6.0`.
|
- No significant changes since `0.6.0`.
|
||||||
|
|
||||||
|
## 0.6.0
|
||||||
|
|
||||||
## 0.6.0 - 2022-03-15
|
|
||||||
### Added
|
### Added
|
||||||
|
|
||||||
- `SessionMiddleware`, a middleware to provide support for saving/updating/deleting session state against a pluggable storage backend (see `SessionStore` trait). [#212]
|
- `SessionMiddleware`, a middleware to provide support for saving/updating/deleting session state against a pluggable storage backend (see `SessionStore` trait). [#212]
|
||||||
- `CookieSessionStore`, a cookie-based backend to store session state. [#212]
|
- `CookieSessionStore`, a cookie-based backend to store session state. [#212]
|
||||||
- `RedisActorSessionStore`, a Redis-based backend to store session state powered by `actix-redis`. [#212]
|
- `RedisActorSessionStore`, a Redis-based backend to store session state powered by `actix-redis`. [#212]
|
||||||
@ -27,37 +87,39 @@
|
|||||||
- Implement `SessionExt` for `ServiceResponse`. [#212]
|
- Implement `SessionExt` for `ServiceResponse`. [#212]
|
||||||
|
|
||||||
### Changed
|
### Changed
|
||||||
|
|
||||||
- Rename `UserSession` to `SessionExt`. [#212]
|
- Rename `UserSession` to `SessionExt`. [#212]
|
||||||
|
|
||||||
### Removed
|
### Removed
|
||||||
|
|
||||||
- `CookieSession`; replaced with `CookieSessionStore`, a storage backend for `SessionMiddleware`. [#212]
|
- `CookieSession`; replaced with `CookieSessionStore`, a storage backend for `SessionMiddleware`. [#212]
|
||||||
- `Session::set_session`; use `Session::insert` to modify the session state. [#212]
|
- `Session::set_session`; use `Session::insert` to modify the session state. [#212]
|
||||||
|
|
||||||
[#212]: https://github.com/actix/actix-extras/pull/212
|
[#212]: https://github.com/actix/actix-extras/pull/212
|
||||||
|
|
||||||
|
## 0.5.0
|
||||||
|
|
||||||
## 0.5.0 - 2022-03-01
|
|
||||||
- Update `actix-web` dependency to `4`.
|
- Update `actix-web` dependency to `4`.
|
||||||
|
|
||||||
|
## 0.5.0-beta.8
|
||||||
|
|
||||||
## 0.5.0-beta.8 - 2022-02-07
|
|
||||||
- Update `actix-web` dependency to `4.0.0-rc.1`.
|
- Update `actix-web` dependency to `4.0.0-rc.1`.
|
||||||
|
|
||||||
|
## 0.5.0-beta.7
|
||||||
|
|
||||||
## 0.5.0-beta.7 - 2021-12-29
|
|
||||||
- Update `actix-web` dependency to `4.0.0.beta-18`. [#218]
|
- Update `actix-web` dependency to `4.0.0.beta-18`. [#218]
|
||||||
- Minimum supported Rust version (MSRV) is now 1.54.
|
- Minimum supported Rust version (MSRV) is now 1.54.
|
||||||
|
|
||||||
[#218]: https://github.com/actix/actix-extras/pull/218
|
[#218]: https://github.com/actix/actix-extras/pull/218
|
||||||
|
|
||||||
|
## 0.5.0-beta.6
|
||||||
|
|
||||||
## 0.5.0-beta.6 - 2021-12-18
|
|
||||||
- Update `actix-web` dependency to `4.0.0.beta-15`. [#216]
|
- Update `actix-web` dependency to `4.0.0.beta-15`. [#216]
|
||||||
|
|
||||||
[#216]: https://github.com/actix/actix-extras/pull/216
|
[#216]: https://github.com/actix/actix-extras/pull/216
|
||||||
|
|
||||||
|
## 0.5.0-beta.5
|
||||||
|
|
||||||
## 0.5.0-beta.5 - 2021-12-12
|
|
||||||
- Update `actix-web` dependency to `4.0.0.beta-14`. [#209]
|
- Update `actix-web` dependency to `4.0.0.beta-14`. [#209]
|
||||||
- Remove `UserSession` implementation for `RequestHead`. [#209]
|
- Remove `UserSession` implementation for `RequestHead`. [#209]
|
||||||
- A session will be created in the storage backend if and only if there is some data inside the session state. This reduces the performance impact of `SessionMiddleware` on routes that do not leverage sessions. [#207]
|
- A session will be created in the storage backend if and only if there is some data inside the session state. This reduces the performance impact of `SessionMiddleware` on routes that do not leverage sessions. [#207]
|
||||||
@ -65,12 +127,12 @@
|
|||||||
[#207]: https://github.com/actix/actix-extras/pull/207
|
[#207]: https://github.com/actix/actix-extras/pull/207
|
||||||
[#209]: https://github.com/actix/actix-extras/pull/209
|
[#209]: https://github.com/actix/actix-extras/pull/209
|
||||||
|
|
||||||
|
## 0.5.0-beta.4
|
||||||
|
|
||||||
## 0.5.0-beta.4 - 2021-11-22
|
|
||||||
- No significant changes since `0.5.0-beta.3`.
|
- No significant changes since `0.5.0-beta.3`.
|
||||||
|
|
||||||
|
## 0.5.0-beta.3
|
||||||
|
|
||||||
## 0.5.0-beta.3 - 2021-10-21
|
|
||||||
- Impl `Clone` for `CookieSession`. [#201]
|
- Impl `Clone` for `CookieSession`. [#201]
|
||||||
- Update `actix-web` dependency to v4.0.0-beta.10. [#203]
|
- Update `actix-web` dependency to v4.0.0-beta.10. [#203]
|
||||||
- Minimum supported Rust version (MSRV) is now 1.52.
|
- Minimum supported Rust version (MSRV) is now 1.52.
|
||||||
@ -78,12 +140,12 @@
|
|||||||
[#201]: https://github.com/actix/actix-extras/pull/201
|
[#201]: https://github.com/actix/actix-extras/pull/201
|
||||||
[#203]: https://github.com/actix/actix-extras/pull/203
|
[#203]: https://github.com/actix/actix-extras/pull/203
|
||||||
|
|
||||||
|
## 0.5.0-beta.2
|
||||||
|
|
||||||
## 0.5.0-beta.2 - 2021-06-27
|
|
||||||
- No notable changes.
|
- No notable changes.
|
||||||
|
|
||||||
|
## 0.5.0-beta.1
|
||||||
|
|
||||||
## 0.5.0-beta.1 - 2021-04-02
|
|
||||||
- Add `Session::entries`. [#170]
|
- Add `Session::entries`. [#170]
|
||||||
- Rename `Session::{set => insert}` to match standard hash map naming. [#170]
|
- Rename `Session::{set => insert}` to match standard hash map naming. [#170]
|
||||||
- Return values from `Session::remove`. [#170]
|
- Return values from `Session::remove`. [#170]
|
||||||
@ -95,21 +157,21 @@
|
|||||||
|
|
||||||
[#170]: https://github.com/actix/actix-extras/pull/170
|
[#170]: https://github.com/actix/actix-extras/pull/170
|
||||||
|
|
||||||
|
## 0.4.1
|
||||||
|
|
||||||
## 0.4.1 - 2021-03-21
|
|
||||||
- `Session::set_session` takes a `IntoIterator` instead of `Iterator`. [#105]
|
- `Session::set_session` takes a `IntoIterator` instead of `Iterator`. [#105]
|
||||||
- Fix calls to `session.purge()` from paths other than the one specified in the cookie. [#129]
|
- Fix calls to `session.purge()` from paths other than the one specified in the cookie. [#129]
|
||||||
|
|
||||||
[#105]: https://github.com/actix/actix-extras/pull/105
|
[#105]: https://github.com/actix/actix-extras/pull/105
|
||||||
[#129]: https://github.com/actix/actix-extras/pull/129
|
[#129]: https://github.com/actix/actix-extras/pull/129
|
||||||
|
|
||||||
|
## 0.4.0
|
||||||
|
|
||||||
## 0.4.0 - 2020-09-11
|
|
||||||
- Update `actix-web` dependency to 3.0.0.
|
- Update `actix-web` dependency to 3.0.0.
|
||||||
- Minimum supported Rust version (MSRV) is now 1.42.0.
|
- Minimum supported Rust version (MSRV) is now 1.42.0.
|
||||||
|
|
||||||
|
## 0.4.0-alpha.1
|
||||||
|
|
||||||
## 0.4.0-alpha.1 - 2020-03-14
|
|
||||||
- Update the `time` dependency to 0.2.7
|
- Update the `time` dependency to 0.2.7
|
||||||
- Update the `actix-web` dependency to 3.0.0-alpha.1
|
- Update the `actix-web` dependency to 3.0.0-alpha.1
|
||||||
- Long lasting auto-prolonged session [#1292]
|
- Long lasting auto-prolonged session [#1292]
|
||||||
@ -117,65 +179,62 @@
|
|||||||
|
|
||||||
[#1292]: https://github.com/actix/actix-web/pull/1292
|
[#1292]: https://github.com/actix/actix-web/pull/1292
|
||||||
|
|
||||||
|
|
||||||
## 0.3.0 - 2019-12-20
|
## 0.3.0 - 2019-12-20
|
||||||
|
|
||||||
- Release
|
- Release
|
||||||
|
|
||||||
|
|
||||||
## 0.3.0-alpha.4 - 2019-12-xx
|
## 0.3.0-alpha.4 - 2019-12-xx
|
||||||
|
|
||||||
- Allow access to sessions also from not mutable references to the request
|
- Allow access to sessions also from not mutable references to the request
|
||||||
|
|
||||||
|
|
||||||
## 0.3.0-alpha.3 - 2019-12-xx
|
## 0.3.0-alpha.3 - 2019-12-xx
|
||||||
|
|
||||||
- Add access to the session from RequestHead for use of session from guard methods
|
- Add access to the session from RequestHead for use of session from guard methods
|
||||||
- Migrate to `std::future`
|
- Migrate to `std::future`
|
||||||
- Migrate to `actix-web` 2.0
|
- Migrate to `actix-web` 2.0
|
||||||
|
|
||||||
|
|
||||||
## 0.2.0 - 2019-07-08
|
## 0.2.0 - 2019-07-08
|
||||||
- Enhanced ``actix-session`` to facilitate state changes. Use ``Session.renew()``
|
|
||||||
at successful login to cycle a session (new key/cookie but keeps state).
|
|
||||||
Use ``Session.purge()`` at logout to invalid a session cookie (and remove
|
|
||||||
from redis cache, if applicable).
|
|
||||||
|
|
||||||
|
- Enhanced `actix-session` to facilitate state changes. Use `Session.renew()` at successful login to cycle a session (new key/cookie but keeps state). Use `Session.purge()` at logout to invalid a session cookie (and remove from redis cache, if applicable).
|
||||||
|
|
||||||
## 0.1.1 - 2019-06-03
|
## 0.1.1 - 2019-06-03
|
||||||
|
|
||||||
- Fix optional cookie session support
|
- Fix optional cookie session support
|
||||||
|
|
||||||
|
|
||||||
## 0.1.0 - 2019-05-18
|
## 0.1.0 - 2019-05-18
|
||||||
|
|
||||||
- Use actix-web 1.0.0-rc
|
- Use actix-web 1.0.0-rc
|
||||||
|
|
||||||
|
|
||||||
## 0.1.0-beta.4 - 2019-05-12
|
## 0.1.0-beta.4 - 2019-05-12
|
||||||
|
|
||||||
- Use actix-web 1.0.0-beta.4
|
- Use actix-web 1.0.0-beta.4
|
||||||
|
|
||||||
|
|
||||||
## 0.1.0-beta.2 - 2019-04-28
|
## 0.1.0-beta.2 - 2019-04-28
|
||||||
|
|
||||||
- Add helper trait `UserSession` which allows to get session for ServiceRequest and HttpRequest
|
- Add helper trait `UserSession` which allows to get session for ServiceRequest and HttpRequest
|
||||||
|
|
||||||
|
|
||||||
## 0.1.0-beta.1 - 2019-04-20
|
## 0.1.0-beta.1 - 2019-04-20
|
||||||
|
|
||||||
- Update actix-web to beta.1
|
- Update actix-web to beta.1
|
||||||
- `CookieSession::max_age()` accepts value in seconds
|
- `CookieSession::max_age()` accepts value in seconds
|
||||||
|
|
||||||
|
|
||||||
## 0.1.0-alpha.6 - 2019-04-14
|
## 0.1.0-alpha.6 - 2019-04-14
|
||||||
|
|
||||||
- Update actix-web alpha.6
|
- Update actix-web alpha.6
|
||||||
|
|
||||||
|
|
||||||
## 0.1.0-alpha.4 - 2019-04-08
|
## 0.1.0-alpha.4 - 2019-04-08
|
||||||
- Update actix-web
|
|
||||||
|
|
||||||
|
- Update actix-web
|
||||||
|
|
||||||
## 0.1.0-alpha.3 - 2019-04-02
|
## 0.1.0-alpha.3 - 2019-04-02
|
||||||
|
|
||||||
- Update actix-web
|
- Update actix-web
|
||||||
|
|
||||||
|
|
||||||
## 0.1.0-alpha.2 - 2019-03-29
|
## 0.1.0-alpha.2 - 2019-03-29
|
||||||
|
|
||||||
- Update actix-web
|
- Update actix-web
|
||||||
- Use new feature name for secure cookies
|
- Use new feature name for secure cookies
|
||||||
|
|
||||||
|
|
||||||
## 0.1.0-alpha.1 - 2019-03-28
|
## 0.1.0-alpha.1 - 2019-03-28
|
||||||
|
|
||||||
- Initial impl
|
- Initial impl
|
||||||
|
@ -1,65 +1,60 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "actix-session"
|
name = "actix-session"
|
||||||
version = "0.6.2"
|
version = "0.10.1"
|
||||||
authors = [
|
authors = [
|
||||||
"Nikolay Kim <fafhrd91@gmail.com>",
|
"Nikolay Kim <fafhrd91@gmail.com>",
|
||||||
"Luca Palmieri <rust@lpalmieri.com>",
|
"Luca Palmieri <rust@lpalmieri.com>",
|
||||||
]
|
]
|
||||||
description = "Session management for Actix Web"
|
description = "Session management for Actix Web"
|
||||||
keywords = ["http", "web", "framework", "async", "session"]
|
keywords = ["http", "web", "framework", "async", "session"]
|
||||||
homepage = "https://actix.rs"
|
repository.workspace = true
|
||||||
repository = "https://github.com/actix/actix-extras.git"
|
homepage.workspace = true
|
||||||
license = "MIT OR Apache-2.0"
|
license.workspace = true
|
||||||
edition = "2018"
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
|
||||||
[package.metadata.docs.rs]
|
[package.metadata.docs.rs]
|
||||||
all-features = true
|
|
||||||
rustdoc-args = ["--cfg", "docsrs"]
|
rustdoc-args = ["--cfg", "docsrs"]
|
||||||
|
all-features = true
|
||||||
[lib]
|
|
||||||
name = "actix_session"
|
|
||||||
path = "src/lib.rs"
|
|
||||||
|
|
||||||
[features]
|
[features]
|
||||||
default = []
|
default = []
|
||||||
cookie-session = []
|
cookie-session = []
|
||||||
redis-actor-session = ["actix-redis", "actix", "futures-core", "rand"]
|
redis-session = ["dep:redis"]
|
||||||
redis-rs-session = ["redis", "rand"]
|
redis-session-native-tls = ["redis-session", "redis/tokio-native-tls-comp"]
|
||||||
redis-rs-tls-session = ["redis-rs-session", "redis/tokio-native-tls-comp"]
|
redis-session-rustls = ["redis-session", "redis/tokio-rustls-comp"]
|
||||||
|
redis-pool = ["dep:deadpool-redis"]
|
||||||
|
|
||||||
[dependencies]
|
[dependencies]
|
||||||
actix-service = "2"
|
actix-service = "2"
|
||||||
actix-utils = "3"
|
actix-utils = "3"
|
||||||
actix-web = { version = "4", default_features = false, features = ["cookies", "secure-cookies"] }
|
actix-web = { version = "4", default-features = false, features = ["cookies", "secure-cookies"] }
|
||||||
|
|
||||||
anyhow = "1"
|
anyhow = "1"
|
||||||
async-trait = "0.1"
|
derive_more = { version = "2", features = ["display", "error", "from"] }
|
||||||
derive_more = "0.99.5"
|
rand = "0.9"
|
||||||
rand = { version = "0.8", optional = true }
|
|
||||||
serde = { version = "1" }
|
serde = { version = "1" }
|
||||||
serde_json = { version = "1" }
|
serde_json = { version = "1" }
|
||||||
time = "0.3"
|
|
||||||
tracing = { version = "0.1.30", default-features = false, features = ["log"] }
|
tracing = { version = "0.1.30", default-features = false, features = ["log"] }
|
||||||
|
|
||||||
# redis-actor-session
|
# redis-session
|
||||||
actix = { version = "0.12.0", default-features = false, optional = true }
|
redis = { version = "0.29", default-features = false, features = ["tokio-comp", "connection-manager"], optional = true }
|
||||||
actix-redis = { version = "0.11.0", optional = true }
|
deadpool-redis = { version = "0.20", optional = true }
|
||||||
futures-core = { version = "0.3.7", default-features = false, optional = true }
|
|
||||||
|
|
||||||
# redis-rs-session
|
|
||||||
redis = { version = "0.21", default-features = false, features = ["aio", "tokio-comp", "connection-manager"], optional = true }
|
|
||||||
|
|
||||||
[dev-dependencies]
|
[dev-dependencies]
|
||||||
actix-session = { path = ".", features = ["cookie-session", "redis-actor-session", "redis-rs-session"] }
|
actix-session = { path = ".", features = ["cookie-session", "redis-session"] }
|
||||||
actix-test = "0.1.0-beta.10"
|
actix-test = "0.1"
|
||||||
actix-web = { version = "4", default_features = false, features = ["cookies", "secure-cookies", "macros"] }
|
actix-web = { version = "4", default-features = false, features = ["cookies", "secure-cookies", "macros"] }
|
||||||
env_logger = "0.9"
|
tracing-subscriber = { version = "0.3", features = ["env-filter"] }
|
||||||
log = "0.4"
|
tracing = "0.1.30"
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
||||||
|
|
||||||
[[example]]
|
[[example]]
|
||||||
name = "basic"
|
name = "basic"
|
||||||
required-features = ["redis-actor-session"]
|
required-features = ["redis-session"]
|
||||||
|
|
||||||
[[example]]
|
[[example]]
|
||||||
name = "authentication"
|
name = "authentication"
|
||||||
required-features = ["redis-actor-session"]
|
required-features = ["redis-session"]
|
||||||
|
@ -1,15 +1,125 @@
|
|||||||
# actix-session
|
# actix-session
|
||||||
|
|
||||||
> Session management for Actix Web applications.
|
> Session management for Actix Web.
|
||||||
|
|
||||||
|
<!-- prettier-ignore-start -->
|
||||||
|
|
||||||
[](https://crates.io/crates/actix-session)
|
[](https://crates.io/crates/actix-session)
|
||||||
[](https://docs.rs/actix-session/0.6.2)
|
[](https://docs.rs/actix-session/0.10.1)
|
||||||

|

|
||||||
[](https://deps.rs/crate/actix-session/0.6.2)
|
[](https://deps.rs/crate/actix-session/0.10.1)
|
||||||
|
|
||||||
|
<!-- prettier-ignore-end -->
|
||||||
|
|
||||||
## Documentation & Resources
|
<!-- cargo-rdme start -->
|
||||||
|
|
||||||
- [API Documentation](https://docs.rs/actix-session)
|
Session management for Actix Web.
|
||||||
- [Example Projects](https://github.com/actix/examples/tree/master/auth/cookie-session)
|
|
||||||
- Minimum Supported Rust Version (MSRV): 1.54
|
The HTTP protocol, at a first glance, is stateless: the client sends a request, the server parses its content, performs some processing and returns a response. The outcome is only influenced by the provided inputs (i.e. the request content) and whatever state the server queries while performing its processing.
|
||||||
|
|
||||||
|
Stateless systems are easier to reason about, but they are not quite as powerful as we need them to be - e.g. how do you authenticate a user? The user would be forced to authenticate **for every single request**. That is, for example, how 'Basic' Authentication works. While it may work for a machine user (i.e. an API client), it is impractical for a person—you do not want a login prompt on every single page you navigate to!
|
||||||
|
|
||||||
|
There is a solution - **sessions**. Using sessions the server can attach state to a set of requests coming from the same client. They are built on top of cookies - the server sets a cookie in the HTTP response (`Set-Cookie` header), the client (e.g. the browser) will store the cookie and play it back to the server when sending new requests (using the `Cookie` header).
|
||||||
|
|
||||||
|
We refer to the cookie used for sessions as a **session cookie**. Its content is called **session key** (or **session ID**), while the state attached to the session is referred to as **session state**.
|
||||||
|
|
||||||
|
`actix-session` provides an easy-to-use framework to manage sessions in applications built on top of Actix Web. [`SessionMiddleware`] is the middleware underpinning the functionality provided by `actix-session`; it takes care of all the session cookie handling and instructs the **storage backend** to create/delete/update the session state based on the operations performed against the active [`Session`].
|
||||||
|
|
||||||
|
`actix-session` provides some built-in storage backends: ([`CookieSessionStore`], [`RedisSessionStore`]) - you can create a custom storage backend by implementing the [`SessionStore`] trait.
|
||||||
|
|
||||||
|
Further reading on sessions:
|
||||||
|
|
||||||
|
- [RFC 6265](https://datatracker.ietf.org/doc/html/rfc6265);
|
||||||
|
- [OWASP's session management cheat-sheet](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html).
|
||||||
|
|
||||||
|
## Getting started
|
||||||
|
|
||||||
|
To start using sessions in your Actix Web application you must register [`SessionMiddleware`] as a middleware on your `App`:
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use actix_web::{web, App, HttpServer, HttpResponse, Error};
|
||||||
|
use actix_session::{Session, SessionMiddleware, storage::RedisSessionStore};
|
||||||
|
use actix_web::cookie::Key;
|
||||||
|
|
||||||
|
#[actix_web::main]
|
||||||
|
async fn main() -> std::io::Result<()> {
|
||||||
|
// When using `Key::generate()` it is important to initialize outside of the
|
||||||
|
// `HttpServer::new` closure. When deployed the secret key should be read from a
|
||||||
|
// configuration file or environment variables.
|
||||||
|
let secret_key = Key::generate();
|
||||||
|
|
||||||
|
let redis_store = RedisSessionStore::new("redis://127.0.0.1:6379")
|
||||||
|
.await
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
HttpServer::new(move ||
|
||||||
|
App::new()
|
||||||
|
// Add session management to your application using Redis for session state storage
|
||||||
|
.wrap(
|
||||||
|
SessionMiddleware::new(
|
||||||
|
redis_store.clone(),
|
||||||
|
secret_key.clone(),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
.default_service(web::to(|| HttpResponse::Ok())))
|
||||||
|
.bind(("127.0.0.1", 8080))?
|
||||||
|
.run()
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The session state can be accessed and modified by your request handlers using the [`Session`] extractor. Note that this doesn't work in the stream of a streaming response.
|
||||||
|
|
||||||
|
```rust
|
||||||
|
use actix_web::Error;
|
||||||
|
use actix_session::Session;
|
||||||
|
|
||||||
|
fn index(session: Session) -> Result<&'static str, Error> {
|
||||||
|
// access the session state
|
||||||
|
if let Some(count) = session.get::<i32>("counter")? {
|
||||||
|
println!("SESSION value: {}", count);
|
||||||
|
// modify the session state
|
||||||
|
session.insert("counter", count + 1)?;
|
||||||
|
} else {
|
||||||
|
session.insert("counter", 1)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok("Welcome!")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
## Choosing A Backend
|
||||||
|
|
||||||
|
By default, `actix-session` does not provide any storage backend to retrieve and save the state attached to your sessions. You can enable:
|
||||||
|
|
||||||
|
- a purely cookie-based "backend", [`CookieSessionStore`], using the `cookie-session` feature flag.
|
||||||
|
|
||||||
|
```console
|
||||||
|
cargo add actix-session --features=cookie-session
|
||||||
|
```
|
||||||
|
|
||||||
|
- a Redis-based backend via the [`redis`] crate, [`RedisSessionStore`], using the `redis-session` feature flag.
|
||||||
|
|
||||||
|
```console
|
||||||
|
cargo add actix-session --features=redis-session
|
||||||
|
```
|
||||||
|
|
||||||
|
Add the `redis-session-native-tls` feature flag if you want to connect to Redis using a secure connection (via the `native-tls` crate):
|
||||||
|
|
||||||
|
```console
|
||||||
|
cargo add actix-session --features=redis-session-native-tls
|
||||||
|
```
|
||||||
|
|
||||||
|
If you, instead, prefer depending on `rustls`, use the `redis-session-rustls` feature flag:
|
||||||
|
|
||||||
|
```console
|
||||||
|
cargo add actix-session --features=redis-session-rustls
|
||||||
|
```
|
||||||
|
|
||||||
|
You can implement your own session storage backend using the [`SessionStore`] trait.
|
||||||
|
|
||||||
|
[`SessionStore`]: storage::SessionStore
|
||||||
|
[`CookieSessionStore`]: storage::CookieSessionStore
|
||||||
|
[`RedisSessionStore`]: storage::RedisSessionStore
|
||||||
|
|
||||||
|
<!-- cargo-rdme end -->
|
||||||
|
@ -1,10 +1,12 @@
|
|||||||
use actix_session::{storage::RedisActorSessionStore, Session, SessionMiddleware};
|
use actix_session::{storage::RedisSessionStore, Session, SessionMiddleware};
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
cookie::{Key, SameSite},
|
cookie::{Key, SameSite},
|
||||||
error::InternalError,
|
error::InternalError,
|
||||||
middleware, web, App, Error, HttpResponse, HttpServer, Responder,
|
middleware, web, App, Error, HttpResponse, HttpServer, Responder,
|
||||||
};
|
};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
|
use tracing::level_filters::LevelFilter;
|
||||||
|
use tracing_subscriber::EnvFilter;
|
||||||
|
|
||||||
#[derive(Deserialize)]
|
#[derive(Deserialize)]
|
||||||
struct Credentials {
|
struct Credentials {
|
||||||
@ -21,7 +23,7 @@ struct User {
|
|||||||
|
|
||||||
impl User {
|
impl User {
|
||||||
fn authenticate(credentials: Credentials) -> Result<Self, HttpResponse> {
|
fn authenticate(credentials: Credentials) -> Result<Self, HttpResponse> {
|
||||||
// TODO: figure out why I keep getting hacked
|
// to do: figure out why I keep getting hacked /s
|
||||||
if &credentials.password != "hunter2" {
|
if &credentials.password != "hunter2" {
|
||||||
return Err(HttpResponse::Unauthorized().json("Unauthorized"));
|
return Err(HttpResponse::Unauthorized().json("Unauthorized"));
|
||||||
}
|
}
|
||||||
@ -71,12 +73,21 @@ async fn secret(session: Session) -> Result<impl Responder, Error> {
|
|||||||
|
|
||||||
#[actix_web::main]
|
#[actix_web::main]
|
||||||
async fn main() -> std::io::Result<()> {
|
async fn main() -> std::io::Result<()> {
|
||||||
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
tracing_subscriber::fmt()
|
||||||
|
.with_env_filter(
|
||||||
|
EnvFilter::builder()
|
||||||
|
.with_default_directive(LevelFilter::INFO.into())
|
||||||
|
.from_env_lossy(),
|
||||||
|
)
|
||||||
|
.init();
|
||||||
|
|
||||||
// The signing key would usually be read from a configuration file/environment variables.
|
// The signing key would usually be read from a configuration file/environment variables.
|
||||||
let signing_key = Key::generate();
|
let signing_key = Key::generate();
|
||||||
|
|
||||||
log::info!("starting HTTP server at http://localhost:8080");
|
tracing::info!("setting up Redis session storage");
|
||||||
|
let storage = RedisSessionStore::new("127.0.0.1:6379").await.unwrap();
|
||||||
|
|
||||||
|
tracing::info!("starting HTTP server at http://localhost:8080");
|
||||||
|
|
||||||
HttpServer::new(move || {
|
HttpServer::new(move || {
|
||||||
App::new()
|
App::new()
|
||||||
@ -84,10 +95,7 @@ async fn main() -> std::io::Result<()> {
|
|||||||
.wrap(middleware::Logger::default())
|
.wrap(middleware::Logger::default())
|
||||||
// cookie session middleware
|
// cookie session middleware
|
||||||
.wrap(
|
.wrap(
|
||||||
SessionMiddleware::builder(
|
SessionMiddleware::builder(storage.clone(), signing_key.clone())
|
||||||
RedisActorSessionStore::new("127.0.0.1:6379"),
|
|
||||||
signing_key.clone(),
|
|
||||||
)
|
|
||||||
// allow the cookie to be accessed from javascript
|
// allow the cookie to be accessed from javascript
|
||||||
.cookie_http_only(false)
|
.cookie_http_only(false)
|
||||||
// allow the cookie only from the current domain
|
// allow the cookie only from the current domain
|
||||||
|
@ -1,13 +1,15 @@
|
|||||||
use actix_session::{storage::RedisActorSessionStore, Session, SessionMiddleware};
|
use actix_session::{storage::RedisSessionStore, Session, SessionMiddleware};
|
||||||
use actix_web::{cookie::Key, middleware, web, App, Error, HttpRequest, HttpServer, Responder};
|
use actix_web::{cookie::Key, middleware, web, App, Error, HttpRequest, HttpServer, Responder};
|
||||||
|
use tracing::level_filters::LevelFilter;
|
||||||
|
use tracing_subscriber::EnvFilter;
|
||||||
|
|
||||||
/// simple handler
|
/// simple handler
|
||||||
async fn index(req: HttpRequest, session: Session) -> Result<impl Responder, Error> {
|
async fn index(req: HttpRequest, session: Session) -> Result<impl Responder, Error> {
|
||||||
println!("{:?}", req);
|
println!("{req:?}");
|
||||||
|
|
||||||
// session
|
// session
|
||||||
if let Some(count) = session.get::<i32>("counter")? {
|
if let Some(count) = session.get::<i32>("counter")? {
|
||||||
println!("SESSION value: {}", count);
|
println!("SESSION value: {count}");
|
||||||
session.insert("counter", count + 1)?;
|
session.insert("counter", count + 1)?;
|
||||||
} else {
|
} else {
|
||||||
session.insert("counter", 1)?;
|
session.insert("counter", 1)?;
|
||||||
@ -18,22 +20,28 @@ async fn index(req: HttpRequest, session: Session) -> Result<impl Responder, Err
|
|||||||
|
|
||||||
#[actix_web::main]
|
#[actix_web::main]
|
||||||
async fn main() -> std::io::Result<()> {
|
async fn main() -> std::io::Result<()> {
|
||||||
env_logger::init_from_env(env_logger::Env::new().default_filter_or("info"));
|
tracing_subscriber::fmt()
|
||||||
|
.with_env_filter(
|
||||||
|
EnvFilter::builder()
|
||||||
|
.with_default_directive(LevelFilter::INFO.into())
|
||||||
|
.from_env_lossy(),
|
||||||
|
)
|
||||||
|
.init();
|
||||||
|
|
||||||
// The signing key would usually be read from a configuration file/environment variables.
|
// The signing key would usually be read from a configuration file/environment variables.
|
||||||
let signing_key = Key::generate();
|
let signing_key = Key::generate();
|
||||||
|
|
||||||
log::info!("starting HTTP server at http://localhost:8080");
|
tracing::info!("setting up Redis session storage");
|
||||||
|
let storage = RedisSessionStore::new("127.0.0.1:6379").await.unwrap();
|
||||||
|
|
||||||
|
tracing::info!("starting HTTP server at http://localhost:8080");
|
||||||
|
|
||||||
HttpServer::new(move || {
|
HttpServer::new(move || {
|
||||||
App::new()
|
App::new()
|
||||||
// enable logger
|
// enable logger
|
||||||
.wrap(middleware::Logger::default())
|
.wrap(middleware::Logger::default())
|
||||||
// cookie session middleware
|
// cookie session middleware
|
||||||
.wrap(SessionMiddleware::new(
|
.wrap(SessionMiddleware::new(storage.clone(), signing_key.clone()))
|
||||||
RedisActorSessionStore::new("127.0.0.1:6379"),
|
|
||||||
signing_key.clone(),
|
|
||||||
))
|
|
||||||
// register simple route, handle all methods
|
// register simple route, handle all methods
|
||||||
.service(web::resource("/").to(index))
|
.service(web::resource("/").to(index))
|
||||||
})
|
})
|
||||||
|
397
actix-session/src/config.rs
Normal file
397
actix-session/src/config.rs
Normal file
@ -0,0 +1,397 @@
|
|||||||
|
//! Configuration options to tune the behaviour of [`SessionMiddleware`].
|
||||||
|
|
||||||
|
use actix_web::cookie::{time::Duration, Key, SameSite};
|
||||||
|
use derive_more::derive::From;
|
||||||
|
|
||||||
|
use crate::{storage::SessionStore, SessionMiddleware};
|
||||||
|
|
||||||
|
/// Determines what type of session cookie should be used and how its lifecycle should be managed.
|
||||||
|
///
|
||||||
|
/// Used by [`SessionMiddlewareBuilder::session_lifecycle`].
|
||||||
|
#[derive(Debug, Clone, From)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub enum SessionLifecycle {
|
||||||
|
/// The session cookie will expire when the current browser session ends.
|
||||||
|
///
|
||||||
|
/// When does a browser session end? It depends on the browser! Chrome, for example, will often
|
||||||
|
/// continue running in the background when the browser is closed—session cookies are not
|
||||||
|
/// deleted and they will still be available when the browser is opened again.
|
||||||
|
/// Check the documentation of the browsers you are targeting for up-to-date information.
|
||||||
|
BrowserSession(BrowserSession),
|
||||||
|
|
||||||
|
/// The session cookie will be a [persistent cookie].
|
||||||
|
///
|
||||||
|
/// Persistent cookies have a pre-determined lifetime, specified via the `Max-Age` or `Expires`
|
||||||
|
/// attribute. They do not disappear when the current browser session ends.
|
||||||
|
///
|
||||||
|
/// [persistent cookie]: https://www.whitehatsec.com/glossary/content/persistent-session-cookie
|
||||||
|
PersistentSession(PersistentSession),
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A [session lifecycle](SessionLifecycle) strategy where the session cookie expires when the
|
||||||
|
/// browser's current session ends.
|
||||||
|
///
|
||||||
|
/// When does a browser session end? It depends on the browser. Chrome, for example, will often
|
||||||
|
/// continue running in the background when the browser is closed—session cookies are not deleted
|
||||||
|
/// and they will still be available when the browser is opened again. Check the documentation of
|
||||||
|
/// the browsers you are targeting for up-to-date information.
|
||||||
|
///
|
||||||
|
/// Due to its `Into<SessionLifecycle>` implementation, a `BrowserSession` can be passed directly
|
||||||
|
/// to [`SessionMiddlewareBuilder::session_lifecycle()`].
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct BrowserSession {
|
||||||
|
state_ttl: Duration,
|
||||||
|
state_ttl_extension_policy: TtlExtensionPolicy,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl BrowserSession {
|
||||||
|
/// Sets a time-to-live (TTL) when storing the session state in the storage backend.
|
||||||
|
///
|
||||||
|
/// We do not want to store session states indefinitely, otherwise we will inevitably run out of
|
||||||
|
/// storage by holding on to the state of countless abandoned or expired sessions!
|
||||||
|
///
|
||||||
|
/// We are dealing with the lifecycle of two uncorrelated object here: the session cookie
|
||||||
|
/// and the session state. It is not a big issue if the session state outlives the cookie—
|
||||||
|
/// we are wasting some space in the backend storage, but it will be cleaned up eventually.
|
||||||
|
/// What happens, instead, if the cookie outlives the session state? A new session starts—
|
||||||
|
/// e.g. if sessions are being used for authentication, the user is de-facto logged out.
|
||||||
|
///
|
||||||
|
/// It is not possible to predict with certainty how long a browser session is going to
|
||||||
|
/// last—you need to provide a reasonable upper bound. You do so via `state_ttl`—it dictates
|
||||||
|
/// what TTL should be used for session state when the lifecycle of the session cookie is
|
||||||
|
/// tied to the browser session length. [`SessionMiddleware`] will default to 1 day if
|
||||||
|
/// `state_ttl` is left unspecified.
|
||||||
|
///
|
||||||
|
/// You can mitigate the risk of the session cookie outliving the session state by
|
||||||
|
/// specifying a more aggressive state TTL extension policy - check out
|
||||||
|
/// [`BrowserSession::state_ttl_extension_policy`] for more details.
|
||||||
|
pub fn state_ttl(mut self, ttl: Duration) -> Self {
|
||||||
|
self.state_ttl = ttl;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Determine under what circumstances the TTL of your session state should be extended.
|
||||||
|
///
|
||||||
|
/// Defaults to [`TtlExtensionPolicy::OnStateChanges`] if left unspecified.
|
||||||
|
///
|
||||||
|
/// See [`TtlExtensionPolicy`] for more details.
|
||||||
|
pub fn state_ttl_extension_policy(mut self, ttl_extension_policy: TtlExtensionPolicy) -> Self {
|
||||||
|
self.state_ttl_extension_policy = ttl_extension_policy;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for BrowserSession {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
state_ttl: default_ttl(),
|
||||||
|
state_ttl_extension_policy: default_ttl_extension_policy(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A [session lifecycle](SessionLifecycle) strategy where the session cookie will be [persistent].
|
||||||
|
///
|
||||||
|
/// Persistent cookies have a pre-determined expiration, specified via the `Max-Age` or `Expires`
|
||||||
|
/// attribute. They do not disappear when the current browser session ends.
|
||||||
|
///
|
||||||
|
/// Due to its `Into<SessionLifecycle>` implementation, a `PersistentSession` can be passed directly
|
||||||
|
/// to [`SessionMiddlewareBuilder::session_lifecycle()`].
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
/// ```
|
||||||
|
/// use actix_web::cookie::time::Duration;
|
||||||
|
/// use actix_session::SessionMiddleware;
|
||||||
|
/// use actix_session::config::{PersistentSession, TtlExtensionPolicy};
|
||||||
|
///
|
||||||
|
/// const SECS_IN_WEEK: i64 = 60 * 60 * 24 * 7;
|
||||||
|
///
|
||||||
|
/// // a session lifecycle with a time-to-live (expiry) of 1 week and default extension policy
|
||||||
|
/// PersistentSession::default().session_ttl(Duration::seconds(SECS_IN_WEEK));
|
||||||
|
///
|
||||||
|
/// // a session lifecycle with the default time-to-live (expiry) and a custom extension policy
|
||||||
|
/// PersistentSession::default()
|
||||||
|
/// // this policy causes the session state's TTL to be refreshed on every request
|
||||||
|
/// .session_ttl_extension_policy(TtlExtensionPolicy::OnEveryRequest);
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// [persistent]: https://www.whitehatsec.com/glossary/content/persistent-session-cookie
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
pub struct PersistentSession {
|
||||||
|
session_ttl: Duration,
|
||||||
|
ttl_extension_policy: TtlExtensionPolicy,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl PersistentSession {
|
||||||
|
/// Specifies how long the session cookie should live.
|
||||||
|
///
|
||||||
|
/// The session TTL is also used as the TTL for the session state in the storage backend.
|
||||||
|
///
|
||||||
|
/// Defaults to 1 day.
|
||||||
|
///
|
||||||
|
/// A persistent session can live more than the specified TTL if the TTL is extended.
|
||||||
|
/// See [`session_ttl_extension_policy`](Self::session_ttl_extension_policy) for more details.
|
||||||
|
#[doc(alias = "max_age", alias = "max age", alias = "expires")]
|
||||||
|
pub fn session_ttl(mut self, session_ttl: Duration) -> Self {
|
||||||
|
self.session_ttl = session_ttl;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Determines under what circumstances the TTL of your session should be extended.
|
||||||
|
/// See [`TtlExtensionPolicy`] for more details.
|
||||||
|
///
|
||||||
|
/// Defaults to [`TtlExtensionPolicy::OnStateChanges`].
|
||||||
|
pub fn session_ttl_extension_policy(
|
||||||
|
mut self,
|
||||||
|
ttl_extension_policy: TtlExtensionPolicy,
|
||||||
|
) -> Self {
|
||||||
|
self.ttl_extension_policy = ttl_extension_policy;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Default for PersistentSession {
|
||||||
|
fn default() -> Self {
|
||||||
|
Self {
|
||||||
|
session_ttl: default_ttl(),
|
||||||
|
ttl_extension_policy: default_ttl_extension_policy(),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Configuration for which events should trigger an extension of the time-to-live for your session.
|
||||||
|
///
|
||||||
|
/// If you are using a [`BrowserSession`], `TtlExtensionPolicy` controls how often the TTL of the
|
||||||
|
/// session state should be refreshed. The browser is in control of the lifecycle of the session
|
||||||
|
/// cookie.
|
||||||
|
///
|
||||||
|
/// If you are using a [`PersistentSession`], `TtlExtensionPolicy` controls both the expiration of
|
||||||
|
/// the session cookie and the TTL of the session state on the storage backend.
|
||||||
|
#[derive(Debug, Clone)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub enum TtlExtensionPolicy {
|
||||||
|
/// The TTL is refreshed every time the server receives a request associated with a session.
|
||||||
|
///
|
||||||
|
/// # Performance impact
|
||||||
|
/// Refreshing the TTL on every request is not free. It implies a refresh of the TTL on the
|
||||||
|
/// session state. This translates into a request over the network if you are using a remote
|
||||||
|
/// system as storage backend (e.g. Redis). This impacts both the total load on your storage
|
||||||
|
/// backend (i.e. number of queries it has to handle) and the latency of the requests served by
|
||||||
|
/// your server.
|
||||||
|
OnEveryRequest,
|
||||||
|
|
||||||
|
/// The TTL is refreshed every time the session state changes or the session key is renewed.
|
||||||
|
OnStateChanges,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Determines how to secure the content of the session cookie.
|
||||||
|
///
|
||||||
|
/// Used by [`SessionMiddlewareBuilder::cookie_content_security`].
|
||||||
|
#[derive(Debug, Clone, Copy)]
|
||||||
|
pub enum CookieContentSecurity {
|
||||||
|
/// The cookie content is encrypted when using `CookieContentSecurity::Private`.
|
||||||
|
///
|
||||||
|
/// Encryption guarantees confidentiality and integrity: the client cannot tamper with the
|
||||||
|
/// cookie content nor decode it, as long as the encryption key remains confidential.
|
||||||
|
Private,
|
||||||
|
|
||||||
|
/// The cookie content is signed when using `CookieContentSecurity::Signed`.
|
||||||
|
///
|
||||||
|
/// Signing guarantees integrity, but it doesn't ensure confidentiality: the client cannot
|
||||||
|
/// tamper with the cookie content, but they can read it.
|
||||||
|
Signed,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) const fn default_ttl() -> Duration {
|
||||||
|
Duration::days(1)
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) const fn default_ttl_extension_policy() -> TtlExtensionPolicy {
|
||||||
|
TtlExtensionPolicy::OnStateChanges
|
||||||
|
}
|
||||||
|
|
||||||
|
/// A fluent, customized [`SessionMiddleware`] builder.
|
||||||
|
#[must_use]
|
||||||
|
pub struct SessionMiddlewareBuilder<Store: SessionStore> {
|
||||||
|
storage_backend: Store,
|
||||||
|
configuration: Configuration,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<Store: SessionStore> SessionMiddlewareBuilder<Store> {
|
||||||
|
pub(crate) fn new(store: Store, configuration: Configuration) -> Self {
|
||||||
|
Self {
|
||||||
|
storage_backend: store,
|
||||||
|
configuration,
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set the name of the cookie used to store the session ID.
|
||||||
|
///
|
||||||
|
/// Defaults to `id`.
|
||||||
|
pub fn cookie_name(mut self, name: String) -> Self {
|
||||||
|
self.configuration.cookie.name = name;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set the `Secure` attribute for the cookie used to store the session ID.
|
||||||
|
///
|
||||||
|
/// If the cookie is set as secure, it will only be transmitted when the connection is secure
|
||||||
|
/// (using `https`).
|
||||||
|
///
|
||||||
|
/// Default is `true`.
|
||||||
|
pub fn cookie_secure(mut self, secure: bool) -> Self {
|
||||||
|
self.configuration.cookie.secure = secure;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Determines what type of session cookie should be used and how its lifecycle should be managed.
|
||||||
|
/// Check out [`SessionLifecycle`]'s documentation for more details on the available options.
|
||||||
|
///
|
||||||
|
/// Default is [`SessionLifecycle::BrowserSession`].
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
/// ```
|
||||||
|
/// use actix_web::cookie::{Key, time::Duration};
|
||||||
|
/// use actix_session::{SessionMiddleware, config::PersistentSession};
|
||||||
|
/// use actix_session::storage::CookieSessionStore;
|
||||||
|
///
|
||||||
|
/// const SECS_IN_WEEK: i64 = 60 * 60 * 24 * 7;
|
||||||
|
///
|
||||||
|
/// // creates a session middleware with a time-to-live (expiry) of 1 week
|
||||||
|
/// SessionMiddleware::builder(CookieSessionStore::default(), Key::from(&[0; 64]))
|
||||||
|
/// .session_lifecycle(
|
||||||
|
/// PersistentSession::default().session_ttl(Duration::seconds(SECS_IN_WEEK))
|
||||||
|
/// )
|
||||||
|
/// .build();
|
||||||
|
/// ```
|
||||||
|
pub fn session_lifecycle<S: Into<SessionLifecycle>>(mut self, session_lifecycle: S) -> Self {
|
||||||
|
match session_lifecycle.into() {
|
||||||
|
SessionLifecycle::BrowserSession(BrowserSession {
|
||||||
|
state_ttl,
|
||||||
|
state_ttl_extension_policy,
|
||||||
|
}) => {
|
||||||
|
self.configuration.cookie.max_age = None;
|
||||||
|
self.configuration.session.state_ttl = state_ttl;
|
||||||
|
self.configuration.ttl_extension_policy = state_ttl_extension_policy;
|
||||||
|
}
|
||||||
|
SessionLifecycle::PersistentSession(PersistentSession {
|
||||||
|
session_ttl,
|
||||||
|
ttl_extension_policy,
|
||||||
|
}) => {
|
||||||
|
self.configuration.cookie.max_age = Some(session_ttl);
|
||||||
|
self.configuration.session.state_ttl = session_ttl;
|
||||||
|
self.configuration.ttl_extension_policy = ttl_extension_policy;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set the `SameSite` attribute for the cookie used to store the session ID.
|
||||||
|
///
|
||||||
|
/// By default, the attribute is set to `Lax`.
|
||||||
|
pub fn cookie_same_site(mut self, same_site: SameSite) -> Self {
|
||||||
|
self.configuration.cookie.same_site = same_site;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set the `Path` attribute for the cookie used to store the session ID.
|
||||||
|
///
|
||||||
|
/// By default, the attribute is set to `/`.
|
||||||
|
pub fn cookie_path(mut self, path: String) -> Self {
|
||||||
|
self.configuration.cookie.path = path;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set the `Domain` attribute for the cookie used to store the session ID.
|
||||||
|
///
|
||||||
|
/// Use `None` to leave the attribute unspecified. If unspecified, the attribute defaults
|
||||||
|
/// to the same host that set the cookie, excluding subdomains.
|
||||||
|
///
|
||||||
|
/// By default, the attribute is left unspecified.
|
||||||
|
pub fn cookie_domain(mut self, domain: Option<String>) -> Self {
|
||||||
|
self.configuration.cookie.domain = domain;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Choose how the session cookie content should be secured.
|
||||||
|
///
|
||||||
|
/// - [`CookieContentSecurity::Private`] selects encrypted cookie content.
|
||||||
|
/// - [`CookieContentSecurity::Signed`] selects signed cookie content.
|
||||||
|
///
|
||||||
|
/// # Default
|
||||||
|
/// By default, the cookie content is encrypted. Encrypted was chosen instead of signed as
|
||||||
|
/// default because it reduces the chances of sensitive information being exposed in the session
|
||||||
|
/// key by accident, regardless of [`SessionStore`] implementation you chose to use.
|
||||||
|
///
|
||||||
|
/// For example, if you are using cookie-based storage, you definitely want the cookie content
|
||||||
|
/// to be encrypted—the whole session state is embedded in the cookie! If you are using
|
||||||
|
/// Redis-based storage, signed is more than enough - the cookie content is just a unique
|
||||||
|
/// tamper-proof session key.
|
||||||
|
pub fn cookie_content_security(mut self, content_security: CookieContentSecurity) -> Self {
|
||||||
|
self.configuration.cookie.content_security = content_security;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Set the `HttpOnly` attribute for the cookie used to store the session ID.
|
||||||
|
///
|
||||||
|
/// If the cookie is set as `HttpOnly`, it will not be visible to any JavaScript snippets
|
||||||
|
/// running in the browser.
|
||||||
|
///
|
||||||
|
/// Default is `true`.
|
||||||
|
pub fn cookie_http_only(mut self, http_only: bool) -> Self {
|
||||||
|
self.configuration.cookie.http_only = http_only;
|
||||||
|
self
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Finalise the builder and return a [`SessionMiddleware`] instance.
|
||||||
|
#[must_use]
|
||||||
|
pub fn build(self) -> SessionMiddleware<Store> {
|
||||||
|
SessionMiddleware::from_parts(self.storage_backend, self.configuration)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub(crate) struct Configuration {
|
||||||
|
pub(crate) cookie: CookieConfiguration,
|
||||||
|
pub(crate) session: SessionConfiguration,
|
||||||
|
pub(crate) ttl_extension_policy: TtlExtensionPolicy,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub(crate) struct SessionConfiguration {
|
||||||
|
pub(crate) state_ttl: Duration,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
pub(crate) struct CookieConfiguration {
|
||||||
|
pub(crate) secure: bool,
|
||||||
|
pub(crate) http_only: bool,
|
||||||
|
pub(crate) name: String,
|
||||||
|
pub(crate) same_site: SameSite,
|
||||||
|
pub(crate) path: String,
|
||||||
|
pub(crate) domain: Option<String>,
|
||||||
|
pub(crate) max_age: Option<Duration>,
|
||||||
|
pub(crate) content_security: CookieContentSecurity,
|
||||||
|
pub(crate) key: Key,
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn default_configuration(key: Key) -> Configuration {
|
||||||
|
Configuration {
|
||||||
|
cookie: CookieConfiguration {
|
||||||
|
secure: true,
|
||||||
|
http_only: true,
|
||||||
|
name: "id".into(),
|
||||||
|
same_site: SameSite::Lax,
|
||||||
|
path: "/".into(),
|
||||||
|
domain: None,
|
||||||
|
max_age: None,
|
||||||
|
content_security: CookieContentSecurity::Private,
|
||||||
|
key,
|
||||||
|
},
|
||||||
|
session: SessionConfiguration {
|
||||||
|
state_ttl: default_ttl(),
|
||||||
|
},
|
||||||
|
ttl_extension_policy: default_ttl_extension_policy(),
|
||||||
|
}
|
||||||
|
}
|
@ -27,11 +27,11 @@
|
|||||||
//! against the active [`Session`].
|
//! against the active [`Session`].
|
||||||
//!
|
//!
|
||||||
//! `actix-session` provides some built-in storage backends: ([`CookieSessionStore`],
|
//! `actix-session` provides some built-in storage backends: ([`CookieSessionStore`],
|
||||||
//! [`RedisSessionStore`], and [`RedisActorSessionStore`]) - you can create a custom storage backend
|
//! [`RedisSessionStore`]) - you can create a custom storage backend by implementing the
|
||||||
//! by implementing the [`SessionStore`] trait.
|
//! [`SessionStore`] trait.
|
||||||
//!
|
//!
|
||||||
//! Further reading on sessions:
|
//! Further reading on sessions:
|
||||||
//! - [RFC6265](https://datatracker.ietf.org/doc/html/rfc6265);
|
//! - [RFC 6265](https://datatracker.ietf.org/doc/html/rfc6265);
|
||||||
//! - [OWASP's session management cheat-sheet](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html).
|
//! - [OWASP's session management cheat-sheet](https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html).
|
||||||
//!
|
//!
|
||||||
//! # Getting started
|
//! # Getting started
|
||||||
@ -40,21 +40,27 @@
|
|||||||
//!
|
//!
|
||||||
//! ```no_run
|
//! ```no_run
|
||||||
//! use actix_web::{web, App, HttpServer, HttpResponse, Error};
|
//! use actix_web::{web, App, HttpServer, HttpResponse, Error};
|
||||||
//! use actix_session::{Session, SessionMiddleware, storage::RedisActorSessionStore};
|
//! use actix_session::{Session, SessionMiddleware, storage::RedisSessionStore};
|
||||||
//! use actix_web::cookie::Key;
|
//! use actix_web::cookie::Key;
|
||||||
//!
|
//!
|
||||||
//! #[actix_web::main]
|
//! #[actix_web::main]
|
||||||
//! async fn main() -> std::io::Result<()> {
|
//! async fn main() -> std::io::Result<()> {
|
||||||
//! // The secret key would usually be read from a configuration file/environment variables.
|
//! // When using `Key::generate()` it is important to initialize outside of the
|
||||||
|
//! // `HttpServer::new` closure. When deployed the secret key should be read from a
|
||||||
|
//! // configuration file or environment variables.
|
||||||
//! let secret_key = Key::generate();
|
//! let secret_key = Key::generate();
|
||||||
//! let redis_connection_string = "127.0.0.1:6379";
|
//!
|
||||||
|
//! let redis_store = RedisSessionStore::new("redis://127.0.0.1:6379")
|
||||||
|
//! .await
|
||||||
|
//! .unwrap();
|
||||||
|
//!
|
||||||
//! HttpServer::new(move ||
|
//! HttpServer::new(move ||
|
||||||
//! App::new()
|
//! App::new()
|
||||||
//! // Add session management to your application using Redis for session state storage
|
//! // Add session management to your application using Redis for session state storage
|
||||||
//! .wrap(
|
//! .wrap(
|
||||||
//! SessionMiddleware::new(
|
//! SessionMiddleware::new(
|
||||||
//! RedisActorSessionStore::new(redis_connection_string),
|
//! redis_store.clone(),
|
||||||
//! secret_key.clone()
|
//! secret_key.clone(),
|
||||||
//! )
|
//! )
|
||||||
//! )
|
//! )
|
||||||
//! .default_service(web::to(|| HttpResponse::Ok())))
|
//! .default_service(web::to(|| HttpResponse::Ok())))
|
||||||
@ -65,7 +71,7 @@
|
|||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! The session state can be accessed and modified by your request handlers using the [`Session`]
|
//! The session state can be accessed and modified by your request handlers using the [`Session`]
|
||||||
//! extractor.
|
//! extractor. Note that this doesn't work in the stream of a streaming response.
|
||||||
//!
|
//!
|
||||||
//! ```no_run
|
//! ```no_run
|
||||||
//! use actix_web::Error;
|
//! use actix_web::Error;
|
||||||
@ -93,37 +99,28 @@
|
|||||||
//! - a purely cookie-based "backend", [`CookieSessionStore`], using the `cookie-session` feature
|
//! - a purely cookie-based "backend", [`CookieSessionStore`], using the `cookie-session` feature
|
||||||
//! flag.
|
//! flag.
|
||||||
//!
|
//!
|
||||||
//! ```toml
|
//! ```console
|
||||||
//! [dependencies]
|
//! cargo add actix-session --features=cookie-session
|
||||||
//! # ...
|
|
||||||
//! actix-session = { version = "...", features = ["cookie-session"] }
|
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! - a Redis-based backend via [`actix-redis`](https://docs.rs/acitx-redis),
|
//! - a Redis-based backend via the [`redis`] crate, [`RedisSessionStore`], using the
|
||||||
//! [`RedisActorSessionStore`], using the `redis-actor-session` feature flag.
|
//! `redis-session` feature flag.
|
||||||
//!
|
//!
|
||||||
//! ```toml
|
//! ```console
|
||||||
//! [dependencies]
|
//! cargo add actix-session --features=redis-session
|
||||||
//! # ...
|
|
||||||
//! actix-session = { version = "...", features = ["redis-actor-session"] }
|
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! - a Redis-based backend via [`redis-rs`](https://docs.rs/redis-rs), [`RedisSessionStore`], using
|
//! Add the `redis-session-native-tls` feature flag if you want to connect to Redis using a secure
|
||||||
//! the `redis-rs-session` feature flag.
|
//! connection (via the `native-tls` crate):
|
||||||
//!
|
//!
|
||||||
//! ```toml
|
//! ```console
|
||||||
//! [dependencies]
|
//! cargo add actix-session --features=redis-session-native-tls
|
||||||
//! # ...
|
|
||||||
//! actix-session = { version = "...", features = ["redis-rs-session"] }
|
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! Add the `redis-rs-tls-session` feature flag if you want to connect to Redis using a secured
|
//! If you, instead, prefer depending on `rustls`, use the `redis-session-rustls` feature flag:
|
||||||
//! connection:
|
|
||||||
//!
|
//!
|
||||||
//! ```toml
|
//! ```console
|
||||||
//! [dependencies]
|
//! cargo add actix-session --features=redis-session-rustls
|
||||||
//! # ...
|
|
||||||
//! actix-session = { version = "...", features = ["redis-rs-session", "redis-rs-tls-session"] }
|
|
||||||
//! ```
|
//! ```
|
||||||
//!
|
//!
|
||||||
//! You can implement your own session storage backend using the [`SessionStore`] trait.
|
//! You can implement your own session storage backend using the [`SessionStore`] trait.
|
||||||
@ -131,40 +128,35 @@
|
|||||||
//! [`SessionStore`]: storage::SessionStore
|
//! [`SessionStore`]: storage::SessionStore
|
||||||
//! [`CookieSessionStore`]: storage::CookieSessionStore
|
//! [`CookieSessionStore`]: storage::CookieSessionStore
|
||||||
//! [`RedisSessionStore`]: storage::RedisSessionStore
|
//! [`RedisSessionStore`]: storage::RedisSessionStore
|
||||||
//! [`RedisActorSessionStore`]: storage::RedisActorSessionStore
|
|
||||||
|
|
||||||
#![deny(rust_2018_idioms, nonstandard_style)]
|
#![forbid(unsafe_code)]
|
||||||
#![warn(future_incompatible, missing_docs)]
|
#![warn(missing_docs)]
|
||||||
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
|
#![doc(html_logo_url = "https://actix.rs/img/logo.png")]
|
||||||
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
|
#![doc(html_favicon_url = "https://actix.rs/favicon.ico")]
|
||||||
#![cfg_attr(docsrs, feature(doc_cfg))]
|
#![cfg_attr(docsrs, feature(doc_auto_cfg))]
|
||||||
|
|
||||||
|
pub mod config;
|
||||||
mod middleware;
|
mod middleware;
|
||||||
mod session;
|
mod session;
|
||||||
mod session_ext;
|
mod session_ext;
|
||||||
pub mod storage;
|
pub mod storage;
|
||||||
|
|
||||||
pub use self::middleware::{
|
pub use self::{
|
||||||
CookieContentSecurity, SessionLength, SessionMiddleware, SessionMiddlewareBuilder,
|
middleware::SessionMiddleware,
|
||||||
|
session::{Session, SessionGetError, SessionInsertError, SessionStatus},
|
||||||
|
session_ext::SessionExt,
|
||||||
};
|
};
|
||||||
pub use self::session::{Session, SessionStatus};
|
|
||||||
pub use self::session_ext::SessionExt;
|
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
|
#[allow(missing_docs)]
|
||||||
pub mod test_helpers {
|
pub mod test_helpers {
|
||||||
use actix_web::cookie::Key;
|
use actix_web::cookie::Key;
|
||||||
use rand::{distributions::Alphanumeric, thread_rng, Rng};
|
|
||||||
|
|
||||||
use crate::{storage::SessionStore, CookieContentSecurity};
|
use crate::{config::CookieContentSecurity, storage::SessionStore};
|
||||||
|
|
||||||
/// Generate a random cookie signing/encryption key.
|
/// Generate a random cookie signing/encryption key.
|
||||||
pub fn key() -> Key {
|
pub fn key() -> Key {
|
||||||
let signing_key: String = thread_rng()
|
Key::generate()
|
||||||
.sample_iter(&Alphanumeric)
|
|
||||||
.take(64)
|
|
||||||
.map(char::from)
|
|
||||||
.collect();
|
|
||||||
Key::from(signing_key.as_bytes())
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A ready-to-go acceptance test suite to verify that sessions behave as expected
|
/// A ready-to-go acceptance test suite to verify that sessions behave as expected
|
||||||
@ -183,10 +175,15 @@ pub mod test_helpers {
|
|||||||
CookieContentSecurity::Signed,
|
CookieContentSecurity::Signed,
|
||||||
CookieContentSecurity::Private,
|
CookieContentSecurity::Private,
|
||||||
] {
|
] {
|
||||||
println!("Using {:?} as cookie content security policy.", policy);
|
println!("Using {policy:?} as cookie content security policy.");
|
||||||
acceptance_tests::basic_workflow(store_builder.clone(), *policy).await;
|
acceptance_tests::basic_workflow(store_builder.clone(), *policy).await;
|
||||||
acceptance_tests::expiration_is_refreshed_on_changes(store_builder.clone(), *policy)
|
acceptance_tests::expiration_is_refreshed_on_changes(store_builder.clone(), *policy)
|
||||||
.await;
|
.await;
|
||||||
|
acceptance_tests::expiration_is_always_refreshed_if_configured_to_refresh_on_every_request(
|
||||||
|
store_builder.clone(),
|
||||||
|
*policy,
|
||||||
|
)
|
||||||
|
.await;
|
||||||
acceptance_tests::complex_workflow(
|
acceptance_tests::complex_workflow(
|
||||||
store_builder.clone(),
|
store_builder.clone(),
|
||||||
is_invalidation_supported,
|
is_invalidation_supported,
|
||||||
@ -199,18 +196,20 @@ pub mod test_helpers {
|
|||||||
|
|
||||||
mod acceptance_tests {
|
mod acceptance_tests {
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
dev::Service,
|
cookie::time,
|
||||||
|
dev::{Service, ServiceResponse},
|
||||||
guard, middleware, test,
|
guard, middleware, test,
|
||||||
web::{self, get, post, resource, Bytes},
|
web::{self, get, post, resource, Bytes},
|
||||||
App, HttpResponse, Result,
|
App, HttpResponse, Result,
|
||||||
};
|
};
|
||||||
use serde::{Deserialize, Serialize};
|
use serde::{Deserialize, Serialize};
|
||||||
use serde_json::json;
|
use serde_json::json;
|
||||||
use time::Duration;
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
middleware::SessionLength, storage::SessionStore, test_helpers::key,
|
config::{CookieContentSecurity, PersistentSession, TtlExtensionPolicy},
|
||||||
CookieContentSecurity, Session, SessionExt, SessionMiddleware,
|
storage::SessionStore,
|
||||||
|
test_helpers::key,
|
||||||
|
Session, SessionExt, SessionMiddleware,
|
||||||
};
|
};
|
||||||
|
|
||||||
pub(super) async fn basic_workflow<F, Store>(
|
pub(super) async fn basic_workflow<F, Store>(
|
||||||
@ -228,9 +227,10 @@ pub mod test_helpers {
|
|||||||
.cookie_name("actix-test".into())
|
.cookie_name("actix-test".into())
|
||||||
.cookie_domain(Some("localhost".into()))
|
.cookie_domain(Some("localhost".into()))
|
||||||
.cookie_content_security(policy)
|
.cookie_content_security(policy)
|
||||||
.session_length(SessionLength::Predetermined {
|
.session_lifecycle(
|
||||||
max_session_length: Some(time::Duration::seconds(100)),
|
PersistentSession::default()
|
||||||
})
|
.session_ttl(time::Duration::seconds(100)),
|
||||||
|
)
|
||||||
.build(),
|
.build(),
|
||||||
)
|
)
|
||||||
.service(web::resource("/").to(|ses: Session| async move {
|
.service(web::resource("/").to(|ses: Session| async move {
|
||||||
@ -239,19 +239,14 @@ pub mod test_helpers {
|
|||||||
}))
|
}))
|
||||||
.service(web::resource("/test/").to(|ses: Session| async move {
|
.service(web::resource("/test/").to(|ses: Session| async move {
|
||||||
let val: usize = ses.get("counter").unwrap().unwrap();
|
let val: usize = ses.get("counter").unwrap().unwrap();
|
||||||
format!("counter: {}", val)
|
format!("counter: {val}")
|
||||||
})),
|
})),
|
||||||
)
|
)
|
||||||
.await;
|
.await;
|
||||||
|
|
||||||
let request = test::TestRequest::get().to_request();
|
let request = test::TestRequest::get().to_request();
|
||||||
let response = app.call(request).await.unwrap();
|
let response = app.call(request).await.unwrap();
|
||||||
let cookie = response
|
let cookie = response.get_cookie("actix-test").unwrap().clone();
|
||||||
.response()
|
|
||||||
.cookies()
|
|
||||||
.find(|c| c.name() == "actix-test")
|
|
||||||
.unwrap()
|
|
||||||
.clone();
|
|
||||||
assert_eq!(cookie.path().unwrap(), "/test/");
|
assert_eq!(cookie.path().unwrap(), "/test/");
|
||||||
|
|
||||||
let request = test::TestRequest::with_uri("/test/")
|
let request = test::TestRequest::with_uri("/test/")
|
||||||
@ -261,6 +256,55 @@ pub mod test_helpers {
|
|||||||
assert_eq!(body, Bytes::from_static(b"counter: 100"));
|
assert_eq!(body, Bytes::from_static(b"counter: 100"));
|
||||||
}
|
}
|
||||||
|
|
||||||
|
pub(super) async fn expiration_is_always_refreshed_if_configured_to_refresh_on_every_request<
|
||||||
|
F,
|
||||||
|
Store,
|
||||||
|
>(
|
||||||
|
store_builder: F,
|
||||||
|
policy: CookieContentSecurity,
|
||||||
|
) where
|
||||||
|
Store: SessionStore + 'static,
|
||||||
|
F: Fn() -> Store + Clone + Send + 'static,
|
||||||
|
{
|
||||||
|
let session_ttl = time::Duration::seconds(60);
|
||||||
|
let app = test::init_service(
|
||||||
|
App::new()
|
||||||
|
.wrap(
|
||||||
|
SessionMiddleware::builder(store_builder(), key())
|
||||||
|
.cookie_content_security(policy)
|
||||||
|
.session_lifecycle(
|
||||||
|
PersistentSession::default()
|
||||||
|
.session_ttl(session_ttl)
|
||||||
|
.session_ttl_extension_policy(
|
||||||
|
TtlExtensionPolicy::OnEveryRequest,
|
||||||
|
),
|
||||||
|
)
|
||||||
|
.build(),
|
||||||
|
)
|
||||||
|
.service(web::resource("/").to(|ses: Session| async move {
|
||||||
|
let _ = ses.insert("counter", 100);
|
||||||
|
"test"
|
||||||
|
}))
|
||||||
|
.service(web::resource("/test/").to(|| async move { "no-changes-in-session" })),
|
||||||
|
)
|
||||||
|
.await;
|
||||||
|
|
||||||
|
// Create session
|
||||||
|
let request = test::TestRequest::get().to_request();
|
||||||
|
let response = app.call(request).await.unwrap();
|
||||||
|
let cookie_1 = response.get_cookie("id").expect("Cookie is set");
|
||||||
|
assert_eq!(cookie_1.max_age(), Some(session_ttl));
|
||||||
|
|
||||||
|
// Fire a request that doesn't touch the session state, check
|
||||||
|
// that the session cookie is present and its expiry is set to the maximum we configured.
|
||||||
|
let request = test::TestRequest::with_uri("/test/")
|
||||||
|
.cookie(cookie_1)
|
||||||
|
.to_request();
|
||||||
|
let response = app.call(request).await.unwrap();
|
||||||
|
let cookie_2 = response.get_cookie("id").expect("Cookie is set");
|
||||||
|
assert_eq!(cookie_2.max_age(), Some(session_ttl));
|
||||||
|
}
|
||||||
|
|
||||||
pub(super) async fn expiration_is_refreshed_on_changes<F, Store>(
|
pub(super) async fn expiration_is_refreshed_on_changes<F, Store>(
|
||||||
store_builder: F,
|
store_builder: F,
|
||||||
policy: CookieContentSecurity,
|
policy: CookieContentSecurity,
|
||||||
@ -268,14 +312,15 @@ pub mod test_helpers {
|
|||||||
Store: SessionStore + 'static,
|
Store: SessionStore + 'static,
|
||||||
F: Fn() -> Store + Clone + Send + 'static,
|
F: Fn() -> Store + Clone + Send + 'static,
|
||||||
{
|
{
|
||||||
|
let session_ttl = time::Duration::seconds(60);
|
||||||
let app = test::init_service(
|
let app = test::init_service(
|
||||||
App::new()
|
App::new()
|
||||||
.wrap(
|
.wrap(
|
||||||
SessionMiddleware::builder(store_builder(), key())
|
SessionMiddleware::builder(store_builder(), key())
|
||||||
.cookie_content_security(policy)
|
.cookie_content_security(policy)
|
||||||
.session_length(SessionLength::Predetermined {
|
.session_lifecycle(
|
||||||
max_session_length: Some(time::Duration::seconds(60)),
|
PersistentSession::default().session_ttl(session_ttl),
|
||||||
})
|
)
|
||||||
.build(),
|
.build(),
|
||||||
)
|
)
|
||||||
.service(web::resource("/").to(|ses: Session| async move {
|
.service(web::resource("/").to(|ses: Session| async move {
|
||||||
@ -288,25 +333,19 @@ pub mod test_helpers {
|
|||||||
|
|
||||||
let request = test::TestRequest::get().to_request();
|
let request = test::TestRequest::get().to_request();
|
||||||
let response = app.call(request).await.unwrap();
|
let response = app.call(request).await.unwrap();
|
||||||
let cookie_1 = response
|
let cookie_1 = response.get_cookie("id").expect("Cookie is set");
|
||||||
.response()
|
assert_eq!(cookie_1.max_age(), Some(session_ttl));
|
||||||
.cookies()
|
|
||||||
.find(|c| c.name() == "id")
|
|
||||||
.expect("Cookie is set");
|
|
||||||
assert_eq!(cookie_1.max_age(), Some(Duration::seconds(60)));
|
|
||||||
|
|
||||||
let request = test::TestRequest::with_uri("/test/").to_request();
|
let request = test::TestRequest::with_uri("/test/")
|
||||||
|
.cookie(cookie_1.clone())
|
||||||
|
.to_request();
|
||||||
let response = app.call(request).await.unwrap();
|
let response = app.call(request).await.unwrap();
|
||||||
assert!(response.response().cookies().next().is_none());
|
assert!(response.response().cookies().next().is_none());
|
||||||
|
|
||||||
let request = test::TestRequest::get().to_request();
|
let request = test::TestRequest::get().cookie(cookie_1).to_request();
|
||||||
let response = app.call(request).await.unwrap();
|
let response = app.call(request).await.unwrap();
|
||||||
let cookie_2 = response
|
let cookie_2 = response.get_cookie("id").expect("Cookie is set");
|
||||||
.response()
|
assert_eq!(cookie_2.max_age(), Some(session_ttl));
|
||||||
.cookies()
|
|
||||||
.find(|c| c.name() == "id")
|
|
||||||
.expect("Cookie is set");
|
|
||||||
assert_eq!(cookie_2.max_age(), Some(Duration::seconds(60)));
|
|
||||||
}
|
}
|
||||||
|
|
||||||
pub(super) async fn guard<F, Store>(store_builder: F, policy: CookieContentSecurity)
|
pub(super) async fn guard<F, Store>(store_builder: F, policy: CookieContentSecurity)
|
||||||
@ -320,9 +359,9 @@ pub mod test_helpers {
|
|||||||
SessionMiddleware::builder(store_builder(), key())
|
SessionMiddleware::builder(store_builder(), key())
|
||||||
.cookie_name("test-session".into())
|
.cookie_name("test-session".into())
|
||||||
.cookie_content_security(policy)
|
.cookie_content_security(policy)
|
||||||
.session_length(SessionLength::Predetermined {
|
.session_lifecycle(
|
||||||
max_session_length: Some(time::Duration::days(7)),
|
PersistentSession::default().session_ttl(time::Duration::days(7)),
|
||||||
})
|
)
|
||||||
.build(),
|
.build(),
|
||||||
)
|
)
|
||||||
.wrap(middleware::Logger::default())
|
.wrap(middleware::Logger::default())
|
||||||
@ -402,15 +441,16 @@ pub mod test_helpers {
|
|||||||
Store: SessionStore + 'static,
|
Store: SessionStore + 'static,
|
||||||
F: Fn() -> Store + Clone + Send + 'static,
|
F: Fn() -> Store + Clone + Send + 'static,
|
||||||
{
|
{
|
||||||
|
let session_ttl = time::Duration::days(7);
|
||||||
let srv = actix_test::start(move || {
|
let srv = actix_test::start(move || {
|
||||||
App::new()
|
App::new()
|
||||||
.wrap(
|
.wrap(
|
||||||
SessionMiddleware::builder(store_builder(), key())
|
SessionMiddleware::builder(store_builder(), key())
|
||||||
.cookie_name("test-session".into())
|
.cookie_name("test-session".into())
|
||||||
.cookie_content_security(policy)
|
.cookie_content_security(policy)
|
||||||
.session_length(SessionLength::Predetermined {
|
.session_lifecycle(
|
||||||
max_session_length: Some(time::Duration::days(7)),
|
PersistentSession::default().session_ttl(session_ttl),
|
||||||
})
|
)
|
||||||
.build(),
|
.build(),
|
||||||
)
|
)
|
||||||
.wrap(middleware::Logger::default())
|
.wrap(middleware::Logger::default())
|
||||||
@ -456,7 +496,7 @@ pub mod test_helpers {
|
|||||||
.into_iter()
|
.into_iter()
|
||||||
.find(|c| c.name() == "test-session")
|
.find(|c| c.name() == "test-session")
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(cookie_1.max_age(), Some(Duration::days(7)));
|
assert_eq!(cookie_1.max_age(), Some(session_ttl));
|
||||||
|
|
||||||
// Step 3: GET index, including session cookie #1 in request
|
// Step 3: GET index, including session cookie #1 in request
|
||||||
// - set-cookie will *not* be in response
|
// - set-cookie will *not* be in response
|
||||||
@ -494,7 +534,7 @@ pub mod test_helpers {
|
|||||||
.into_iter()
|
.into_iter()
|
||||||
.find(|c| c.name() == "test-session")
|
.find(|c| c.name() == "test-session")
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_eq!(cookie_2.max_age(), Some(Duration::days(7)));
|
assert_eq!(cookie_2.max_age(), cookie_1.max_age());
|
||||||
|
|
||||||
// Step 5: POST to login, including session cookie #2 in request
|
// Step 5: POST to login, including session cookie #2 in request
|
||||||
// - set-cookie actix-session will be in response (session cookie #3)
|
// - set-cookie actix-session will be in response (session cookie #3)
|
||||||
@ -608,7 +648,7 @@ pub mod test_helpers {
|
|||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Serialize, Deserialize, Debug, PartialEq)]
|
#[derive(Debug, PartialEq, Eq, Serialize, Deserialize)]
|
||||||
pub struct IndexResponse {
|
pub struct IndexResponse {
|
||||||
user_id: Option<String>,
|
user_id: Option<String>,
|
||||||
counter: i32,
|
counter: i32,
|
||||||
@ -630,7 +670,7 @@ pub mod test_helpers {
|
|||||||
.get::<i32>("counter")
|
.get::<i32>("counter")
|
||||||
.unwrap_or(Some(0))
|
.unwrap_or(Some(0))
|
||||||
.map_or(1, |inner| inner + 1);
|
.map_or(1, |inner| inner + 1);
|
||||||
session.insert("counter", &counter)?;
|
session.insert("counter", counter)?;
|
||||||
|
|
||||||
Ok(HttpResponse::Ok().json(&IndexResponse { user_id, counter }))
|
Ok(HttpResponse::Ok().json(&IndexResponse { user_id, counter }))
|
||||||
}
|
}
|
||||||
@ -666,14 +706,24 @@ pub mod test_helpers {
|
|||||||
async fn logout(session: Session) -> Result<HttpResponse> {
|
async fn logout(session: Session) -> Result<HttpResponse> {
|
||||||
let id: Option<String> = session.get("user_id")?;
|
let id: Option<String> = session.get("user_id")?;
|
||||||
|
|
||||||
let body = if let Some(x) = id {
|
let body = if let Some(id) = id {
|
||||||
session.purge();
|
session.purge();
|
||||||
format!("Logged out: {}", x)
|
format!("Logged out: {id}")
|
||||||
} else {
|
} else {
|
||||||
"Could not log out anonymous user".to_owned()
|
"Could not log out anonymous user".to_owned()
|
||||||
};
|
};
|
||||||
|
|
||||||
Ok(HttpResponse::Ok().body(body))
|
Ok(HttpResponse::Ok().body(body))
|
||||||
}
|
}
|
||||||
|
|
||||||
|
trait ServiceResponseExt {
|
||||||
|
fn get_cookie(&self, cookie_name: &str) -> Option<actix_web::cookie::Cookie<'_>>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ServiceResponseExt for ServiceResponse {
|
||||||
|
fn get_cookie(&self, cookie_name: &str) -> Option<actix_web::cookie::Cookie<'_>> {
|
||||||
|
self.response().cookies().find(|c| c.name() == cookie_name)
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,17 +1,20 @@
|
|||||||
use std::{collections::HashMap, convert::TryInto, fmt, future::Future, pin::Pin, rc::Rc};
|
use std::{collections::HashMap, fmt, future::Future, pin::Pin, rc::Rc};
|
||||||
|
|
||||||
use actix_utils::future::{ready, Ready};
|
use actix_utils::future::{ready, Ready};
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
body::MessageBody,
|
body::MessageBody,
|
||||||
cookie::{Cookie, CookieJar, Key, SameSite},
|
cookie::{Cookie, CookieJar, Key},
|
||||||
dev::{forward_ready, ResponseHead, Service, ServiceRequest, ServiceResponse, Transform},
|
dev::{forward_ready, ResponseHead, Service, ServiceRequest, ServiceResponse, Transform},
|
||||||
http::header::{HeaderValue, SET_COOKIE},
|
http::header::{HeaderValue, SET_COOKIE},
|
||||||
HttpResponse,
|
HttpResponse,
|
||||||
};
|
};
|
||||||
use anyhow::Context;
|
use anyhow::Context;
|
||||||
use time::Duration;
|
|
||||||
|
|
||||||
use crate::{
|
use crate::{
|
||||||
|
config::{
|
||||||
|
self, Configuration, CookieConfiguration, CookieContentSecurity, SessionMiddlewareBuilder,
|
||||||
|
TtlExtensionPolicy,
|
||||||
|
},
|
||||||
storage::{LoadError, SessionKey, SessionStore},
|
storage::{LoadError, SessionKey, SessionStore},
|
||||||
Session, SessionStatus,
|
Session, SessionStatus,
|
||||||
};
|
};
|
||||||
@ -29,12 +32,22 @@ use crate::{
|
|||||||
/// To create a new instance of [`SessionMiddleware`] you need to provide:
|
/// To create a new instance of [`SessionMiddleware`] you need to provide:
|
||||||
///
|
///
|
||||||
/// - an instance of the session storage backend you wish to use (i.e. an implementation of
|
/// - an instance of the session storage backend you wish to use (i.e. an implementation of
|
||||||
/// [`SessionStore]);
|
/// [`SessionStore`]);
|
||||||
/// - a secret key, to sign or encrypt the content of client-side session cookie.
|
/// - a secret key, to sign or encrypt the content of client-side session cookie.
|
||||||
///
|
///
|
||||||
|
/// # How did we choose defaults?
|
||||||
|
/// You should not regret adding `actix-session` to your dependencies and going to production using
|
||||||
|
/// the default configuration. That is why, when in doubt, we opt to use the most secure option for
|
||||||
|
/// each configuration parameter.
|
||||||
|
///
|
||||||
|
/// We expose knobs to change the default to suit your needs—i.e., if you know what you are doing,
|
||||||
|
/// we will not stop you. But being a subject-matter expert should not be a requirement to deploy
|
||||||
|
/// reasonably secure implementation of sessions.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
/// ```no_run
|
/// ```no_run
|
||||||
/// use actix_web::{web, App, HttpServer, HttpResponse, Error};
|
/// use actix_web::{web, App, HttpServer, HttpResponse, Error};
|
||||||
/// use actix_session::{Session, SessionMiddleware, storage::RedisActorSessionStore};
|
/// use actix_session::{Session, SessionMiddleware, storage::RedisSessionStore};
|
||||||
/// use actix_web::cookie::Key;
|
/// use actix_web::cookie::Key;
|
||||||
///
|
///
|
||||||
/// // The secret key would usually be read from a configuration file/environment variables.
|
/// // The secret key would usually be read from a configuration file/environment variables.
|
||||||
@ -46,17 +59,17 @@ use crate::{
|
|||||||
/// #[actix_web::main]
|
/// #[actix_web::main]
|
||||||
/// async fn main() -> std::io::Result<()> {
|
/// async fn main() -> std::io::Result<()> {
|
||||||
/// let secret_key = get_secret_key();
|
/// let secret_key = get_secret_key();
|
||||||
/// let redis_connection_string = "127.0.0.1:6379";
|
/// let storage = RedisSessionStore::new("127.0.0.1:6379").await.unwrap();
|
||||||
/// HttpServer::new(move ||
|
///
|
||||||
|
/// HttpServer::new(move || {
|
||||||
/// App::new()
|
/// App::new()
|
||||||
/// // Add session management to your application using Redis for session state storage
|
/// // Add session management to your application using Redis as storage
|
||||||
/// .wrap(
|
/// .wrap(SessionMiddleware::new(
|
||||||
/// SessionMiddleware::new(
|
/// storage.clone(),
|
||||||
/// RedisActorSessionStore::new(redis_connection_string),
|
/// secret_key.clone(),
|
||||||
/// secret_key.clone()
|
/// ))
|
||||||
/// )
|
/// .default_service(web::to(|| HttpResponse::Ok()))
|
||||||
/// )
|
/// })
|
||||||
/// .default_service(web::to(|| HttpResponse::Ok())))
|
|
||||||
/// .bind(("127.0.0.1", 8080))?
|
/// .bind(("127.0.0.1", 8080))?
|
||||||
/// .run()
|
/// .run()
|
||||||
/// .await
|
/// .await
|
||||||
@ -66,8 +79,9 @@ use crate::{
|
|||||||
/// If you want to customise use [`builder`](Self::builder) instead of [`new`](Self::new):
|
/// If you want to customise use [`builder`](Self::builder) instead of [`new`](Self::new):
|
||||||
///
|
///
|
||||||
/// ```no_run
|
/// ```no_run
|
||||||
/// use actix_web::{cookie::Key, web, App, HttpServer, HttpResponse, Error};
|
/// use actix_web::{App, cookie::{Key, time}, Error, HttpResponse, HttpServer, web};
|
||||||
/// use actix_session::{Session, SessionMiddleware, storage::RedisActorSessionStore, SessionLength};
|
/// use actix_session::{Session, SessionMiddleware, storage::RedisSessionStore};
|
||||||
|
/// use actix_session::config::PersistentSession;
|
||||||
///
|
///
|
||||||
/// // The secret key would usually be read from a configuration file/environment variables.
|
/// // The secret key would usually be read from a configuration file/environment variables.
|
||||||
/// fn get_secret_key() -> Key {
|
/// fn get_secret_key() -> Key {
|
||||||
@ -78,293 +92,57 @@ use crate::{
|
|||||||
/// #[actix_web::main]
|
/// #[actix_web::main]
|
||||||
/// async fn main() -> std::io::Result<()> {
|
/// async fn main() -> std::io::Result<()> {
|
||||||
/// let secret_key = get_secret_key();
|
/// let secret_key = get_secret_key();
|
||||||
/// let redis_connection_string = "127.0.0.1:6379";
|
/// let storage = RedisSessionStore::new("127.0.0.1:6379").await.unwrap();
|
||||||
/// HttpServer::new(move ||
|
///
|
||||||
|
/// HttpServer::new(move || {
|
||||||
/// App::new()
|
/// App::new()
|
||||||
/// // Customise session length!
|
/// // Customise session length!
|
||||||
/// .wrap(
|
/// .wrap(
|
||||||
/// SessionMiddleware::builder(
|
/// SessionMiddleware::builder(storage.clone(), secret_key.clone())
|
||||||
/// RedisActorSessionStore::new(redis_connection_string),
|
/// .session_lifecycle(
|
||||||
/// secret_key.clone()
|
/// PersistentSession::default().session_ttl(time::Duration::days(5)),
|
||||||
/// )
|
/// )
|
||||||
/// .session_length(SessionLength::Predetermined {
|
|
||||||
/// max_session_length: Some(time::Duration::days(5)),
|
|
||||||
/// })
|
|
||||||
/// .build(),
|
/// .build(),
|
||||||
/// )
|
/// )
|
||||||
/// .default_service(web::to(|| HttpResponse::Ok())))
|
/// .default_service(web::to(|| HttpResponse::Ok()))
|
||||||
|
/// })
|
||||||
/// .bind(("127.0.0.1", 8080))?
|
/// .bind(("127.0.0.1", 8080))?
|
||||||
/// .run()
|
/// .run()
|
||||||
/// .await
|
/// .await
|
||||||
/// }
|
/// }
|
||||||
/// ```
|
/// ```
|
||||||
///
|
|
||||||
/// ## How did we choose defaults?
|
|
||||||
///
|
|
||||||
/// You should not regret adding `actix-session` to your dependencies and going to production using
|
|
||||||
/// the default configuration. That is why, when in doubt, we opt to use the most secure option for
|
|
||||||
/// each configuration parameter.
|
|
||||||
///
|
|
||||||
/// We expose knobs to change the default to suit your needs—i.e., if you know what you are doing,
|
|
||||||
/// we will not stop you. But being a subject-matter expert should not be a requirement to deploy
|
|
||||||
/// reasonably secure implementation of sessions.
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct SessionMiddleware<Store: SessionStore> {
|
pub struct SessionMiddleware<Store: SessionStore> {
|
||||||
storage_backend: Rc<Store>,
|
storage_backend: Rc<Store>,
|
||||||
configuration: Rc<Configuration>,
|
configuration: Rc<Configuration>,
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
struct Configuration {
|
|
||||||
cookie: CookieConfiguration,
|
|
||||||
session: SessionConfiguration,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
struct SessionConfiguration {
|
|
||||||
state_ttl: Duration,
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Clone)]
|
|
||||||
struct CookieConfiguration {
|
|
||||||
secure: bool,
|
|
||||||
http_only: bool,
|
|
||||||
name: String,
|
|
||||||
same_site: SameSite,
|
|
||||||
path: String,
|
|
||||||
domain: Option<String>,
|
|
||||||
max_age: Option<Duration>,
|
|
||||||
content_security: CookieContentSecurity,
|
|
||||||
key: Key,
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Describes how long a session should last.
|
|
||||||
///
|
|
||||||
/// Used by [`SessionMiddlewareBuilder::session_length`].
|
|
||||||
#[derive(Clone, Debug)]
|
|
||||||
pub enum SessionLength {
|
|
||||||
/// The session cookie will expire when the current browser session ends.
|
|
||||||
///
|
|
||||||
/// When does a browser session end? It depends on the browser! Chrome, for example, will often
|
|
||||||
/// continue running in the background when the browser is closed—session cookies are not
|
|
||||||
/// deleted and they will still be available when the browser is opened again. Check the
|
|
||||||
/// documentation of the browsers you are targeting for up-to-date information.
|
|
||||||
BrowserSession {
|
|
||||||
/// We must provide a time-to-live (TTL) when storing the session state in the storage
|
|
||||||
/// backend—we do not want to store session states indefinitely, otherwise we will
|
|
||||||
/// inevitably run out of storage by holding on to the state of countless abandoned or
|
|
||||||
/// expired sessions!
|
|
||||||
///
|
|
||||||
/// We are dealing with the lifecycle of two uncorrelated object here: the session cookie
|
|
||||||
/// and the session state. It is not a big issue if the session state outlives the cookie—
|
|
||||||
/// we are wasting some space in the backend storage, but it will be cleaned up eventually.
|
|
||||||
/// What happens, instead, if the cookie outlives the session state? A new session starts—
|
|
||||||
/// e.g. if sessions are being used for authentication, the user is de-facto logged out.
|
|
||||||
///
|
|
||||||
/// It is not possible to predict with certainty how long a browser session is going to
|
|
||||||
/// last—you need to provide a reasonable upper bound. You do so via `state_ttl`—it dictates
|
|
||||||
/// what TTL should be used for session state when the lifecycle of the session cookie is
|
|
||||||
/// tied to the browser session length. [`SessionMiddleware`] will default to 1 day if
|
|
||||||
/// `state_ttl` is left unspecified.
|
|
||||||
state_ttl: Option<Duration>,
|
|
||||||
},
|
|
||||||
|
|
||||||
/// The session cookie will be a [persistent cookie].
|
|
||||||
///
|
|
||||||
/// Persistent cookies have a pre-determined lifetime, specified via the `Max-Age` or `Expires`
|
|
||||||
/// attribute. They do not disappear when the current browser session ends.
|
|
||||||
///
|
|
||||||
/// [persistent cookie]: https://www.whitehatsec.com/glossary/content/persistent-session-cookie
|
|
||||||
Predetermined {
|
|
||||||
/// Set `max_session_length` to specify how long the session cookie should live.
|
|
||||||
/// [`SessionMiddleware`] will default to 1 day if `max_session_length` is set to `None`.
|
|
||||||
///
|
|
||||||
/// `max_session_length` is also used as the TTL for the session state in the
|
|
||||||
/// storage backend.
|
|
||||||
max_session_length: Option<Duration>,
|
|
||||||
},
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Used by [`SessionMiddlewareBuilder::cookie_content_security`] to determine how to secure
|
|
||||||
/// the content of the session cookie.
|
|
||||||
#[derive(Debug, Clone, Copy)]
|
|
||||||
pub enum CookieContentSecurity {
|
|
||||||
/// The cookie content is encrypted when using `CookieContentSecurity::Private`.
|
|
||||||
///
|
|
||||||
/// Encryption guarantees confidentiality and integrity: the client cannot tamper with the
|
|
||||||
/// cookie content nor decode it, as long as the encryption key remains confidential.
|
|
||||||
Private,
|
|
||||||
|
|
||||||
/// The cookie content is signed when using `CookieContentSecurity::Signed`.
|
|
||||||
///
|
|
||||||
/// Signing guarantees integrity, but it doesn't ensure confidentiality: the client cannot
|
|
||||||
/// tamper with the cookie content, but they can read it.
|
|
||||||
Signed,
|
|
||||||
}
|
|
||||||
|
|
||||||
fn default_configuration(key: Key) -> Configuration {
|
|
||||||
Configuration {
|
|
||||||
cookie: CookieConfiguration {
|
|
||||||
secure: true,
|
|
||||||
http_only: true,
|
|
||||||
name: "id".into(),
|
|
||||||
same_site: SameSite::Lax,
|
|
||||||
path: "/".into(),
|
|
||||||
domain: None,
|
|
||||||
max_age: None,
|
|
||||||
content_security: CookieContentSecurity::Private,
|
|
||||||
key,
|
|
||||||
},
|
|
||||||
session: SessionConfiguration {
|
|
||||||
state_ttl: default_ttl(),
|
|
||||||
},
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
fn default_ttl() -> Duration {
|
|
||||||
Duration::days(1)
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<Store: SessionStore> SessionMiddleware<Store> {
|
impl<Store: SessionStore> SessionMiddleware<Store> {
|
||||||
/// Use [`SessionMiddleware::new`] to initialize the session framework using the default
|
/// Use [`SessionMiddleware::new`] to initialize the session framework using the default
|
||||||
/// parameters.
|
/// parameters.
|
||||||
///
|
///
|
||||||
/// To create a new instance of [`SessionMiddleware`] you need to provide:
|
/// To create a new instance of [`SessionMiddleware`] you need to provide:
|
||||||
/// - an instance of the session storage backend you wish to use (i.e. an implementation of
|
/// - an instance of the session storage backend you wish to use (i.e. an implementation of
|
||||||
/// [`SessionStore]);
|
/// [`SessionStore`]);
|
||||||
/// - a secret key, to sign or encrypt the content of client-side session cookie.
|
/// - a secret key, to sign or encrypt the content of client-side session cookie.
|
||||||
pub fn new(store: Store, key: Key) -> Self {
|
pub fn new(store: Store, key: Key) -> Self {
|
||||||
Self {
|
Self::builder(store, key).build()
|
||||||
storage_backend: Rc::new(store),
|
|
||||||
configuration: Rc::new(default_configuration(key)),
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A fluent API to configure [`SessionMiddleware`].
|
/// A fluent API to configure [`SessionMiddleware`].
|
||||||
///
|
///
|
||||||
/// It takes as input the two required inputs to create a new instance of [`SessionMiddleware`]:
|
/// It takes as input the two required inputs to create a new instance of [`SessionMiddleware`]:
|
||||||
/// - an instance of the session storage backend you wish to use (i.e. an implementation of
|
/// - an instance of the session storage backend you wish to use (i.e. an implementation of
|
||||||
/// [`SessionStore]);
|
/// [`SessionStore`]);
|
||||||
/// - a secret key, to sign or encrypt the content of client-side session cookie.
|
/// - a secret key, to sign or encrypt the content of client-side session cookie.
|
||||||
pub fn builder(store: Store, key: Key) -> SessionMiddlewareBuilder<Store> {
|
pub fn builder(store: Store, key: Key) -> SessionMiddlewareBuilder<Store> {
|
||||||
SessionMiddlewareBuilder {
|
SessionMiddlewareBuilder::new(store, config::default_configuration(key))
|
||||||
|
}
|
||||||
|
|
||||||
|
pub(crate) fn from_parts(store: Store, configuration: Configuration) -> Self {
|
||||||
|
Self {
|
||||||
storage_backend: Rc::new(store),
|
storage_backend: Rc::new(store),
|
||||||
configuration: default_configuration(key),
|
configuration: Rc::new(configuration),
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/// A fluent builder to construct a [`SessionMiddleware`] instance with custom configuration
|
|
||||||
/// parameters.
|
|
||||||
#[must_use]
|
|
||||||
pub struct SessionMiddlewareBuilder<Store: SessionStore> {
|
|
||||||
storage_backend: Rc<Store>,
|
|
||||||
configuration: Configuration,
|
|
||||||
}
|
|
||||||
|
|
||||||
impl<Store: SessionStore> SessionMiddlewareBuilder<Store> {
|
|
||||||
/// Set the name of the cookie used to store the session ID.
|
|
||||||
///
|
|
||||||
/// Defaults to `id`.
|
|
||||||
pub fn cookie_name(mut self, name: String) -> Self {
|
|
||||||
self.configuration.cookie.name = name;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set the `Secure` attribute for the cookie used to store the session ID.
|
|
||||||
///
|
|
||||||
/// If the cookie is set as secure, it will only be transmitted when the connection is secure
|
|
||||||
/// (using `https`).
|
|
||||||
///
|
|
||||||
/// Default is `true`.
|
|
||||||
pub fn cookie_secure(mut self, secure: bool) -> Self {
|
|
||||||
self.configuration.cookie.secure = secure;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Determine how long a session should last - check out [`SessionLength`]'s documentation for
|
|
||||||
/// more details on the available options.
|
|
||||||
///
|
|
||||||
/// Default is [`SessionLength::BrowserSession`].
|
|
||||||
pub fn session_length(mut self, session_length: SessionLength) -> Self {
|
|
||||||
match session_length {
|
|
||||||
SessionLength::BrowserSession { state_ttl } => {
|
|
||||||
self.configuration.cookie.max_age = None;
|
|
||||||
self.configuration.session.state_ttl = state_ttl.unwrap_or_else(default_ttl);
|
|
||||||
}
|
|
||||||
SessionLength::Predetermined { max_session_length } => {
|
|
||||||
let ttl = max_session_length.unwrap_or_else(default_ttl);
|
|
||||||
self.configuration.cookie.max_age = Some(ttl);
|
|
||||||
self.configuration.session.state_ttl = ttl;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set the `SameSite` attribute for the cookie used to store the session ID.
|
|
||||||
///
|
|
||||||
/// By default, the attribute is set to `Lax`.
|
|
||||||
pub fn cookie_same_site(mut self, same_site: SameSite) -> Self {
|
|
||||||
self.configuration.cookie.same_site = same_site;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set the `Path` attribute for the cookie used to store the session ID.
|
|
||||||
///
|
|
||||||
/// By default, the attribute is set to `/`.
|
|
||||||
pub fn cookie_path(mut self, path: String) -> Self {
|
|
||||||
self.configuration.cookie.path = path;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set the `Domain` attribute for the cookie used to store the session ID.
|
|
||||||
///
|
|
||||||
/// Use `None` to leave the attribute unspecified. If unspecified, the attribute defaults
|
|
||||||
/// to the same host that set the cookie, excluding subdomains.
|
|
||||||
///
|
|
||||||
/// By default, the attribute is left unspecified.
|
|
||||||
pub fn cookie_domain(mut self, domain: Option<String>) -> Self {
|
|
||||||
self.configuration.cookie.domain = domain;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Choose how the session cookie content should be secured.
|
|
||||||
///
|
|
||||||
/// - [`CookieContentSecurity::Private`] selects encrypted cookie content.
|
|
||||||
/// - [`CookieContentSecurity::Signed`] selects signed cookie content.
|
|
||||||
///
|
|
||||||
/// # Default
|
|
||||||
/// By default, the cookie content is encrypted. Encrypted was chosen instead of signed as
|
|
||||||
/// default because it reduces the chances of sensitive information being exposed in the session
|
|
||||||
/// key by accident, regardless of [`SessionStore`] implementation you chose to use.
|
|
||||||
///
|
|
||||||
/// For example, if you are using cookie-based storage, you definitely want the cookie content
|
|
||||||
/// to be encrypted—the whole session state is embedded in the cookie! If you are using
|
|
||||||
/// Redis-based storage, signed is more than enough - the cookie content is just a unique
|
|
||||||
/// tamper-proof session key.
|
|
||||||
pub fn cookie_content_security(mut self, content_security: CookieContentSecurity) -> Self {
|
|
||||||
self.configuration.cookie.content_security = content_security;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Set the `HttpOnly` attribute for the cookie used to store the session ID.
|
|
||||||
///
|
|
||||||
/// If the cookie is set as `HttpOnly`, it will not be visible to any JavaScript snippets
|
|
||||||
/// running in the browser.
|
|
||||||
///
|
|
||||||
/// Default is `true`.
|
|
||||||
pub fn cookie_http_only(mut self, http_only: bool) -> Self {
|
|
||||||
self.configuration.cookie.http_only = http_only;
|
|
||||||
self
|
|
||||||
}
|
|
||||||
|
|
||||||
/// Finalise the builder and return a [`SessionMiddleware`] instance.
|
|
||||||
#[must_use]
|
|
||||||
pub fn build(self) -> SessionMiddleware<Store> {
|
|
||||||
SessionMiddleware {
|
|
||||||
storage_backend: self.storage_backend,
|
|
||||||
configuration: Rc::new(self.configuration),
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -509,16 +287,39 @@ where
|
|||||||
}
|
}
|
||||||
|
|
||||||
SessionStatus::Unchanged => {
|
SessionStatus::Unchanged => {
|
||||||
// Nothing to do; we avoid the unnecessary call to the storage.
|
if matches!(
|
||||||
|
configuration.ttl_extension_policy,
|
||||||
|
TtlExtensionPolicy::OnEveryRequest
|
||||||
|
) {
|
||||||
|
storage_backend
|
||||||
|
.update_ttl(&session_key, &configuration.session.state_ttl)
|
||||||
|
.await
|
||||||
|
.map_err(e500)?;
|
||||||
|
|
||||||
|
if configuration.cookie.max_age.is_some() {
|
||||||
|
set_session_cookie(
|
||||||
|
res.response_mut().head_mut(),
|
||||||
|
session_key,
|
||||||
|
&configuration.cookie,
|
||||||
|
)
|
||||||
|
.map_err(e500)?;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
Ok(res)
|
Ok(res)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Examines the session cookie attached to the incoming request, if there is one, and tries
|
||||||
|
/// to extract the session key.
|
||||||
|
///
|
||||||
|
/// It returns `None` if there is no session cookie or if the session cookie is considered invalid
|
||||||
|
/// (e.g., when failing a signature check).
|
||||||
fn extract_session_key(req: &ServiceRequest, config: &CookieConfiguration) -> Option<SessionKey> {
|
fn extract_session_key(req: &ServiceRequest, config: &CookieConfiguration) -> Option<SessionKey> {
|
||||||
let cookies = req.cookies().ok()?;
|
let cookies = req.cookies().ok()?;
|
||||||
let session_cookie = cookies
|
let session_cookie = cookies
|
||||||
@ -641,7 +442,9 @@ fn delete_session_cookie(
|
|||||||
) -> Result<(), anyhow::Error> {
|
) -> Result<(), anyhow::Error> {
|
||||||
let removal_cookie = Cookie::build(config.name.clone(), "")
|
let removal_cookie = Cookie::build(config.name.clone(), "")
|
||||||
.path(config.path.clone())
|
.path(config.path.clone())
|
||||||
.http_only(config.http_only);
|
.secure(config.secure)
|
||||||
|
.http_only(config.http_only)
|
||||||
|
.same_site(config.same_site);
|
||||||
|
|
||||||
let mut removal_cookie = if let Some(ref domain) = config.domain {
|
let mut removal_cookie = if let Some(ref domain) = config.domain {
|
||||||
removal_cookie.domain(domain)
|
removal_cookie.domain(domain)
|
||||||
|
@ -1,16 +1,20 @@
|
|||||||
use std::{
|
use std::{
|
||||||
cell::{Ref, RefCell},
|
cell::{Ref, RefCell},
|
||||||
collections::HashMap,
|
collections::HashMap,
|
||||||
|
error::Error as StdError,
|
||||||
mem,
|
mem,
|
||||||
rc::Rc,
|
rc::Rc,
|
||||||
};
|
};
|
||||||
|
|
||||||
use actix_utils::future::{ready, Ready};
|
use actix_utils::future::{ready, Ready};
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
|
body::BoxBody,
|
||||||
dev::{Extensions, Payload, ServiceRequest, ServiceResponse},
|
dev::{Extensions, Payload, ServiceRequest, ServiceResponse},
|
||||||
error::Error,
|
error::Error,
|
||||||
FromRequest, HttpMessage, HttpRequest,
|
FromRequest, HttpMessage, HttpRequest, HttpResponse, ResponseError,
|
||||||
};
|
};
|
||||||
|
use anyhow::Context;
|
||||||
|
use derive_more::derive::{Display, From};
|
||||||
use serde::{de::DeserializeOwned, Serialize};
|
use serde::{de::DeserializeOwned, Serialize};
|
||||||
|
|
||||||
/// The primary interface to access and modify session state.
|
/// The primary interface to access and modify session state.
|
||||||
@ -29,6 +33,9 @@ use serde::{de::DeserializeOwned, Serialize};
|
|||||||
/// session.insert("counter", 1)?;
|
/// session.insert("counter", 1)?;
|
||||||
/// }
|
/// }
|
||||||
///
|
///
|
||||||
|
/// // or use the shorthand
|
||||||
|
/// session.update_or("counter", 1, |count: i32| count + 1);
|
||||||
|
///
|
||||||
/// Ok("Welcome!")
|
/// Ok("Welcome!")
|
||||||
/// }
|
/// }
|
||||||
/// # actix_web::web::to(index);
|
/// # actix_web::web::to(index);
|
||||||
@ -38,10 +45,11 @@ use serde::{de::DeserializeOwned, Serialize};
|
|||||||
/// [`SessionExt`].
|
/// [`SessionExt`].
|
||||||
///
|
///
|
||||||
/// [`SessionExt`]: crate::SessionExt
|
/// [`SessionExt`]: crate::SessionExt
|
||||||
|
#[derive(Clone)]
|
||||||
pub struct Session(Rc<RefCell<SessionInner>>);
|
pub struct Session(Rc<RefCell<SessionInner>>);
|
||||||
|
|
||||||
/// Status of a [`Session`].
|
/// Status of a [`Session`].
|
||||||
#[derive(Debug, Clone, PartialEq, Eq)]
|
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||||
pub enum SessionStatus {
|
pub enum SessionStatus {
|
||||||
/// Session state has been updated - the changes will have to be persisted to the backend.
|
/// Session state has been updated - the changes will have to be persisted to the backend.
|
||||||
Changed,
|
Changed,
|
||||||
@ -59,15 +67,10 @@ pub enum SessionStatus {
|
|||||||
Renewed,
|
Renewed,
|
||||||
|
|
||||||
/// The session state has not been modified since its creation/retrieval.
|
/// The session state has not been modified since its creation/retrieval.
|
||||||
|
#[default]
|
||||||
Unchanged,
|
Unchanged,
|
||||||
}
|
}
|
||||||
|
|
||||||
impl Default for SessionStatus {
|
|
||||||
fn default() -> SessionStatus {
|
|
||||||
SessionStatus::Unchanged
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
struct SessionInner {
|
struct SessionInner {
|
||||||
state: HashMap<String, String>,
|
state: HashMap<String, String>,
|
||||||
@ -78,14 +81,30 @@ impl Session {
|
|||||||
/// Get a `value` from the session.
|
/// Get a `value` from the session.
|
||||||
///
|
///
|
||||||
/// It returns an error if it fails to deserialize as `T` the JSON value associated with `key`.
|
/// It returns an error if it fails to deserialize as `T` the JSON value associated with `key`.
|
||||||
pub fn get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>, serde_json::Error> {
|
pub fn get<T: DeserializeOwned>(&self, key: &str) -> Result<Option<T>, SessionGetError> {
|
||||||
if let Some(val_str) = self.0.borrow().state.get(key) {
|
if let Some(val_str) = self.0.borrow().state.get(key) {
|
||||||
Ok(Some(serde_json::from_str(val_str)?))
|
Ok(Some(
|
||||||
|
serde_json::from_str(val_str)
|
||||||
|
.with_context(|| {
|
||||||
|
format!(
|
||||||
|
"Failed to deserialize the JSON-encoded session data attached to key \
|
||||||
|
`{}` as a `{}` type",
|
||||||
|
key,
|
||||||
|
std::any::type_name::<T>()
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.map_err(SessionGetError)?,
|
||||||
|
))
|
||||||
} else {
|
} else {
|
||||||
Ok(None)
|
Ok(None)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Returns `true` if the session contains a value for the specified `key`.
|
||||||
|
pub fn contains_key(&self, key: &str) -> bool {
|
||||||
|
self.0.borrow().state.contains_key(key)
|
||||||
|
}
|
||||||
|
|
||||||
/// Get all raw key-value data from the session.
|
/// Get all raw key-value data from the session.
|
||||||
///
|
///
|
||||||
/// Note that values are JSON encoded.
|
/// Note that values are JSON encoded.
|
||||||
@ -103,23 +122,115 @@ impl Session {
|
|||||||
/// Any serializable value can be used and will be encoded as JSON in session data, hence why
|
/// Any serializable value can be used and will be encoded as JSON in session data, hence why
|
||||||
/// only a reference to the value is taken.
|
/// only a reference to the value is taken.
|
||||||
///
|
///
|
||||||
/// It returns an error if it fails to serialize `value` to JSON.
|
/// # Errors
|
||||||
pub fn insert(
|
///
|
||||||
|
/// Returns an error if JSON serialization of `value` fails.
|
||||||
|
pub fn insert<T: Serialize>(
|
||||||
&self,
|
&self,
|
||||||
key: impl Into<String>,
|
key: impl Into<String>,
|
||||||
value: impl Serialize,
|
value: T,
|
||||||
) -> Result<(), serde_json::Error> {
|
) -> Result<(), SessionInsertError> {
|
||||||
let mut inner = self.0.borrow_mut();
|
let mut inner = self.0.borrow_mut();
|
||||||
|
|
||||||
if inner.status != SessionStatus::Purged {
|
if inner.status != SessionStatus::Purged {
|
||||||
|
if inner.status != SessionStatus::Renewed {
|
||||||
inner.status = SessionStatus::Changed;
|
inner.status = SessionStatus::Changed;
|
||||||
let val = serde_json::to_string(&value)?;
|
}
|
||||||
inner.state.insert(key.into(), val);
|
|
||||||
|
let key = key.into();
|
||||||
|
let val = serde_json::to_string(&value)
|
||||||
|
.with_context(|| {
|
||||||
|
format!(
|
||||||
|
"Failed to serialize the provided `{}` type instance as JSON in order to \
|
||||||
|
attach as session data to the `{key}` key",
|
||||||
|
std::any::type_name::<T>(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.map_err(SessionInsertError)?;
|
||||||
|
|
||||||
|
inner.state.insert(key, val);
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Updates a key-value pair into the session.
|
||||||
|
///
|
||||||
|
/// If the key exists then update it to the new value and place it back in. If the key does not
|
||||||
|
/// exist it will not be updated.
|
||||||
|
///
|
||||||
|
/// Any serializable value can be used and will be encoded as JSON in the session data, hence
|
||||||
|
/// why only a reference to the value is taken.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Returns an error if JSON serialization of the value fails.
|
||||||
|
pub fn update<T: Serialize + DeserializeOwned, F>(
|
||||||
|
&self,
|
||||||
|
key: impl Into<String>,
|
||||||
|
updater: F,
|
||||||
|
) -> Result<(), SessionUpdateError>
|
||||||
|
where
|
||||||
|
F: FnOnce(T) -> T,
|
||||||
|
{
|
||||||
|
let mut inner = self.0.borrow_mut();
|
||||||
|
let key_str = key.into();
|
||||||
|
|
||||||
|
if let Some(val_str) = inner.state.get(&key_str) {
|
||||||
|
let value = serde_json::from_str(val_str)
|
||||||
|
.with_context(|| {
|
||||||
|
format!(
|
||||||
|
"Failed to deserialize the JSON-encoded session data attached to key \
|
||||||
|
`{key_str}` as a `{}` type",
|
||||||
|
std::any::type_name::<T>()
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.map_err(SessionUpdateError)?;
|
||||||
|
|
||||||
|
let val = serde_json::to_string(&updater(value))
|
||||||
|
.with_context(|| {
|
||||||
|
format!(
|
||||||
|
"Failed to serialize the provided `{}` type instance as JSON in order to \
|
||||||
|
attach as session data to the `{key_str}` key",
|
||||||
|
std::any::type_name::<T>(),
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.map_err(SessionUpdateError)?;
|
||||||
|
|
||||||
|
inner.state.insert(key_str, val);
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Updates a key-value pair into the session, or inserts a default value.
|
||||||
|
///
|
||||||
|
/// If the key exists then update it to the new value and place it back in. If the key does not
|
||||||
|
/// exist the default value will be inserted instead.
|
||||||
|
///
|
||||||
|
/// Any serializable value can be used and will be encoded as JSON in session data, hence why
|
||||||
|
/// only a reference to the value is taken.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Returns error if JSON serialization of a value fails.
|
||||||
|
pub fn update_or<T: Serialize + DeserializeOwned, F>(
|
||||||
|
&self,
|
||||||
|
key: &str,
|
||||||
|
default_value: T,
|
||||||
|
updater: F,
|
||||||
|
) -> Result<(), SessionUpdateError>
|
||||||
|
where
|
||||||
|
F: FnOnce(T) -> T,
|
||||||
|
{
|
||||||
|
if self.contains_key(key) {
|
||||||
|
self.update(key, updater)
|
||||||
|
} else {
|
||||||
|
self.insert(key, default_value)
|
||||||
|
.map_err(|err| SessionUpdateError(err.into()))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/// Remove value from the session.
|
/// Remove value from the session.
|
||||||
///
|
///
|
||||||
/// If present, the JSON encoded value is returned.
|
/// If present, the JSON encoded value is returned.
|
||||||
@ -127,7 +238,9 @@ impl Session {
|
|||||||
let mut inner = self.0.borrow_mut();
|
let mut inner = self.0.borrow_mut();
|
||||||
|
|
||||||
if inner.status != SessionStatus::Purged {
|
if inner.status != SessionStatus::Purged {
|
||||||
|
if inner.status != SessionStatus::Renewed {
|
||||||
inner.status = SessionStatus::Changed;
|
inner.status = SessionStatus::Changed;
|
||||||
|
}
|
||||||
return inner.state.remove(key);
|
return inner.state.remove(key);
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -136,7 +249,7 @@ impl Session {
|
|||||||
|
|
||||||
/// Remove value from the session and deserialize.
|
/// Remove value from the session and deserialize.
|
||||||
///
|
///
|
||||||
/// Returns None if key was not present in session. Returns `T` if deserialization succeeds,
|
/// Returns `None` if key was not present in session. Returns `T` if deserialization succeeds,
|
||||||
/// otherwise returns un-deserialized JSON string.
|
/// otherwise returns un-deserialized JSON string.
|
||||||
pub fn remove_as<T: DeserializeOwned>(&self, key: &str) -> Option<Result<T, String>> {
|
pub fn remove_as<T: DeserializeOwned>(&self, key: &str) -> Option<Result<T, String>> {
|
||||||
self.remove(key)
|
self.remove(key)
|
||||||
@ -144,7 +257,7 @@ impl Session {
|
|||||||
Ok(val) => Ok(val),
|
Ok(val) => Ok(val),
|
||||||
Err(_err) => {
|
Err(_err) => {
|
||||||
tracing::debug!(
|
tracing::debug!(
|
||||||
"removed value (key: {}) could not be deserialized as {}",
|
"Removed value (key: {}) could not be deserialized as {}",
|
||||||
key,
|
key,
|
||||||
std::any::type_name::<T>()
|
std::any::type_name::<T>()
|
||||||
);
|
);
|
||||||
@ -159,7 +272,9 @@ impl Session {
|
|||||||
let mut inner = self.0.borrow_mut();
|
let mut inner = self.0.borrow_mut();
|
||||||
|
|
||||||
if inner.status != SessionStatus::Purged {
|
if inner.status != SessionStatus::Purged {
|
||||||
|
if inner.status != SessionStatus::Renewed {
|
||||||
inner.status = SessionStatus::Changed;
|
inner.status = SessionStatus::Changed;
|
||||||
|
}
|
||||||
inner.state.clear()
|
inner.state.clear()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -184,20 +299,22 @@ impl Session {
|
|||||||
///
|
///
|
||||||
/// Values that match keys already existing on the session will be overwritten. Values should
|
/// Values that match keys already existing on the session will be overwritten. Values should
|
||||||
/// already be JSON serialized.
|
/// already be JSON serialized.
|
||||||
|
#[allow(clippy::needless_pass_by_ref_mut)]
|
||||||
pub(crate) fn set_session(
|
pub(crate) fn set_session(
|
||||||
req: &mut ServiceRequest,
|
req: &mut ServiceRequest,
|
||||||
data: impl IntoIterator<Item = (String, String)>,
|
data: impl IntoIterator<Item = (String, String)>,
|
||||||
) {
|
) {
|
||||||
let session = Session::get_session(&mut *req.extensions_mut());
|
let session = Session::get_session(&mut req.extensions_mut());
|
||||||
let mut inner = session.0.borrow_mut();
|
let mut inner = session.0.borrow_mut();
|
||||||
inner.state.extend(data);
|
inner.state.extend(data);
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Returns session status and iterator of key-value pairs of changes.
|
/// Returns session status and iterator of key-value pairs of changes.
|
||||||
///
|
///
|
||||||
/// This is a destructive operation - the session state is removed from the request extensions typemap,
|
/// This is a destructive operation - the session state is removed from the request extensions
|
||||||
/// leaving behind a new empty map. It should only be used when the session is being finalised (i.e.
|
/// typemap, leaving behind a new empty map. It should only be used when the session is being
|
||||||
/// in `SessionMiddleware`).
|
/// finalised (i.e. in `SessionMiddleware`).
|
||||||
|
#[allow(clippy::needless_pass_by_ref_mut)]
|
||||||
pub(crate) fn get_changes<B>(
|
pub(crate) fn get_changes<B>(
|
||||||
res: &mut ServiceResponse<B>,
|
res: &mut ServiceResponse<B>,
|
||||||
) -> (SessionStatus, HashMap<String, String>) {
|
) -> (SessionStatus, HashMap<String, String>) {
|
||||||
@ -251,6 +368,57 @@ impl FromRequest for Session {
|
|||||||
|
|
||||||
#[inline]
|
#[inline]
|
||||||
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future {
|
||||||
ready(Ok(Session::get_session(&mut *req.extensions_mut())))
|
ready(Ok(Session::get_session(&mut req.extensions_mut())))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Error returned by [`Session::get`].
|
||||||
|
#[derive(Debug, Display, From)]
|
||||||
|
#[display("{_0}")]
|
||||||
|
pub struct SessionGetError(anyhow::Error);
|
||||||
|
|
||||||
|
impl StdError for SessionGetError {
|
||||||
|
fn source(&self) -> Option<&(dyn StdError + 'static)> {
|
||||||
|
Some(self.0.as_ref())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ResponseError for SessionGetError {
|
||||||
|
fn error_response(&self) -> HttpResponse<BoxBody> {
|
||||||
|
HttpResponse::new(self.status_code())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Error returned by [`Session::insert`].
|
||||||
|
#[derive(Debug, Display, From)]
|
||||||
|
#[display("{_0}")]
|
||||||
|
pub struct SessionInsertError(anyhow::Error);
|
||||||
|
|
||||||
|
impl StdError for SessionInsertError {
|
||||||
|
fn source(&self) -> Option<&(dyn StdError + 'static)> {
|
||||||
|
Some(self.0.as_ref())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ResponseError for SessionInsertError {
|
||||||
|
fn error_response(&self) -> HttpResponse<BoxBody> {
|
||||||
|
HttpResponse::new(self.status_code())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Error returned by [`Session::update`].
|
||||||
|
#[derive(Debug, Display, From)]
|
||||||
|
#[display("{_0}")]
|
||||||
|
pub struct SessionUpdateError(anyhow::Error);
|
||||||
|
|
||||||
|
impl StdError for SessionUpdateError {
|
||||||
|
fn source(&self) -> Option<&(dyn StdError + 'static)> {
|
||||||
|
Some(self.0.as_ref())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl ResponseError for SessionUpdateError {
|
||||||
|
fn error_response(&self) -> HttpResponse<BoxBody> {
|
||||||
|
HttpResponse::new(self.status_code())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -15,13 +15,13 @@ pub trait SessionExt {
|
|||||||
|
|
||||||
impl SessionExt for HttpRequest {
|
impl SessionExt for HttpRequest {
|
||||||
fn get_session(&self) -> Session {
|
fn get_session(&self) -> Session {
|
||||||
Session::get_session(&mut *self.extensions_mut())
|
Session::get_session(&mut self.extensions_mut())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl SessionExt for ServiceRequest {
|
impl SessionExt for ServiceRequest {
|
||||||
fn get_session(&self) -> Session {
|
fn get_session(&self) -> Session {
|
||||||
Session::get_session(&mut *self.extensions_mut())
|
Session::get_session(&mut self.extensions_mut())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -31,8 +31,8 @@ impl SessionExt for ServiceResponse {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl<'a> SessionExt for GuardContext<'a> {
|
impl SessionExt for GuardContext<'_> {
|
||||||
fn get_session(&self) -> Session {
|
fn get_session(&self) -> Session {
|
||||||
Session::get_session(&mut *self.req_data_mut())
|
Session::get_session(&mut self.req_data_mut())
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,5 @@
|
|||||||
use std::convert::TryInto;
|
use actix_web::cookie::time::Duration;
|
||||||
|
use anyhow::Error;
|
||||||
use time::Duration;
|
|
||||||
|
|
||||||
use super::SessionKey;
|
use super::SessionKey;
|
||||||
use crate::storage::{
|
use crate::storage::{
|
||||||
@ -34,9 +33,9 @@ use crate::storage::{
|
|||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// # Limitations
|
/// # Limitations
|
||||||
/// Cookies are subject to size limits - we require session keys to be shorter than 4096 bytes. This
|
/// Cookies are subject to size limits so we require session keys to be shorter than 4096 bytes.
|
||||||
/// translates into a limit on the maximum size of the session state when using cookies as storage
|
/// This translates into a limit on the maximum size of the session state when using cookies as
|
||||||
/// backend.
|
/// storage backend.
|
||||||
///
|
///
|
||||||
/// The session cookie can always be inspected by end users via the developer tools exposed by their
|
/// The session cookie can always be inspected by end users via the developer tools exposed by their
|
||||||
/// browsers. We strongly recommend setting the policy to [`CookieContentSecurity::Private`] when
|
/// browsers. We strongly recommend setting the policy to [`CookieContentSecurity::Private`] when
|
||||||
@ -45,13 +44,11 @@ use crate::storage::{
|
|||||||
/// There is no way to invalidate a session before its natural expiry when using cookies as the
|
/// There is no way to invalidate a session before its natural expiry when using cookies as the
|
||||||
/// storage backend.
|
/// storage backend.
|
||||||
///
|
///
|
||||||
/// [`CookieContentSecurity::Private`]: crate::CookieContentSecurity::Private
|
/// [`CookieContentSecurity::Private`]: crate::config::CookieContentSecurity::Private
|
||||||
#[cfg_attr(docsrs, doc(cfg(feature = "cookie-session")))]
|
|
||||||
#[derive(Default)]
|
#[derive(Default)]
|
||||||
#[non_exhaustive]
|
#[non_exhaustive]
|
||||||
pub struct CookieSessionStore;
|
pub struct CookieSessionStore;
|
||||||
|
|
||||||
#[async_trait::async_trait(?Send)]
|
|
||||||
impl SessionStore for CookieSessionStore {
|
impl SessionStore for CookieSessionStore {
|
||||||
async fn load(&self, session_key: &SessionKey) -> Result<Option<SessionState>, LoadError> {
|
async fn load(&self, session_key: &SessionKey) -> Result<Option<SessionState>, LoadError> {
|
||||||
serde_json::from_str(session_key.as_ref())
|
serde_json::from_str(session_key.as_ref())
|
||||||
@ -69,10 +66,10 @@ impl SessionStore for CookieSessionStore {
|
|||||||
.map_err(anyhow::Error::new)
|
.map_err(anyhow::Error::new)
|
||||||
.map_err(SaveError::Serialization)?;
|
.map_err(SaveError::Serialization)?;
|
||||||
|
|
||||||
Ok(session_key
|
session_key
|
||||||
.try_into()
|
.try_into()
|
||||||
.map_err(Into::into)
|
.map_err(Into::into)
|
||||||
.map_err(SaveError::Other)?)
|
.map_err(SaveError::Other)
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn update(
|
async fn update(
|
||||||
@ -89,6 +86,10 @@ impl SessionStore for CookieSessionStore {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn update_ttl(&self, _session_key: &SessionKey, _ttl: &Duration) -> Result<(), Error> {
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
async fn delete(&self, _session_key: &SessionKey) -> Result<(), anyhow::Error> {
|
async fn delete(&self, _session_key: &SessionKey) -> Result<(), anyhow::Error> {
|
||||||
Ok(())
|
Ok(())
|
||||||
}
|
}
|
||||||
|
@ -1,7 +1,7 @@
|
|||||||
use std::collections::HashMap;
|
use std::{collections::HashMap, future::Future};
|
||||||
|
|
||||||
use derive_more::Display;
|
use actix_web::cookie::time::Duration;
|
||||||
use time::Duration;
|
use derive_more::derive::Display;
|
||||||
|
|
||||||
use super::SessionKey;
|
use super::SessionKey;
|
||||||
|
|
||||||
@ -10,34 +10,39 @@ pub(crate) type SessionState = HashMap<String, String>;
|
|||||||
/// The interface to retrieve and save the current session data from/to the chosen storage backend.
|
/// The interface to retrieve and save the current session data from/to the chosen storage backend.
|
||||||
///
|
///
|
||||||
/// You can provide your own custom session store backend by implementing this trait.
|
/// You can provide your own custom session store backend by implementing this trait.
|
||||||
///
|
|
||||||
/// [`async-trait`](https://docs.rs/async-trait) is used for this trait's definition. Therefore, it
|
|
||||||
/// is required for implementations, too. In particular, we use the send-optional variant:
|
|
||||||
/// `#[async_trait(?Send)]`.
|
|
||||||
#[async_trait::async_trait(?Send)]
|
|
||||||
pub trait SessionStore {
|
pub trait SessionStore {
|
||||||
/// Loads the session state associated to a session key.
|
/// Loads the session state associated to a session key.
|
||||||
async fn load(&self, session_key: &SessionKey) -> Result<Option<SessionState>, LoadError>;
|
fn load(
|
||||||
|
&self,
|
||||||
|
session_key: &SessionKey,
|
||||||
|
) -> impl Future<Output = Result<Option<SessionState>, LoadError>>;
|
||||||
|
|
||||||
/// Persist the session state for a newly created session.
|
/// Persist the session state for a newly created session.
|
||||||
///
|
///
|
||||||
/// Returns the corresponding session key.
|
/// Returns the corresponding session key.
|
||||||
async fn save(
|
fn save(
|
||||||
&self,
|
&self,
|
||||||
session_state: SessionState,
|
session_state: SessionState,
|
||||||
ttl: &Duration,
|
ttl: &Duration,
|
||||||
) -> Result<SessionKey, SaveError>;
|
) -> impl Future<Output = Result<SessionKey, SaveError>>;
|
||||||
|
|
||||||
/// Updates the session state associated to a pre-existing session key.
|
/// Updates the session state associated to a pre-existing session key.
|
||||||
async fn update(
|
fn update(
|
||||||
&self,
|
&self,
|
||||||
session_key: SessionKey,
|
session_key: SessionKey,
|
||||||
session_state: SessionState,
|
session_state: SessionState,
|
||||||
ttl: &Duration,
|
ttl: &Duration,
|
||||||
) -> Result<SessionKey, UpdateError>;
|
) -> impl Future<Output = Result<SessionKey, UpdateError>>;
|
||||||
|
|
||||||
|
/// Updates the TTL of the session state associated to a pre-existing session key.
|
||||||
|
fn update_ttl(
|
||||||
|
&self,
|
||||||
|
session_key: &SessionKey,
|
||||||
|
ttl: &Duration,
|
||||||
|
) -> impl Future<Output = Result<(), anyhow::Error>>;
|
||||||
|
|
||||||
/// Deletes a session from the store.
|
/// Deletes a session from the store.
|
||||||
async fn delete(&self, session_key: &SessionKey) -> Result<(), anyhow::Error>;
|
fn delete(&self, session_key: &SessionKey) -> impl Future<Output = Result<(), anyhow::Error>>;
|
||||||
}
|
}
|
||||||
|
|
||||||
// We cannot derive the `Error` implementation using `derive_more` for our custom errors:
|
// We cannot derive the `Error` implementation using `derive_more` for our custom errors:
|
||||||
@ -48,11 +53,11 @@ pub trait SessionStore {
|
|||||||
#[derive(Debug, Display)]
|
#[derive(Debug, Display)]
|
||||||
pub enum LoadError {
|
pub enum LoadError {
|
||||||
/// Failed to deserialize session state.
|
/// Failed to deserialize session state.
|
||||||
#[display(fmt = "Failed to deserialize session state")]
|
#[display("Failed to deserialize session state")]
|
||||||
Deserialization(anyhow::Error),
|
Deserialization(anyhow::Error),
|
||||||
|
|
||||||
/// Something went wrong when retrieving the session state.
|
/// Something went wrong when retrieving the session state.
|
||||||
#[display(fmt = "Something went wrong when retrieving the session state")]
|
#[display("Something went wrong when retrieving the session state")]
|
||||||
Other(anyhow::Error),
|
Other(anyhow::Error),
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -69,11 +74,11 @@ impl std::error::Error for LoadError {
|
|||||||
#[derive(Debug, Display)]
|
#[derive(Debug, Display)]
|
||||||
pub enum SaveError {
|
pub enum SaveError {
|
||||||
/// Failed to serialize session state.
|
/// Failed to serialize session state.
|
||||||
#[display(fmt = "Failed to serialize session state")]
|
#[display("Failed to serialize session state")]
|
||||||
Serialization(anyhow::Error),
|
Serialization(anyhow::Error),
|
||||||
|
|
||||||
/// Something went wrong when persisting the session state.
|
/// Something went wrong when persisting the session state.
|
||||||
#[display(fmt = "Something went wrong when persisting the session state")]
|
#[display("Something went wrong when persisting the session state")]
|
||||||
Other(anyhow::Error),
|
Other(anyhow::Error),
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -90,11 +95,11 @@ impl std::error::Error for SaveError {
|
|||||||
/// Possible failures modes for [`SessionStore::update`].
|
/// Possible failures modes for [`SessionStore::update`].
|
||||||
pub enum UpdateError {
|
pub enum UpdateError {
|
||||||
/// Failed to serialize session state.
|
/// Failed to serialize session state.
|
||||||
#[display(fmt = "Failed to serialize session state")]
|
#[display("Failed to serialize session state")]
|
||||||
Serialization(anyhow::Error),
|
Serialization(anyhow::Error),
|
||||||
|
|
||||||
/// Something went wrong when updating the session state.
|
/// Something went wrong when updating the session state.
|
||||||
#[display(fmt = "Something went wrong when updating the session state.")]
|
#[display("Something went wrong when updating the session state.")]
|
||||||
Other(anyhow::Error),
|
Other(anyhow::Error),
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -1,28 +1,19 @@
|
|||||||
//! Pluggable storage backends for session state.
|
//! Pluggable storage backends for session state.
|
||||||
|
|
||||||
mod interface;
|
|
||||||
mod session_key;
|
|
||||||
|
|
||||||
pub use self::interface::{LoadError, SaveError, SessionStore, UpdateError};
|
|
||||||
pub use self::session_key::SessionKey;
|
|
||||||
|
|
||||||
#[cfg(feature = "cookie-session")]
|
#[cfg(feature = "cookie-session")]
|
||||||
mod cookie;
|
mod cookie;
|
||||||
|
mod interface;
|
||||||
#[cfg(feature = "redis-actor-session")]
|
#[cfg(feature = "redis-session")]
|
||||||
mod redis_actor;
|
|
||||||
|
|
||||||
#[cfg(feature = "redis-rs-session")]
|
|
||||||
mod redis_rs;
|
mod redis_rs;
|
||||||
|
mod session_key;
|
||||||
#[cfg(any(feature = "redis-actor-session", feature = "redis-rs-session"))]
|
|
||||||
mod utils;
|
mod utils;
|
||||||
|
|
||||||
#[cfg(feature = "cookie-session")]
|
#[cfg(feature = "cookie-session")]
|
||||||
pub use cookie::CookieSessionStore;
|
pub use self::cookie::CookieSessionStore;
|
||||||
|
#[cfg(feature = "redis-session")]
|
||||||
#[cfg(feature = "redis-actor-session")]
|
pub use self::redis_rs::{RedisSessionStore, RedisSessionStoreBuilder};
|
||||||
pub use redis_actor::{RedisActorSessionStore, RedisActorSessionStoreBuilder};
|
pub use self::{
|
||||||
|
interface::{LoadError, SaveError, SessionStore, UpdateError},
|
||||||
#[cfg(feature = "redis-rs-session")]
|
session_key::SessionKey,
|
||||||
pub use redis_rs::{RedisSessionStore, RedisSessionStoreBuilder};
|
utils::generate_session_key,
|
||||||
|
};
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
use actix::Addr;
|
use actix::Addr;
|
||||||
use actix_redis::{resp_array, Command, RedisActor, RespValue};
|
use actix_redis::{resp_array, Command, RedisActor, RespValue};
|
||||||
use time::{self, Duration};
|
use actix_web::cookie::time::Duration;
|
||||||
|
use anyhow::Error;
|
||||||
|
|
||||||
use super::SessionKey;
|
use super::SessionKey;
|
||||||
use crate::storage::{
|
use crate::storage::{
|
||||||
@ -52,7 +53,6 @@ use crate::storage::{
|
|||||||
/// Redis. Use [`RedisSessionStore`] if you need TLS support.
|
/// Redis. Use [`RedisSessionStore`] if you need TLS support.
|
||||||
///
|
///
|
||||||
/// [`RedisSessionStore`]: crate::storage::RedisSessionStore
|
/// [`RedisSessionStore`]: crate::storage::RedisSessionStore
|
||||||
#[cfg_attr(docsrs, doc(cfg(feature = "redis-actor-session")))]
|
|
||||||
pub struct RedisActorSessionStore {
|
pub struct RedisActorSessionStore {
|
||||||
configuration: CacheConfiguration,
|
configuration: CacheConfiguration,
|
||||||
addr: Addr<RedisActor>,
|
addr: Addr<RedisActor>,
|
||||||
@ -92,7 +92,6 @@ impl Default for CacheConfiguration {
|
|||||||
|
|
||||||
/// A fluent builder to construct a [`RedisActorSessionStore`] instance with custom configuration
|
/// A fluent builder to construct a [`RedisActorSessionStore`] instance with custom configuration
|
||||||
/// parameters.
|
/// parameters.
|
||||||
#[cfg_attr(docsrs, doc(cfg(feature = "redis-actor-session")))]
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub struct RedisActorSessionStoreBuilder {
|
pub struct RedisActorSessionStoreBuilder {
|
||||||
connection_string: String,
|
connection_string: String,
|
||||||
@ -119,7 +118,6 @@ impl RedisActorSessionStoreBuilder {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait::async_trait(?Send)]
|
|
||||||
impl SessionStore for RedisActorSessionStore {
|
impl SessionStore for RedisActorSessionStore {
|
||||||
async fn load(&self, session_key: &SessionKey) -> Result<Option<SessionState>, LoadError> {
|
async fn load(&self, session_key: &SessionKey) -> Result<Option<SessionState>, LoadError> {
|
||||||
let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
|
let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
|
||||||
@ -238,6 +236,24 @@ impl SessionStore for RedisActorSessionStore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async fn update_ttl(&self, session_key: &SessionKey, ttl: &Duration) -> Result<(), Error> {
|
||||||
|
let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
|
||||||
|
|
||||||
|
let cmd = Command(resp_array![
|
||||||
|
"EXPIRE",
|
||||||
|
cache_key,
|
||||||
|
ttl.whole_seconds().to_string()
|
||||||
|
]);
|
||||||
|
|
||||||
|
match self.addr.send(cmd).await? {
|
||||||
|
Ok(RespValue::Integer(_)) => Ok(()),
|
||||||
|
val => Err(anyhow::anyhow!(
|
||||||
|
"Failed to update the session state TTL: {:?}",
|
||||||
|
val
|
||||||
|
)),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async fn delete(&self, session_key: &SessionKey) -> Result<(), anyhow::Error> {
|
async fn delete(&self, session_key: &SessionKey) -> Result<(), anyhow::Error> {
|
||||||
let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
|
let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
|
||||||
|
|
||||||
@ -258,7 +274,7 @@ impl SessionStore for RedisActorSessionStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod tests {
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
@ -286,7 +302,7 @@ mod test {
|
|||||||
let session_key = generate_session_key();
|
let session_key = generate_session_key();
|
||||||
let initial_session_key = session_key.as_ref().to_owned();
|
let initial_session_key = session_key.as_ref().to_owned();
|
||||||
let updated_session_key = store
|
let updated_session_key = store
|
||||||
.update(session_key, HashMap::new(), &time::Duration::seconds(1))
|
.update(session_key, HashMap::new(), &Duration::seconds(1))
|
||||||
.await
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
assert_ne!(initial_session_key, updated_session_key.as_ref());
|
assert_ne!(initial_session_key, updated_session_key.as_ref());
|
||||||
|
@ -1,7 +1,8 @@
|
|||||||
use std::sync::Arc;
|
use std::sync::Arc;
|
||||||
|
|
||||||
use redis::{aio::ConnectionManager, Cmd, FromRedisValue, RedisResult, Value};
|
use actix_web::cookie::time::Duration;
|
||||||
use time::{self, Duration};
|
use anyhow::Error;
|
||||||
|
use redis::{aio::ConnectionManager, AsyncCommands, Client, Cmd, FromRedisValue, Value};
|
||||||
|
|
||||||
use super::SessionKey;
|
use super::SessionKey;
|
||||||
use crate::storage::{
|
use crate::storage::{
|
||||||
@ -28,6 +29,7 @@ use crate::storage::{
|
|||||||
/// let secret_key = get_secret_key();
|
/// let secret_key = get_secret_key();
|
||||||
/// let redis_connection_string = "redis://127.0.0.1:6379";
|
/// let redis_connection_string = "redis://127.0.0.1:6379";
|
||||||
/// let store = RedisSessionStore::new(redis_connection_string).await.unwrap();
|
/// let store = RedisSessionStore::new(redis_connection_string).await.unwrap();
|
||||||
|
///
|
||||||
/// HttpServer::new(move ||
|
/// HttpServer::new(move ||
|
||||||
/// App::new()
|
/// App::new()
|
||||||
/// .wrap(SessionMiddleware::new(
|
/// .wrap(SessionMiddleware::new(
|
||||||
@ -42,7 +44,7 @@ use crate::storage::{
|
|||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// # TLS support
|
/// # TLS support
|
||||||
/// Add the `redis-rs-tls-session` feature flag to enable TLS support. You can then establish a TLS
|
/// Add the `redis-session-native-tls` or `redis-session-rustls` feature flag to enable TLS support. You can then establish a TLS
|
||||||
/// connection to Redis using the `rediss://` URL scheme:
|
/// connection to Redis using the `rediss://` URL scheme:
|
||||||
///
|
///
|
||||||
/// ```no_run
|
/// ```no_run
|
||||||
@ -54,15 +56,38 @@ use crate::storage::{
|
|||||||
/// # })
|
/// # })
|
||||||
/// ```
|
/// ```
|
||||||
///
|
///
|
||||||
/// # Implementation notes
|
/// # Pooled Redis Connections
|
||||||
/// `RedisSessionStore` leverages [`redis-rs`] as Redis client.
|
|
||||||
///
|
///
|
||||||
/// [`redis-rs`]: https://github.com/mitsuhiko/redis-rs
|
/// When the `redis-pool` crate feature is enabled, a pre-existing pool from [`deadpool_redis`] can
|
||||||
#[cfg_attr(docsrs, doc(cfg(feature = "redis-rs-session")))]
|
/// be provided.
|
||||||
|
///
|
||||||
|
/// ```no_run
|
||||||
|
/// use actix_session::storage::RedisSessionStore;
|
||||||
|
/// use deadpool_redis::{Config, Runtime};
|
||||||
|
///
|
||||||
|
/// let redis_cfg = Config::from_url("redis://127.0.0.1:6379");
|
||||||
|
/// let redis_pool = redis_cfg.create_pool(Some(Runtime::Tokio1)).unwrap();
|
||||||
|
///
|
||||||
|
/// let store = RedisSessionStore::new_pooled(redis_pool);
|
||||||
|
/// ```
|
||||||
|
///
|
||||||
|
/// # Implementation notes
|
||||||
|
///
|
||||||
|
/// `RedisSessionStore` leverages the [`redis`] crate as the underlying Redis client.
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
pub struct RedisSessionStore {
|
pub struct RedisSessionStore {
|
||||||
configuration: CacheConfiguration,
|
configuration: CacheConfiguration,
|
||||||
client: ConnectionManager,
|
client: RedisSessionConn,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Clone)]
|
||||||
|
enum RedisSessionConn {
|
||||||
|
/// Single connection.
|
||||||
|
Single(ConnectionManager),
|
||||||
|
|
||||||
|
/// Connection pool.
|
||||||
|
#[cfg(feature = "redis-pool")]
|
||||||
|
Pool(deadpool_redis::Pool),
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Clone)]
|
#[derive(Clone)]
|
||||||
@ -79,35 +104,77 @@ impl Default for CacheConfiguration {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl RedisSessionStore {
|
impl RedisSessionStore {
|
||||||
/// A fluent API to configure [`RedisSessionStore`].
|
/// Returns a fluent API builder to configure [`RedisSessionStore`].
|
||||||
/// It takes as input the only required input to create a new instance of [`RedisSessionStore`] - a
|
///
|
||||||
/// connection string for Redis.
|
/// It takes as input the only required input to create a new instance of [`RedisSessionStore`]
|
||||||
pub fn builder<S: Into<String>>(connection_string: S) -> RedisSessionStoreBuilder {
|
/// - a connection string for Redis.
|
||||||
|
pub fn builder(connection_string: impl Into<String>) -> RedisSessionStoreBuilder {
|
||||||
RedisSessionStoreBuilder {
|
RedisSessionStoreBuilder {
|
||||||
configuration: CacheConfiguration::default(),
|
configuration: CacheConfiguration::default(),
|
||||||
connection_string: connection_string.into(),
|
conn_builder: RedisSessionConnBuilder::Single(connection_string.into()),
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Create a new instance of [`RedisSessionStore`] using the default configuration.
|
/// Returns a fluent API builder to configure [`RedisSessionStore`].
|
||||||
/// It takes as input the only required input to create a new instance of [`RedisSessionStore`] - a
|
///
|
||||||
/// connection string for Redis.
|
/// It takes as input the only required input to create a new instance of [`RedisSessionStore`]
|
||||||
pub async fn new<S: Into<String>>(
|
/// - a pool object for Redis.
|
||||||
connection_string: S,
|
#[cfg(feature = "redis-pool")]
|
||||||
) -> Result<RedisSessionStore, anyhow::Error> {
|
pub fn builder_pooled(pool: impl Into<deadpool_redis::Pool>) -> RedisSessionStoreBuilder {
|
||||||
|
RedisSessionStoreBuilder {
|
||||||
|
configuration: CacheConfiguration::default(),
|
||||||
|
conn_builder: RedisSessionConnBuilder::Pool(pool.into()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Creates a new instance of [`RedisSessionStore`] using the default configuration.
|
||||||
|
///
|
||||||
|
/// It takes as input the only required input to create a new instance of [`RedisSessionStore`]
|
||||||
|
/// - a connection string for Redis.
|
||||||
|
pub async fn new(connection_string: impl Into<String>) -> Result<RedisSessionStore, Error> {
|
||||||
Self::builder(connection_string).build().await
|
Self::builder(connection_string).build().await
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/// Creates a new instance of [`RedisSessionStore`] using the default configuration.
|
||||||
|
///
|
||||||
|
/// It takes as input the only required input to create a new instance of [`RedisSessionStore`]
|
||||||
|
/// - a pool object for Redis.
|
||||||
|
#[cfg(feature = "redis-pool")]
|
||||||
|
pub async fn new_pooled(
|
||||||
|
pool: impl Into<deadpool_redis::Pool>,
|
||||||
|
) -> anyhow::Result<RedisSessionStore> {
|
||||||
|
Self::builder_pooled(pool).build().await
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
/// A fluent builder to construct a [`RedisSessionStore`] instance with custom configuration
|
/// A fluent builder to construct a [`RedisSessionStore`] instance with custom configuration
|
||||||
/// parameters.
|
/// parameters.
|
||||||
///
|
|
||||||
/// [`RedisSessionStore`]: crate::storage::RedisSessionStore
|
|
||||||
#[cfg_attr(docsrs, doc(cfg(feature = "redis-rs-session")))]
|
|
||||||
#[must_use]
|
#[must_use]
|
||||||
pub struct RedisSessionStoreBuilder {
|
pub struct RedisSessionStoreBuilder {
|
||||||
connection_string: String,
|
|
||||||
configuration: CacheConfiguration,
|
configuration: CacheConfiguration,
|
||||||
|
conn_builder: RedisSessionConnBuilder,
|
||||||
|
}
|
||||||
|
|
||||||
|
enum RedisSessionConnBuilder {
|
||||||
|
/// Single connection string.
|
||||||
|
Single(String),
|
||||||
|
|
||||||
|
/// Pre-built connection pool.
|
||||||
|
#[cfg(feature = "redis-pool")]
|
||||||
|
Pool(deadpool_redis::Pool),
|
||||||
|
}
|
||||||
|
|
||||||
|
impl RedisSessionConnBuilder {
|
||||||
|
async fn into_client(self) -> anyhow::Result<RedisSessionConn> {
|
||||||
|
Ok(match self {
|
||||||
|
RedisSessionConnBuilder::Single(conn_string) => {
|
||||||
|
RedisSessionConn::Single(ConnectionManager::new(Client::open(conn_string)?).await?)
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "redis-pool")]
|
||||||
|
RedisSessionConnBuilder::Pool(pool) => RedisSessionConn::Pool(pool),
|
||||||
|
})
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
impl RedisSessionStoreBuilder {
|
impl RedisSessionStoreBuilder {
|
||||||
@ -120,11 +187,10 @@ impl RedisSessionStoreBuilder {
|
|||||||
self
|
self
|
||||||
}
|
}
|
||||||
|
|
||||||
/// Finalise the builder and return a [`RedisActorSessionStore`] instance.
|
/// Finalises builder and returns a [`RedisSessionStore`] instance.
|
||||||
///
|
pub async fn build(self) -> anyhow::Result<RedisSessionStore> {
|
||||||
/// [`RedisActorSessionStore`]: crate::storage::RedisActorSessionStore
|
let client = self.conn_builder.into_client().await?;
|
||||||
pub async fn build(self) -> Result<RedisSessionStore, anyhow::Error> {
|
|
||||||
let client = ConnectionManager::new(redis::Client::open(self.connection_string)?).await?;
|
|
||||||
Ok(RedisSessionStore {
|
Ok(RedisSessionStore {
|
||||||
configuration: self.configuration,
|
configuration: self.configuration,
|
||||||
client,
|
client,
|
||||||
@ -132,7 +198,6 @@ impl RedisSessionStoreBuilder {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[async_trait::async_trait(?Send)]
|
|
||||||
impl SessionStore for RedisSessionStore {
|
impl SessionStore for RedisSessionStore {
|
||||||
async fn load(&self, session_key: &SessionKey) -> Result<Option<SessionState>, LoadError> {
|
async fn load(&self, session_key: &SessionKey) -> Result<Option<SessionState>, LoadError> {
|
||||||
let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
|
let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
|
||||||
@ -140,7 +205,6 @@ impl SessionStore for RedisSessionStore {
|
|||||||
let value: Option<String> = self
|
let value: Option<String> = self
|
||||||
.execute_command(redis::cmd("GET").arg(&[&cache_key]))
|
.execute_command(redis::cmd("GET").arg(&[&cache_key]))
|
||||||
.await
|
.await
|
||||||
.map_err(Into::into)
|
|
||||||
.map_err(LoadError::Other)?;
|
.map_err(LoadError::Other)?;
|
||||||
|
|
||||||
match value {
|
match value {
|
||||||
@ -162,15 +226,19 @@ impl SessionStore for RedisSessionStore {
|
|||||||
let session_key = generate_session_key();
|
let session_key = generate_session_key();
|
||||||
let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
|
let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
|
||||||
|
|
||||||
self.execute_command(redis::cmd("SET").arg(&[
|
self.execute_command::<()>(
|
||||||
&cache_key,
|
redis::cmd("SET")
|
||||||
&body,
|
.arg(&[
|
||||||
"NX", // NX: only set the key if it does not already exist
|
&cache_key, // key
|
||||||
"EX", // EX: set expiry
|
&body, // value
|
||||||
&format!("{}", ttl.whole_seconds()),
|
"NX", // only set the key if it does not already exist
|
||||||
]))
|
"EX", // set expiry / TTL
|
||||||
|
])
|
||||||
|
.arg(
|
||||||
|
ttl.whole_seconds(), // EXpiry in seconds
|
||||||
|
),
|
||||||
|
)
|
||||||
.await
|
.await
|
||||||
.map_err(Into::into)
|
|
||||||
.map_err(SaveError::Other)?;
|
.map_err(SaveError::Other)?;
|
||||||
|
|
||||||
Ok(session_key)
|
Ok(session_key)
|
||||||
@ -188,7 +256,7 @@ impl SessionStore for RedisSessionStore {
|
|||||||
|
|
||||||
let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
|
let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
|
||||||
|
|
||||||
let v: redis::Value = self
|
let v: Value = self
|
||||||
.execute_command(redis::cmd("SET").arg(&[
|
.execute_command(redis::cmd("SET").arg(&[
|
||||||
&cache_key,
|
&cache_key,
|
||||||
&body,
|
&body,
|
||||||
@ -197,7 +265,6 @@ impl SessionStore for RedisSessionStore {
|
|||||||
&format!("{}", ttl.whole_seconds()),
|
&format!("{}", ttl.whole_seconds()),
|
||||||
]))
|
]))
|
||||||
.await
|
.await
|
||||||
.map_err(Into::into)
|
|
||||||
.map_err(UpdateError::Other)?;
|
.map_err(UpdateError::Other)?;
|
||||||
|
|
||||||
match v {
|
match v {
|
||||||
@ -213,7 +280,7 @@ impl SessionStore for RedisSessionStore {
|
|||||||
SaveError::Other(err) => UpdateError::Other(err),
|
SaveError::Other(err) => UpdateError::Other(err),
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
Value::Int(_) | Value::Okay | Value::Status(_) => Ok(session_key),
|
Value::Int(_) | Value::Okay | Value::SimpleString(_) => Ok(session_key),
|
||||||
val => Err(UpdateError::Other(anyhow::anyhow!(
|
val => Err(UpdateError::Other(anyhow::anyhow!(
|
||||||
"Failed to update session state. {:?}",
|
"Failed to update session state. {:?}",
|
||||||
val
|
val
|
||||||
@ -221,11 +288,33 @@ impl SessionStore for RedisSessionStore {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn delete(&self, session_key: &SessionKey) -> Result<(), anyhow::Error> {
|
async fn update_ttl(&self, session_key: &SessionKey, ttl: &Duration) -> anyhow::Result<()> {
|
||||||
let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
|
let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
|
||||||
self.execute_command(redis::cmd("DEL").arg(&[&cache_key]))
|
|
||||||
|
match self.client {
|
||||||
|
RedisSessionConn::Single(ref conn) => {
|
||||||
|
conn.clone()
|
||||||
|
.expire::<_, ()>(&cache_key, ttl.whole_seconds())
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "redis-pool")]
|
||||||
|
RedisSessionConn::Pool(ref pool) => {
|
||||||
|
pool.get()
|
||||||
|
.await?
|
||||||
|
.expire::<_, ()>(&cache_key, ttl.whole_seconds())
|
||||||
|
.await?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn delete(&self, session_key: &SessionKey) -> Result<(), Error> {
|
||||||
|
let cache_key = (self.configuration.cache_keygen)(session_key.as_ref());
|
||||||
|
|
||||||
|
self.execute_command::<()>(redis::cmd("DEL").arg(&[&cache_key]))
|
||||||
.await
|
.await
|
||||||
.map_err(Into::into)
|
|
||||||
.map_err(UpdateError::Other)?;
|
.map_err(UpdateError::Other)?;
|
||||||
|
|
||||||
Ok(())
|
Ok(())
|
||||||
@ -246,11 +335,16 @@ impl RedisSessionStore {
|
|||||||
/// This helper method catches this case (`.is_connection_dropped`) to execute a retry. The
|
/// This helper method catches this case (`.is_connection_dropped`) to execute a retry. The
|
||||||
/// retry will be executed on a fresh connection, therefore it is likely to succeed (or fail for
|
/// retry will be executed on a fresh connection, therefore it is likely to succeed (or fail for
|
||||||
/// a different more meaningful reason).
|
/// a different more meaningful reason).
|
||||||
async fn execute_command<T: FromRedisValue>(&self, cmd: &mut Cmd) -> RedisResult<T> {
|
#[allow(clippy::needless_pass_by_ref_mut)]
|
||||||
|
async fn execute_command<T: FromRedisValue>(&self, cmd: &mut Cmd) -> anyhow::Result<T> {
|
||||||
let mut can_retry = true;
|
let mut can_retry = true;
|
||||||
|
|
||||||
|
match self.client {
|
||||||
|
RedisSessionConn::Single(ref conn) => {
|
||||||
|
let mut conn = conn.clone();
|
||||||
|
|
||||||
loop {
|
loop {
|
||||||
match cmd.query_async(&mut self.client.clone()).await {
|
match cmd.query_async(&mut conn).await {
|
||||||
Ok(value) => return Ok(value),
|
Ok(value) => return Ok(value),
|
||||||
Err(err) => {
|
Err(err) => {
|
||||||
if can_retry && err.is_connection_dropped() {
|
if can_retry && err.is_connection_dropped() {
|
||||||
@ -263,7 +357,34 @@ impl RedisSessionStore {
|
|||||||
|
|
||||||
continue;
|
continue;
|
||||||
} else {
|
} else {
|
||||||
return Err(err);
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "redis-pool")]
|
||||||
|
RedisSessionConn::Pool(ref pool) => {
|
||||||
|
let mut conn = pool.get().await?;
|
||||||
|
|
||||||
|
loop {
|
||||||
|
match cmd.query_async(&mut conn).await {
|
||||||
|
Ok(value) => return Ok(value),
|
||||||
|
Err(err) => {
|
||||||
|
if can_retry && err.is_connection_dropped() {
|
||||||
|
tracing::debug!(
|
||||||
|
"Connection dropped while trying to talk to Redis. Retrying."
|
||||||
|
);
|
||||||
|
|
||||||
|
// Retry at most once
|
||||||
|
can_retry = false;
|
||||||
|
|
||||||
|
continue;
|
||||||
|
} else {
|
||||||
|
return Err(err.into());
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
@ -272,20 +393,33 @@ impl RedisSessionStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#[cfg(test)]
|
#[cfg(test)]
|
||||||
mod test {
|
mod tests {
|
||||||
use std::collections::HashMap;
|
use std::collections::HashMap;
|
||||||
|
|
||||||
use redis::AsyncCommands;
|
use actix_web::cookie::time;
|
||||||
|
#[cfg(not(feature = "redis-session"))]
|
||||||
|
use deadpool_redis::{Config, Runtime};
|
||||||
|
|
||||||
use super::*;
|
use super::*;
|
||||||
use crate::test_helpers::acceptance_test_suite;
|
use crate::test_helpers::acceptance_test_suite;
|
||||||
|
|
||||||
async fn redis_store() -> RedisSessionStore {
|
async fn redis_store() -> RedisSessionStore {
|
||||||
|
#[cfg(feature = "redis-session")]
|
||||||
|
{
|
||||||
RedisSessionStore::new("redis://127.0.0.1:6379")
|
RedisSessionStore::new("redis://127.0.0.1:6379")
|
||||||
.await
|
.await
|
||||||
.unwrap()
|
.unwrap()
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "redis-session"))]
|
||||||
|
{
|
||||||
|
let redis_pool = Config::from_url("redis://127.0.0.1:6379")
|
||||||
|
.create_pool(Some(Runtime::Tokio1))
|
||||||
|
.unwrap();
|
||||||
|
RedisSessionStore::new(redis_pool.clone())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
#[actix_web::test]
|
#[actix_web::test]
|
||||||
async fn test_session_workflow() {
|
async fn test_session_workflow() {
|
||||||
let redis_store = redis_store().await;
|
let redis_store = redis_store().await;
|
||||||
@ -303,12 +437,25 @@ mod test {
|
|||||||
async fn loading_an_invalid_session_state_returns_deserialization_error() {
|
async fn loading_an_invalid_session_state_returns_deserialization_error() {
|
||||||
let store = redis_store().await;
|
let store = redis_store().await;
|
||||||
let session_key = generate_session_key();
|
let session_key = generate_session_key();
|
||||||
store
|
|
||||||
.client
|
match store.client {
|
||||||
|
RedisSessionConn::Single(ref conn) => conn
|
||||||
.clone()
|
.clone()
|
||||||
.set::<_, _, ()>(session_key.as_ref(), "random-thing-which-is-not-json")
|
.set::<_, _, ()>(session_key.as_ref(), "random-thing-which-is-not-json")
|
||||||
.await
|
.await
|
||||||
|
.unwrap(),
|
||||||
|
|
||||||
|
#[cfg(feature = "redis-pool")]
|
||||||
|
RedisSessionConn::Pool(ref pool) => {
|
||||||
|
pool.get()
|
||||||
|
.await
|
||||||
|
.unwrap()
|
||||||
|
.set::<_, _, ()>(session_key.as_ref(), "random-thing-which-is-not-json")
|
||||||
|
.await
|
||||||
.unwrap();
|
.unwrap();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
assert!(matches!(
|
assert!(matches!(
|
||||||
store.load(&session_key).await.unwrap_err(),
|
store.load(&session_key).await.unwrap_err(),
|
||||||
LoadError::Deserialization(_),
|
LoadError::Deserialization(_),
|
||||||
|
@ -1,17 +1,13 @@
|
|||||||
use std::convert::TryFrom;
|
use derive_more::derive::{Display, From};
|
||||||
|
|
||||||
use derive_more::{Display, From};
|
/// A session key, the string stored in a client-side cookie to associate a user with its session
|
||||||
|
/// state on the backend.
|
||||||
/// A session key, the string stored in a client-side cookie to associate a user
|
|
||||||
/// with its session state on the backend.
|
|
||||||
///
|
///
|
||||||
/// ## Validation
|
/// # Validation
|
||||||
|
/// Session keys are stored as cookies, therefore they cannot be arbitrary long. Session keys are
|
||||||
|
/// required to be smaller than 4064 bytes.
|
||||||
///
|
///
|
||||||
/// Session keys are stored as cookies, therefore they cannot be arbitrary long.
|
/// ```
|
||||||
/// We require session keys to be smaller than 4064 bytes.
|
|
||||||
///
|
|
||||||
/// ```rust
|
|
||||||
/// use std::convert::TryInto;
|
|
||||||
/// use actix_session::storage::SessionKey;
|
/// use actix_session::storage::SessionKey;
|
||||||
///
|
///
|
||||||
/// let key: String = std::iter::repeat('a').take(4065).collect();
|
/// let key: String = std::iter::repeat('a').take(4065).collect();
|
||||||
@ -24,15 +20,15 @@ pub struct SessionKey(String);
|
|||||||
impl TryFrom<String> for SessionKey {
|
impl TryFrom<String> for SessionKey {
|
||||||
type Error = InvalidSessionKeyError;
|
type Error = InvalidSessionKeyError;
|
||||||
|
|
||||||
fn try_from(v: String) -> Result<Self, Self::Error> {
|
fn try_from(val: String) -> Result<Self, Self::Error> {
|
||||||
if v.len() > 4064 {
|
if val.len() > 4064 {
|
||||||
return Err(anyhow::anyhow!(
|
return Err(anyhow::anyhow!(
|
||||||
"The session key is bigger than 4064 bytes, the upper limit on cookie content."
|
"The session key is bigger than 4064 bytes, the upper limit on cookie content."
|
||||||
)
|
)
|
||||||
.into());
|
.into());
|
||||||
}
|
}
|
||||||
|
|
||||||
Ok(SessionKey(v))
|
Ok(SessionKey(val))
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -43,13 +39,13 @@ impl AsRef<str> for SessionKey {
|
|||||||
}
|
}
|
||||||
|
|
||||||
impl From<SessionKey> for String {
|
impl From<SessionKey> for String {
|
||||||
fn from(k: SessionKey) -> Self {
|
fn from(key: SessionKey) -> Self {
|
||||||
k.0
|
key.0
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
#[derive(Debug, Display, From)]
|
#[derive(Debug, Display, From)]
|
||||||
#[display(fmt = "The provided string is not a valid session key")]
|
#[display("The provided string is not a valid session key")]
|
||||||
pub struct InvalidSessionKeyError(anyhow::Error);
|
pub struct InvalidSessionKeyError(anyhow::Error);
|
||||||
|
|
||||||
impl std::error::Error for InvalidSessionKeyError {
|
impl std::error::Error for InvalidSessionKeyError {
|
||||||
|
@ -1,19 +1,13 @@
|
|||||||
use std::convert::TryInto;
|
use rand::distr::{Alphanumeric, SampleString as _};
|
||||||
|
|
||||||
use rand::{distributions::Alphanumeric, rngs::OsRng, Rng as _};
|
|
||||||
|
|
||||||
use crate::storage::SessionKey;
|
use crate::storage::SessionKey;
|
||||||
|
|
||||||
/// Session key generation routine that follows [OWASP recommendations].
|
/// Session key generation routine that follows [OWASP recommendations].
|
||||||
///
|
///
|
||||||
/// [OWASP recommendations]: https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html#session-id-entropy
|
/// [OWASP recommendations]: https://cheatsheetseries.owasp.org/cheatsheets/Session_Management_Cheat_Sheet.html#session-id-entropy
|
||||||
pub(crate) fn generate_session_key() -> SessionKey {
|
pub fn generate_session_key() -> SessionKey {
|
||||||
let value = std::iter::repeat(())
|
Alphanumeric
|
||||||
.map(|()| OsRng.sample(Alphanumeric))
|
.sample_string(&mut rand::rng(), 64)
|
||||||
.take(64)
|
.try_into()
|
||||||
.collect::<Vec<_>>();
|
.expect("generated string should be within size range for a session key")
|
||||||
|
|
||||||
// These unwraps will never panic because pre-conditions are always verified
|
|
||||||
// (i.e. length and character set)
|
|
||||||
String::from_utf8(value).unwrap().try_into().unwrap()
|
|
||||||
}
|
}
|
||||||
|
@ -48,7 +48,7 @@ async fn cookie_storage() -> std::io::Result<()> {
|
|||||||
let deletion_cookie = logout_response.response().cookies().next().unwrap();
|
let deletion_cookie = logout_response.response().cookies().next().unwrap();
|
||||||
assert_eq!(deletion_cookie.name(), "id");
|
assert_eq!(deletion_cookie.name(), "id");
|
||||||
assert_eq!(deletion_cookie.path().unwrap(), "/test");
|
assert_eq!(deletion_cookie.path().unwrap(), "/test");
|
||||||
assert!(deletion_cookie.secure().is_none());
|
assert!(deletion_cookie.secure().unwrap());
|
||||||
assert!(deletion_cookie.http_only().unwrap());
|
assert!(deletion_cookie.http_only().unwrap());
|
||||||
assert_eq!(deletion_cookie.max_age().unwrap(), Duration::ZERO);
|
assert_eq!(deletion_cookie.max_age().unwrap(), Duration::ZERO);
|
||||||
assert_eq!(deletion_cookie.domain().unwrap(), "localhost");
|
assert_eq!(deletion_cookie.domain().unwrap(), "localhost");
|
||||||
|
@ -1,15 +1,17 @@
|
|||||||
use actix_session::storage::{LoadError, SaveError, SessionKey, SessionStore, UpdateError};
|
use std::collections::HashMap;
|
||||||
use actix_session::{Session, SessionMiddleware};
|
|
||||||
use actix_web::body::MessageBody;
|
use actix_session::{
|
||||||
use actix_web::http::StatusCode;
|
storage::{LoadError, SaveError, SessionKey, SessionStore, UpdateError},
|
||||||
|
Session, SessionMiddleware,
|
||||||
|
};
|
||||||
use actix_web::{
|
use actix_web::{
|
||||||
|
body::MessageBody,
|
||||||
cookie::{time::Duration, Key},
|
cookie::{time::Duration, Key},
|
||||||
dev::Service,
|
dev::Service,
|
||||||
|
http::StatusCode,
|
||||||
test, web, App, Responder,
|
test, web, App, Responder,
|
||||||
};
|
};
|
||||||
use anyhow::Error;
|
use anyhow::Error;
|
||||||
use std::collections::HashMap;
|
|
||||||
use std::convert::TryInto;
|
|
||||||
|
|
||||||
#[actix_web::test]
|
#[actix_web::test]
|
||||||
async fn errors_are_opaque() {
|
async fn errors_are_opaque() {
|
||||||
@ -42,7 +44,6 @@ async fn errors_are_opaque() {
|
|||||||
|
|
||||||
struct MockStore;
|
struct MockStore;
|
||||||
|
|
||||||
#[async_trait::async_trait(?Send)]
|
|
||||||
impl SessionStore for MockStore {
|
impl SessionStore for MockStore {
|
||||||
async fn load(
|
async fn load(
|
||||||
&self,
|
&self,
|
||||||
@ -67,11 +68,18 @@ impl SessionStore for MockStore {
|
|||||||
_session_state: HashMap<String, String>,
|
_session_state: HashMap<String, String>,
|
||||||
_ttl: &Duration,
|
_ttl: &Duration,
|
||||||
) -> Result<SessionKey, UpdateError> {
|
) -> Result<SessionKey, UpdateError> {
|
||||||
todo!()
|
#![allow(clippy::diverging_sub_expression)]
|
||||||
|
unimplemented!()
|
||||||
|
}
|
||||||
|
|
||||||
|
async fn update_ttl(&self, _session_key: &SessionKey, _ttl: &Duration) -> Result<(), Error> {
|
||||||
|
#![allow(clippy::diverging_sub_expression)]
|
||||||
|
unimplemented!()
|
||||||
}
|
}
|
||||||
|
|
||||||
async fn delete(&self, _session_key: &SessionKey) -> Result<(), Error> {
|
async fn delete(&self, _session_key: &SessionKey) -> Result<(), Error> {
|
||||||
todo!()
|
#![allow(clippy::diverging_sub_expression)]
|
||||||
|
unimplemented!()
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -68,3 +68,84 @@ async fn session_entries() {
|
|||||||
map.contains_key("test_str");
|
map.contains_key("test_str");
|
||||||
map.contains_key("test_num");
|
map.contains_key("test_num");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
#[actix_web::test]
|
||||||
|
async fn session_contains_key() {
|
||||||
|
let req = test::TestRequest::default().to_srv_request();
|
||||||
|
let session = req.get_session();
|
||||||
|
session.insert("test_str", "val").unwrap();
|
||||||
|
session.insert("test_str", 1).unwrap();
|
||||||
|
assert!(session.contains_key("test_str"));
|
||||||
|
assert!(!session.contains_key("test_num"));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_web::test]
|
||||||
|
async fn insert_session_after_renew() {
|
||||||
|
let session = test::TestRequest::default().to_srv_request().get_session();
|
||||||
|
|
||||||
|
session.insert("test_val", "val").unwrap();
|
||||||
|
assert_eq!(session.status(), SessionStatus::Changed);
|
||||||
|
|
||||||
|
session.renew();
|
||||||
|
assert_eq!(session.status(), SessionStatus::Renewed);
|
||||||
|
|
||||||
|
session.insert("test_val1", "val1").unwrap();
|
||||||
|
assert_eq!(session.status(), SessionStatus::Renewed);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_web::test]
|
||||||
|
async fn update_session() {
|
||||||
|
let session = test::TestRequest::default().to_srv_request().get_session();
|
||||||
|
|
||||||
|
session.update("test_val", |c: u32| c + 1).unwrap();
|
||||||
|
assert_eq!(session.status(), SessionStatus::Unchanged);
|
||||||
|
|
||||||
|
session.insert("test_val", 0).unwrap();
|
||||||
|
assert_eq!(session.status(), SessionStatus::Changed);
|
||||||
|
|
||||||
|
session.update("test_val", |c: u32| c + 1).unwrap();
|
||||||
|
assert_eq!(session.get("test_val").unwrap(), Some(1));
|
||||||
|
|
||||||
|
session.update("test_val", |c: u32| c + 1).unwrap();
|
||||||
|
assert_eq!(session.get("test_val").unwrap(), Some(2));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_web::test]
|
||||||
|
async fn update_or_session() {
|
||||||
|
let session = test::TestRequest::default().to_srv_request().get_session();
|
||||||
|
|
||||||
|
session.update_or("test_val", 1, |c: u32| c + 1).unwrap();
|
||||||
|
assert_eq!(session.status(), SessionStatus::Changed);
|
||||||
|
assert_eq!(session.get("test_val").unwrap(), Some(1));
|
||||||
|
|
||||||
|
session.update_or("test_val", 1, |c: u32| c + 1).unwrap();
|
||||||
|
assert_eq!(session.get("test_val").unwrap(), Some(2));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_web::test]
|
||||||
|
async fn remove_session_after_renew() {
|
||||||
|
let session = test::TestRequest::default().to_srv_request().get_session();
|
||||||
|
|
||||||
|
session.insert("test_val", "val").unwrap();
|
||||||
|
session.remove("test_val").unwrap();
|
||||||
|
assert_eq!(session.status(), SessionStatus::Changed);
|
||||||
|
|
||||||
|
session.renew();
|
||||||
|
session.insert("test_val", "val").unwrap();
|
||||||
|
session.remove("test_val").unwrap();
|
||||||
|
assert_eq!(session.status(), SessionStatus::Renewed);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_web::test]
|
||||||
|
async fn clear_session_after_renew() {
|
||||||
|
let session = test::TestRequest::default().to_srv_request().get_session();
|
||||||
|
|
||||||
|
session.clear();
|
||||||
|
assert_eq!(session.status(), SessionStatus::Changed);
|
||||||
|
|
||||||
|
session.renew();
|
||||||
|
assert_eq!(session.status(), SessionStatus::Renewed);
|
||||||
|
|
||||||
|
session.clear();
|
||||||
|
assert_eq!(session.status(), SessionStatus::Renewed);
|
||||||
|
}
|
||||||
|
40
actix-settings/CHANGES.md
Normal file
40
actix-settings/CHANGES.md
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
# Changes
|
||||||
|
|
||||||
|
## Unreleased
|
||||||
|
|
||||||
|
## 0.8.0
|
||||||
|
|
||||||
|
- Add `openssl` crate feature for TLS settings using OpenSSL.
|
||||||
|
- Add `ApplySettings::try_apply_settings()`.
|
||||||
|
- Implement TLS logic for `ApplySettings::try_apply_settings()`.
|
||||||
|
- Add `Tls::get_ssl_acceptor_builder()` function to build `openssl::ssl::SslAcceptorBuilder`.
|
||||||
|
- Deprecate `ApplySettings::apply_settings()`.
|
||||||
|
- Minimum supported Rust version (MSRV) is now 1.75.
|
||||||
|
|
||||||
|
## 0.7.1
|
||||||
|
|
||||||
|
- Fix doc examples.
|
||||||
|
|
||||||
|
## 0.7.0
|
||||||
|
|
||||||
|
- The `ApplySettings` trait now includes a type parameter, allowing multiple types to be implemented per configuration target.
|
||||||
|
- Implement `ApplySettings` for `ActixSettings`.
|
||||||
|
- `BasicSettings::from_default_template()` is now infallible.
|
||||||
|
- Rename `AtError => Error`.
|
||||||
|
- Remove `AtResult` type alias.
|
||||||
|
- Update `toml` dependency to `0.8`.
|
||||||
|
- Remove `ioe` dependency; `std::io::Error` is now used directly.
|
||||||
|
- Remove `Clone` implementation for `Error`.
|
||||||
|
- Implement `Display` for `Error`.
|
||||||
|
- Implement std's `Error` for `Error`.
|
||||||
|
- Minimum supported Rust version (MSRV) is now 1.68.
|
||||||
|
|
||||||
|
## 0.6.0
|
||||||
|
|
||||||
|
- Update Actix Web dependencies to v4 ecosystem.
|
||||||
|
- Rename `actix.ssl` settings object to `actix.tls`.
|
||||||
|
- `NoSettings` is now marked `#[non_exhaustive]`.
|
||||||
|
|
||||||
|
## 0.5.2
|
||||||
|
|
||||||
|
- Adopted into @actix org from <https://github.com/jjpe/actix-settings>.
|
37
actix-settings/Cargo.toml
Normal file
37
actix-settings/Cargo.toml
Normal file
@ -0,0 +1,37 @@
|
|||||||
|
[package]
|
||||||
|
name = "actix-settings"
|
||||||
|
version = "0.8.0"
|
||||||
|
authors = [
|
||||||
|
"Joey Ezechiels <joey.ezechiels@gmail.com>",
|
||||||
|
"Rob Ede <robjtede@icloud.com>",
|
||||||
|
]
|
||||||
|
description = "Easily manage Actix Web's settings from a TOML file and environment variables"
|
||||||
|
repository.workspace = true
|
||||||
|
homepage.workspace = true
|
||||||
|
license.workspace = true
|
||||||
|
edition.workspace = true
|
||||||
|
rust-version.workspace = true
|
||||||
|
|
||||||
|
[package.metadata.docs.rs]
|
||||||
|
rustdoc-args = ["--cfg", "docsrs"]
|
||||||
|
|
||||||
|
[features]
|
||||||
|
openssl = ["dep:openssl", "actix-web/openssl"]
|
||||||
|
|
||||||
|
[dependencies]
|
||||||
|
actix-http = "3"
|
||||||
|
actix-service = "2"
|
||||||
|
actix-web = { version = "4", default-features = false }
|
||||||
|
derive_more = { version = "2", features = ["display", "error"] }
|
||||||
|
once_cell = "1.21"
|
||||||
|
openssl = { version = "0.10", features = ["v110"], optional = true }
|
||||||
|
regex = "1.5"
|
||||||
|
serde = { version = "1", features = ["derive"] }
|
||||||
|
toml = "0.8"
|
||||||
|
|
||||||
|
[dev-dependencies]
|
||||||
|
actix-web = "4"
|
||||||
|
env_logger = "0.11"
|
||||||
|
|
||||||
|
[lints]
|
||||||
|
workspace = true
|
31
actix-settings/README.md
Normal file
31
actix-settings/README.md
Normal file
@ -0,0 +1,31 @@
|
|||||||
|
# actix-settings
|
||||||
|
|
||||||
|
> Easily manage Actix Web's settings from a TOML file and environment variables.
|
||||||
|
|
||||||
|
<!-- prettier-ignore-start -->
|
||||||
|
|
||||||
|
[](https://crates.io/crates/actix-settings)
|
||||||
|
[](https://docs.rs/actix-settings/0.8.0)
|
||||||
|

|
||||||
|
[](https://deps.rs/crate/actix-settings/0.8.0)
|
||||||
|
|
||||||
|
<!-- prettier-ignore-end -->
|
||||||
|
|
||||||
|
## Documentation & Resources
|
||||||
|
|
||||||
|
- [API Documentation](https://docs.rs/actix-settings)
|
||||||
|
- [Usage Example][usage]
|
||||||
|
- Minimum Supported Rust Version (MSRV): 1.57
|
||||||
|
|
||||||
|
### Custom Settings
|
||||||
|
|
||||||
|
There is a way to extend the available settings. This can be used to combine the settings provided by Actix Web and those provided by application server built using `actix`.
|
||||||
|
|
||||||
|
Have a look at [the usage example][usage] to see how.
|
||||||
|
|
||||||
|
## Special Thanks
|
||||||
|
|
||||||
|
This crate was made possible by support from Accept B.V and [@jjpe].
|
||||||
|
|
||||||
|
[usage]: https://github.com/actix/actix-extras/blob/master/actix-settings/examples/actix.rs
|
||||||
|
[@jjpe]: https://github.com/jjpe
|
82
actix-settings/examples/actix.rs
Normal file
82
actix-settings/examples/actix.rs
Normal file
@ -0,0 +1,82 @@
|
|||||||
|
use actix_settings::{ApplySettings as _, Mode, Settings};
|
||||||
|
use actix_web::{
|
||||||
|
get,
|
||||||
|
middleware::{Compress, Condition, Logger},
|
||||||
|
web, App, HttpServer, Responder,
|
||||||
|
};
|
||||||
|
|
||||||
|
#[get("/")]
|
||||||
|
async fn index(settings: web::Data<Settings>) -> impl Responder {
|
||||||
|
format!(
|
||||||
|
r#"{{
|
||||||
|
"mode": "{}",
|
||||||
|
"hosts": ["{}"]
|
||||||
|
}}"#,
|
||||||
|
match settings.actix.mode {
|
||||||
|
Mode::Development => "development",
|
||||||
|
Mode::Production => "production",
|
||||||
|
},
|
||||||
|
settings
|
||||||
|
.actix
|
||||||
|
.hosts
|
||||||
|
.iter()
|
||||||
|
.map(|addr| { format!("{}:{}", addr.host, addr.port) })
|
||||||
|
.collect::<Vec<_>>()
|
||||||
|
.join(", "),
|
||||||
|
)
|
||||||
|
.customize()
|
||||||
|
.insert_header(("content-type", "application/json"))
|
||||||
|
}
|
||||||
|
|
||||||
|
#[actix_web::main]
|
||||||
|
async fn main() -> std::io::Result<()> {
|
||||||
|
let mut settings = Settings::parse_toml("./examples/config.toml")
|
||||||
|
.expect("Failed to parse `Settings` from config.toml");
|
||||||
|
|
||||||
|
// If the environment variable `$APPLICATION__HOSTS` is set,
|
||||||
|
// have its value override the `settings.actix.hosts` setting:
|
||||||
|
Settings::override_field_with_env_var(&mut settings.actix.hosts, "APPLICATION__HOSTS")?;
|
||||||
|
|
||||||
|
init_logger(&settings);
|
||||||
|
|
||||||
|
HttpServer::new({
|
||||||
|
// clone settings into each worker thread
|
||||||
|
let settings = settings.clone();
|
||||||
|
|
||||||
|
move || {
|
||||||
|
App::new()
|
||||||
|
// Include this `.wrap()` call for compression settings to take effect:
|
||||||
|
.wrap(Condition::new(
|
||||||
|
settings.actix.enable_compression,
|
||||||
|
Compress::default(),
|
||||||
|
))
|
||||||
|
.wrap(Logger::default())
|
||||||
|
// make `Settings` available to handlers
|
||||||
|
.app_data(web::Data::new(settings.clone()))
|
||||||
|
.service(index)
|
||||||
|
}
|
||||||
|
})
|
||||||
|
// apply the `Settings` to Actix Web's `HttpServer`
|
||||||
|
.try_apply_settings(&settings)?
|
||||||
|
.run()
|
||||||
|
.await
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Initialize the logging infrastructure.
|
||||||
|
fn init_logger(settings: &Settings) {
|
||||||
|
if !settings.actix.enable_log {
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
|
||||||
|
std::env::set_var(
|
||||||
|
"RUST_LOG",
|
||||||
|
match settings.actix.mode {
|
||||||
|
Mode::Development => "actix_web=debug",
|
||||||
|
Mode::Production => "actix_web=info",
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
std::env::set_var("RUST_BACKTRACE", "1");
|
||||||
|
|
||||||
|
env_logger::init();
|
||||||
|
}
|
72
actix-settings/examples/config.toml
Normal file
72
actix-settings/examples/config.toml
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
[actix]
|
||||||
|
# For more info, see: https://docs.rs/actix-web/4/actix_web/struct.HttpServer.html.
|
||||||
|
|
||||||
|
hosts = [
|
||||||
|
["0.0.0.0", 8080] # This should work for both development and deployment...
|
||||||
|
# # ... but other entries are possible, as well.
|
||||||
|
]
|
||||||
|
mode = "development" # Either "development" or "production".
|
||||||
|
enable-compression = true # Toggle compression middleware.
|
||||||
|
enable-log = true # Toggle logging middleware.
|
||||||
|
|
||||||
|
# The number of workers that the server should start.
|
||||||
|
# By default the number of available logical cpu cores is used.
|
||||||
|
# Takes a string value: Either "default", or an integer N > 0 e.g. "6".
|
||||||
|
num-workers = "default"
|
||||||
|
|
||||||
|
# The maximum number of pending connections. This refers to the number of clients
|
||||||
|
# that can be waiting to be served. Exceeding this number results in the client
|
||||||
|
# getting an error when attempting to connect. It should only affect servers under
|
||||||
|
# significant load. Generally set in the 64-2048 range. The default value is 2048.
|
||||||
|
# Takes a string value: Either "default", or an integer N > 0 e.g. "6".
|
||||||
|
backlog = "default"
|
||||||
|
|
||||||
|
# Sets the per-worker maximum number of concurrent connections. All socket listeners
|
||||||
|
# will stop accepting connections when this limit is reached for each worker.
|
||||||
|
# By default max connections is set to a 25k.
|
||||||
|
# Takes a string value: Either "default", or an integer N > 0 e.g. "6".
|
||||||
|
max-connections = "default"
|
||||||
|
|
||||||
|
# Sets the per-worker maximum concurrent connection establish process. All listeners
|
||||||
|
# will stop accepting connections when this limit is reached. It can be used to limit
|
||||||
|
# the global TLS CPU usage. By default max connections is set to a 256.
|
||||||
|
# Takes a string value: Either "default", or an integer N > 0 e.g. "6".
|
||||||
|
max-connection-rate = "default"
|
||||||
|
|
||||||
|
# Set server keep-alive preference. By default keep alive is set to 5 seconds.
|
||||||
|
# Takes a string value: Either "default", "disabled", "os",
|
||||||
|
# or a string of the format "N seconds" where N is an integer > 0 e.g. "6 seconds".
|
||||||
|
keep-alive = "default"
|
||||||
|
|
||||||
|
# Set server client timeout in milliseconds for first request. Defines a timeout
|
||||||
|
# for reading client request header. If a client does not transmit the entire set of
|
||||||
|
# headers within this time, the request is terminated with the 408 (Request Time-out)
|
||||||
|
# error. To disable timeout, set the value to 0.
|
||||||
|
# By default client timeout is set to 5000 milliseconds.
|
||||||
|
# Takes a string value: Either "default", or a string of the format "N milliseconds"
|
||||||
|
# where N is an integer > 0 e.g. "6 milliseconds".
|
||||||
|
client-timeout = "default"
|
||||||
|
|
||||||
|
# Set server connection shutdown timeout in milliseconds. Defines a timeout for
|
||||||
|
# shutdown connection. If a shutdown procedure does not complete within this time,
|
||||||
|
# the request is dropped. To disable timeout set value to 0.
|
||||||
|
# By default client timeout is set to 5000 milliseconds.
|
||||||
|
# Takes a string value: Either "default", or a string of the format "N milliseconds"
|
||||||
|
# where N is an integer > 0 e.g. "6 milliseconds".
|
||||||
|
client-shutdown = "default"
|
||||||
|
|
||||||
|
# Timeout for graceful workers shutdown. After receiving a stop signal, workers have
|
||||||
|
# this much time to finish serving requests. Workers still alive after the timeout
|
||||||
|
# are force dropped. By default shutdown timeout sets to 30 seconds.
|
||||||
|
# Takes a string value: Either "default", or a string of the format "N seconds"
|
||||||
|
# where N is an integer > 0 e.g. "6 seconds".
|
||||||
|
shutdown-timeout = "default"
|
||||||
|
|
||||||
|
[actix.tls] # TLS is disabled by default because the certs don't exist
|
||||||
|
enabled = false
|
||||||
|
certificate = "path/to/cert/cert.pem"
|
||||||
|
private-key = "path/to/cert/key.pem"
|
||||||
|
|
||||||
|
# The `application` table be used to express application-specific settings.
|
||||||
|
# See the `README.md` file for more details on how to use this.
|
||||||
|
[application]
|
72
actix-settings/src/defaults.toml
Normal file
72
actix-settings/src/defaults.toml
Normal file
@ -0,0 +1,72 @@
|
|||||||
|
[actix]
|
||||||
|
# For more info, see: https://docs.rs/actix-web/4/actix_web/struct.HttpServer.html.
|
||||||
|
|
||||||
|
hosts = [
|
||||||
|
["0.0.0.0", 9000] # This should work for both development and deployment...
|
||||||
|
# # ... but other entries are possible, as well.
|
||||||
|
]
|
||||||
|
mode = "development" # Either "development" or "production".
|
||||||
|
enable-compression = true # Toggle compression middleware.
|
||||||
|
enable-log = true # Toggle logging middleware.
|
||||||
|
|
||||||
|
# The number of workers that the server should start.
|
||||||
|
# By default the number of available logical cpu cores is used.
|
||||||
|
# Takes a string value: Either "default", or an integer N > 0 e.g. "6".
|
||||||
|
num-workers = "default"
|
||||||
|
|
||||||
|
# The maximum number of pending connections. This refers to the number of clients
|
||||||
|
# that can be waiting to be served. Exceeding this number results in the client
|
||||||
|
# getting an error when attempting to connect. It should only affect servers under
|
||||||
|
# significant load. Generally set in the 64-2048 range. The default value is 2048.
|
||||||
|
# Takes a string value: Either "default", or an integer N > 0 e.g. "6".
|
||||||
|
backlog = "default"
|
||||||
|
|
||||||
|
# Sets the per-worker maximum number of concurrent connections. All socket listeners
|
||||||
|
# will stop accepting connections when this limit is reached for each worker.
|
||||||
|
# By default max connections is set to a 25k.
|
||||||
|
# Takes a string value: Either "default", or an integer N > 0 e.g. "6".
|
||||||
|
max-connections = "default"
|
||||||
|
|
||||||
|
# Sets the per-worker maximum concurrent connection establish process. All listeners
|
||||||
|
# will stop accepting connections when this limit is reached. It can be used to limit
|
||||||
|
# the global TLS CPU usage. By default max connections is set to a 256.
|
||||||
|
# Takes a string value: Either "default", or an integer N > 0 e.g. "6".
|
||||||
|
max-connection-rate = "default"
|
||||||
|
|
||||||
|
# Set server keep-alive preference. By default keep alive is set to 5 seconds.
|
||||||
|
# Takes a string value: Either "default", "disabled", "os",
|
||||||
|
# or a string of the format "N seconds" where N is an integer > 0 e.g. "6 seconds".
|
||||||
|
keep-alive = "default"
|
||||||
|
|
||||||
|
# Set server client timeout in milliseconds for first request. Defines a timeout
|
||||||
|
# for reading client request header. If a client does not transmit the entire set of
|
||||||
|
# headers within this time, the request is terminated with the 408 (Request Time-out)
|
||||||
|
# error. To disable timeout, set the value to 0.
|
||||||
|
# By default client timeout is set to 5000 milliseconds.
|
||||||
|
# Takes a string value: Either "default", or a string of the format "N milliseconds"
|
||||||
|
# where N is an integer > 0 e.g. "6 milliseconds".
|
||||||
|
client-timeout = "default"
|
||||||
|
|
||||||
|
# Set server connection shutdown timeout in milliseconds. Defines a timeout for
|
||||||
|
# shutdown connection. If a shutdown procedure does not complete within this time,
|
||||||
|
# the request is dropped. To disable timeout set value to 0.
|
||||||
|
# By default client timeout is set to 5000 milliseconds.
|
||||||
|
# Takes a string value: Either "default", or a string of the format "N milliseconds"
|
||||||
|
# where N is an integer > 0 e.g. "6 milliseconds".
|
||||||
|
client-shutdown = "default"
|
||||||
|
|
||||||
|
# Timeout for graceful workers shutdown. After receiving a stop signal, workers have
|
||||||
|
# this much time to finish serving requests. Workers still alive after the timeout
|
||||||
|
# are force dropped. By default shutdown timeout sets to 30 seconds.
|
||||||
|
# Takes a string value: Either "default", or a string of the format "N seconds"
|
||||||
|
# where N is an integer > 0 e.g. "6 seconds".
|
||||||
|
shutdown-timeout = "default"
|
||||||
|
|
||||||
|
[actix.tls] # TLS is disabled by default because the certs don't exist
|
||||||
|
enabled = false
|
||||||
|
certificate = "path/to/cert/cert.pem"
|
||||||
|
private-key = "path/to/cert/key.pem"
|
||||||
|
|
||||||
|
# The `application` table be used to express application-specific settings.
|
||||||
|
# See the `README.md` file for more details on how to use this.
|
||||||
|
[application]
|
134
actix-settings/src/error.rs
Normal file
134
actix-settings/src/error.rs
Normal file
@ -0,0 +1,134 @@
|
|||||||
|
use std::{env::VarError, io, num::ParseIntError, path::PathBuf, str::ParseBoolError};
|
||||||
|
|
||||||
|
use derive_more::derive::{Display, Error};
|
||||||
|
#[cfg(feature = "openssl")]
|
||||||
|
use openssl::error::ErrorStack as OpenSSLError;
|
||||||
|
use toml::de::Error as TomlError;
|
||||||
|
|
||||||
|
/// Errors that can be returned from methods in this crate.
|
||||||
|
#[derive(Debug, Display, Error)]
|
||||||
|
pub enum Error {
|
||||||
|
/// Environment variable does not exists or is invalid.
|
||||||
|
#[display("Env var error: {_0}")]
|
||||||
|
EnvVarError(VarError),
|
||||||
|
|
||||||
|
/// File already exists on disk.
|
||||||
|
#[display("File exists: {}", _0.display())]
|
||||||
|
FileExists(#[error(not(source))] PathBuf),
|
||||||
|
|
||||||
|
/// Invalid value.
|
||||||
|
#[allow(missing_docs)]
|
||||||
|
#[display("Expected {expected}, got {got} (@ {file}:{line}:{column})")]
|
||||||
|
InvalidValue {
|
||||||
|
expected: &'static str,
|
||||||
|
got: String,
|
||||||
|
file: &'static str,
|
||||||
|
line: u32,
|
||||||
|
column: u32,
|
||||||
|
},
|
||||||
|
|
||||||
|
/// I/O error.
|
||||||
|
#[display("I/O error: {_0}")]
|
||||||
|
IoError(io::Error),
|
||||||
|
|
||||||
|
/// OpenSSL Error.
|
||||||
|
#[cfg(feature = "openssl")]
|
||||||
|
#[display("OpenSSL error: {_0}")]
|
||||||
|
OpenSSLError(OpenSSLError),
|
||||||
|
|
||||||
|
/// Value is not a boolean.
|
||||||
|
#[display("Failed to parse boolean: {_0}")]
|
||||||
|
ParseBoolError(ParseBoolError),
|
||||||
|
|
||||||
|
/// Value is not an integer.
|
||||||
|
#[display("Failed to parse integer: {_0}")]
|
||||||
|
ParseIntError(ParseIntError),
|
||||||
|
|
||||||
|
/// Value is not an address.
|
||||||
|
#[display("Failed to parse address: {_0}")]
|
||||||
|
ParseAddressError(#[error(not(source))] String),
|
||||||
|
|
||||||
|
/// Error deserializing as TOML.
|
||||||
|
#[display("TOML error: {_0}")]
|
||||||
|
TomlError(TomlError),
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! InvalidValue {
|
||||||
|
(expected: $expected:expr, got: $got:expr,) => {
|
||||||
|
crate::Error::InvalidValue {
|
||||||
|
expected: $expected,
|
||||||
|
got: $got.to_string(),
|
||||||
|
file: file!(),
|
||||||
|
line: line!(),
|
||||||
|
column: column!(),
|
||||||
|
}
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<io::Error> for Error {
|
||||||
|
fn from(err: io::Error) -> Self {
|
||||||
|
Self::IoError(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "openssl")]
|
||||||
|
impl From<OpenSSLError> for Error {
|
||||||
|
fn from(err: OpenSSLError) -> Self {
|
||||||
|
Self::OpenSSLError(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<ParseBoolError> for Error {
|
||||||
|
fn from(err: ParseBoolError) -> Self {
|
||||||
|
Self::ParseBoolError(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<ParseIntError> for Error {
|
||||||
|
fn from(err: ParseIntError) -> Self {
|
||||||
|
Self::ParseIntError(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<TomlError> for Error {
|
||||||
|
fn from(err: TomlError) -> Self {
|
||||||
|
Self::TomlError(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<VarError> for Error {
|
||||||
|
fn from(err: VarError) -> Self {
|
||||||
|
Self::EnvVarError(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl From<Error> for io::Error {
|
||||||
|
fn from(err: Error) -> Self {
|
||||||
|
match err {
|
||||||
|
Error::EnvVarError(_) => io::Error::new(io::ErrorKind::InvalidInput, err.to_string()),
|
||||||
|
|
||||||
|
Error::FileExists(_) => io::Error::new(io::ErrorKind::AlreadyExists, err.to_string()),
|
||||||
|
|
||||||
|
Error::InvalidValue { .. } => {
|
||||||
|
io::Error::new(io::ErrorKind::InvalidInput, err.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
Error::IoError(io_error) => io_error,
|
||||||
|
|
||||||
|
#[cfg(feature = "openssl")]
|
||||||
|
Error::OpenSSLError(ossl_error) => io::Error::new(io::ErrorKind::Other, ossl_error),
|
||||||
|
|
||||||
|
Error::ParseBoolError(_) => {
|
||||||
|
io::Error::new(io::ErrorKind::InvalidInput, err.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
Error::ParseIntError(_) => io::Error::new(io::ErrorKind::InvalidInput, err.to_string()),
|
||||||
|
|
||||||
|
Error::ParseAddressError(_) => {
|
||||||
|
io::Error::new(io::ErrorKind::InvalidInput, err.to_string())
|
||||||
|
}
|
||||||
|
|
||||||
|
Error::TomlError(_) => io::Error::new(io::ErrorKind::InvalidInput, err.to_string()),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
860
actix-settings/src/lib.rs
Normal file
860
actix-settings/src/lib.rs
Normal file
@ -0,0 +1,860 @@
|
|||||||
|
//! Easily manage Actix Web's settings from a TOML file and environment variables.
|
||||||
|
//!
|
||||||
|
//! To get started add a [`Settings::parse_toml("./Server.toml")`](Settings::parse_toml) call to the
|
||||||
|
//! top of your main function. This will create a template file with descriptions of all the
|
||||||
|
//! configurable settings. You can change or remove anything in that file and it will be picked up
|
||||||
|
//! the next time you run your application.
|
||||||
|
//!
|
||||||
|
//! Overriding parts of the file can be done from values using [`Settings::override_field`] or from
|
||||||
|
//! the environment using [`Settings::override_field_with_env_var`].
|
||||||
|
//!
|
||||||
|
//! # Examples
|
||||||
|
//!
|
||||||
|
//! See examples folder on GitHub for complete example.
|
||||||
|
//!
|
||||||
|
//! ```ignore
|
||||||
|
//! # use actix_web::{
|
||||||
|
//! # get,
|
||||||
|
//! # middleware::{Compress, Condition, Logger},
|
||||||
|
//! # web, App, HttpServer,
|
||||||
|
//! # };
|
||||||
|
//! use actix_settings::{ApplySettings as _, Mode, Settings};
|
||||||
|
//!
|
||||||
|
//! #[actix_web::main]
|
||||||
|
//! async fn main() -> std::io::Result<()> {
|
||||||
|
//! let mut settings = Settings::parse_toml("./Server.toml")
|
||||||
|
//! .expect("Failed to parse `Settings` from Server.toml");
|
||||||
|
//!
|
||||||
|
//! // If the environment variable `$APPLICATION__HOSTS` is set,
|
||||||
|
//! // have its value override the `settings.actix.hosts` setting:
|
||||||
|
//! Settings::override_field_with_env_var(&mut settings.actix.hosts, "APPLICATION__HOSTS")?;
|
||||||
|
//!
|
||||||
|
//! init_logger(&settings);
|
||||||
|
//!
|
||||||
|
//! HttpServer::new({
|
||||||
|
//! // clone settings into each worker thread
|
||||||
|
//! let settings = settings.clone();
|
||||||
|
//!
|
||||||
|
//! move || {
|
||||||
|
//! App::new()
|
||||||
|
//! // Include this `.wrap()` call for compression settings to take effect
|
||||||
|
//! .wrap(Condition::new(
|
||||||
|
//! settings.actix.enable_compression,
|
||||||
|
//! Compress::default(),
|
||||||
|
//! ))
|
||||||
|
//!
|
||||||
|
//! // add request logger
|
||||||
|
//! .wrap(Logger::default())
|
||||||
|
//!
|
||||||
|
//! // make `Settings` available to handlers
|
||||||
|
//! .app_data(web::Data::new(settings.clone()))
|
||||||
|
//!
|
||||||
|
//! // add request handlers as normal
|
||||||
|
//! .service(index)
|
||||||
|
//! }
|
||||||
|
//! })
|
||||||
|
//! // apply the `Settings` to Actix Web's `HttpServer`
|
||||||
|
//! .try_apply_settings(&settings)?
|
||||||
|
//! .run()
|
||||||
|
//! .await
|
||||||
|
//! }
|
||||||
|
//! ```
|
||||||
|
|
||||||
|
#![forbid(unsafe_code)]
|
||||||
|
#![warn(missing_docs, missing_debug_implementations)]
|
||||||
|
#![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))]
|
||||||
|
|
||||||
|
use std::{
|
||||||
|
env, fmt,
|
||||||
|
fs::File,
|
||||||
|
io::{Read as _, Write as _},
|
||||||
|
path::Path,
|
||||||
|
time::Duration,
|
||||||
|
};
|
||||||
|
|
||||||
|
use actix_http::{Request, Response};
|
||||||
|
use actix_service::IntoServiceFactory;
|
||||||
|
use actix_web::{
|
||||||
|
body::MessageBody,
|
||||||
|
dev::{AppConfig, ServiceFactory},
|
||||||
|
http::KeepAlive as ActixKeepAlive,
|
||||||
|
Error as WebError, HttpServer,
|
||||||
|
};
|
||||||
|
use serde::{de, Deserialize};
|
||||||
|
|
||||||
|
#[macro_use]
|
||||||
|
mod error;
|
||||||
|
mod parse;
|
||||||
|
mod settings;
|
||||||
|
|
||||||
|
#[cfg(feature = "openssl")]
|
||||||
|
pub use self::settings::Tls;
|
||||||
|
pub use self::{
|
||||||
|
error::Error,
|
||||||
|
parse::Parse,
|
||||||
|
settings::{
|
||||||
|
ActixSettings, Address, Backlog, KeepAlive, MaxConnectionRate, MaxConnections, Mode,
|
||||||
|
NumWorkers, Timeout,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
/// Convenience type alias for `Result<T, AtError>`.
|
||||||
|
type AsResult<T> = std::result::Result<T, Error>;
|
||||||
|
|
||||||
|
/// Wrapper for server and application-specific settings.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
|
||||||
|
#[serde(bound = "A: Deserialize<'de>")]
|
||||||
|
pub struct BasicSettings<A> {
|
||||||
|
/// Actix Web server settings.
|
||||||
|
pub actix: ActixSettings,
|
||||||
|
|
||||||
|
/// Application-specific settings.
|
||||||
|
pub application: A,
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Convenience type alias for [`BasicSettings`] with no defined application-specific settings.
|
||||||
|
pub type Settings = BasicSettings<NoSettings>;
|
||||||
|
|
||||||
|
/// Marker type representing no defined application-specific settings.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
|
||||||
|
#[non_exhaustive]
|
||||||
|
pub struct NoSettings {/* NOTE: turning this into a unit struct will cause deserialization failures. */}
|
||||||
|
|
||||||
|
impl<A> BasicSettings<A>
|
||||||
|
where
|
||||||
|
A: de::DeserializeOwned,
|
||||||
|
{
|
||||||
|
// NOTE **DO NOT** mess with the ordering of the tables in the default template.
|
||||||
|
// Especially the `[application]` table needs to be last in order
|
||||||
|
// for some tests to keep working.
|
||||||
|
/// Default settings file contents.
|
||||||
|
pub(crate) const DEFAULT_TOML_TEMPLATE: &'static str = include_str!("./defaults.toml");
|
||||||
|
|
||||||
|
/// Parse an instance of `Self` from a TOML file located at `filepath`.
|
||||||
|
///
|
||||||
|
/// If the file doesn't exist, it is generated from the default TOML template, after which the
|
||||||
|
/// newly generated file is read in and parsed.
|
||||||
|
pub fn parse_toml<P>(filepath: P) -> AsResult<Self>
|
||||||
|
where
|
||||||
|
P: AsRef<Path>,
|
||||||
|
{
|
||||||
|
let filepath = filepath.as_ref();
|
||||||
|
|
||||||
|
if !filepath.exists() {
|
||||||
|
Self::write_toml_file(filepath)?;
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut f = File::open(filepath)?;
|
||||||
|
let len_guess = f.metadata().map(|md| md.len()).unwrap_or(128);
|
||||||
|
|
||||||
|
let mut contents = String::with_capacity(len_guess as usize);
|
||||||
|
f.read_to_string(&mut contents)?;
|
||||||
|
|
||||||
|
Ok(toml::from_str::<Self>(&contents)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse an instance of `Self` straight from the default TOML template.
|
||||||
|
pub fn from_default_template() -> Self {
|
||||||
|
Self::from_template(Self::DEFAULT_TOML_TEMPLATE).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Parse an instance of `Self` straight from the default TOML template.
|
||||||
|
pub fn from_template(template: &str) -> AsResult<Self> {
|
||||||
|
Ok(toml::from_str(template)?)
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Writes the default TOML template to a new file, located at `filepath`.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// Returns a [`FileExists`](crate::Error::FileExists) error if a file already exists at that
|
||||||
|
/// location.
|
||||||
|
pub fn write_toml_file<P>(filepath: P) -> AsResult<()>
|
||||||
|
where
|
||||||
|
P: AsRef<Path>,
|
||||||
|
{
|
||||||
|
let filepath = filepath.as_ref();
|
||||||
|
|
||||||
|
if filepath.exists() {
|
||||||
|
return Err(Error::FileExists(filepath.to_path_buf()));
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut file = File::create(filepath)?;
|
||||||
|
file.write_all(Self::DEFAULT_TOML_TEMPLATE.trim().as_bytes())?;
|
||||||
|
file.flush()?;
|
||||||
|
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Attempts to parse `value` and override the referenced `field`.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
/// ```
|
||||||
|
/// use actix_settings::{Settings, Mode};
|
||||||
|
///
|
||||||
|
/// # fn inner() -> Result<(), actix_settings::Error> {
|
||||||
|
/// let mut settings = Settings::from_default_template();
|
||||||
|
/// assert_eq!(settings.actix.mode, Mode::Development);
|
||||||
|
///
|
||||||
|
/// Settings::override_field(&mut settings.actix.mode, "production")?;
|
||||||
|
/// assert_eq!(settings.actix.mode, Mode::Production);
|
||||||
|
/// # Ok(()) }
|
||||||
|
/// ```
|
||||||
|
pub fn override_field<F, V>(field: &mut F, value: V) -> AsResult<()>
|
||||||
|
where
|
||||||
|
F: Parse,
|
||||||
|
V: AsRef<str>,
|
||||||
|
{
|
||||||
|
*field = F::parse(value.as_ref())?;
|
||||||
|
Ok(())
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Attempts to read an environment variable, parse it, and override the referenced `field`.
|
||||||
|
///
|
||||||
|
/// # Examples
|
||||||
|
/// ```
|
||||||
|
/// use actix_settings::{Settings, Mode};
|
||||||
|
///
|
||||||
|
/// std::env::set_var("OVERRIDE__MODE", "production");
|
||||||
|
///
|
||||||
|
/// # fn inner() -> Result<(), actix_settings::Error> {
|
||||||
|
/// let mut settings = Settings::from_default_template();
|
||||||
|
/// assert_eq!(settings.actix.mode, Mode::Development);
|
||||||
|
///
|
||||||
|
/// Settings::override_field_with_env_var(&mut settings.actix.mode, "OVERRIDE__MODE")?;
|
||||||
|
/// assert_eq!(settings.actix.mode, Mode::Production);
|
||||||
|
/// # Ok(()) }
|
||||||
|
/// ```
|
||||||
|
pub fn override_field_with_env_var<F, N>(field: &mut F, var_name: N) -> AsResult<()>
|
||||||
|
where
|
||||||
|
F: Parse,
|
||||||
|
N: AsRef<str>,
|
||||||
|
{
|
||||||
|
match env::var(var_name.as_ref()) {
|
||||||
|
Err(env::VarError::NotPresent) => Ok((/*NOP*/)),
|
||||||
|
Err(var_error) => Err(Error::from(var_error)),
|
||||||
|
Ok(value) => Self::override_field(field, value),
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Extension trait for applying parsed settings to the server object.
|
||||||
|
pub trait ApplySettings<S>: Sized {
|
||||||
|
/// Applies some settings object value to `self`.
|
||||||
|
///
|
||||||
|
/// The default implementation calls [`try_apply_settings()`].
|
||||||
|
///
|
||||||
|
/// # Panics
|
||||||
|
///
|
||||||
|
/// May panic if settings are invalid or cannot be applied.
|
||||||
|
///
|
||||||
|
/// [`try_apply_settings()`]: ApplySettings::try_apply_settings().
|
||||||
|
#[deprecated = "Prefer `try_apply_settings()`."]
|
||||||
|
fn apply_settings(self, settings: &S) -> Self {
|
||||||
|
self.try_apply_settings(settings)
|
||||||
|
.expect("Could not apply settings")
|
||||||
|
}
|
||||||
|
|
||||||
|
/// Applies some settings object value to `self`.
|
||||||
|
///
|
||||||
|
/// # Errors
|
||||||
|
///
|
||||||
|
/// May return error if settings are invalid or cannot be applied.
|
||||||
|
fn try_apply_settings(self, settings: &S) -> AsResult<Self>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<F, I, S, B> ApplySettings<ActixSettings> for HttpServer<F, I, S, B>
|
||||||
|
where
|
||||||
|
F: Fn() -> I + Send + Clone + 'static,
|
||||||
|
I: IntoServiceFactory<S, Request>,
|
||||||
|
S: ServiceFactory<Request, Config = AppConfig> + 'static,
|
||||||
|
S::Error: Into<WebError> + 'static,
|
||||||
|
S::InitError: fmt::Debug,
|
||||||
|
S::Response: Into<Response<B>> + 'static,
|
||||||
|
S::Future: 'static,
|
||||||
|
B: MessageBody + 'static,
|
||||||
|
{
|
||||||
|
fn apply_settings(self, settings: &ActixSettings) -> Self {
|
||||||
|
self.try_apply_settings(settings).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_apply_settings(mut self, settings: &ActixSettings) -> AsResult<Self> {
|
||||||
|
for Address { host, port } in &settings.hosts {
|
||||||
|
#[cfg(feature = "openssl")]
|
||||||
|
{
|
||||||
|
if settings.tls.enabled {
|
||||||
|
self = self.bind_openssl(
|
||||||
|
format!("{}:{}", host, port),
|
||||||
|
settings.tls.get_ssl_acceptor_builder()?,
|
||||||
|
)?;
|
||||||
|
} else {
|
||||||
|
self = self.bind(format!("{host}:{port}"))?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(not(feature = "openssl"))]
|
||||||
|
{
|
||||||
|
self = self.bind(format!("{host}:{port}"))?;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
self = match settings.num_workers {
|
||||||
|
NumWorkers::Default => self,
|
||||||
|
NumWorkers::Manual(n) => self.workers(n),
|
||||||
|
};
|
||||||
|
|
||||||
|
self = match settings.backlog {
|
||||||
|
Backlog::Default => self,
|
||||||
|
Backlog::Manual(n) => self.backlog(n as u32),
|
||||||
|
};
|
||||||
|
|
||||||
|
self = match settings.max_connections {
|
||||||
|
MaxConnections::Default => self,
|
||||||
|
MaxConnections::Manual(n) => self.max_connections(n),
|
||||||
|
};
|
||||||
|
|
||||||
|
self = match settings.max_connection_rate {
|
||||||
|
MaxConnectionRate::Default => self,
|
||||||
|
MaxConnectionRate::Manual(n) => self.max_connection_rate(n),
|
||||||
|
};
|
||||||
|
|
||||||
|
self = match settings.keep_alive {
|
||||||
|
KeepAlive::Default => self,
|
||||||
|
KeepAlive::Disabled => self.keep_alive(ActixKeepAlive::Disabled),
|
||||||
|
KeepAlive::Os => self.keep_alive(ActixKeepAlive::Os),
|
||||||
|
KeepAlive::Seconds(n) => self.keep_alive(Duration::from_secs(n as u64)),
|
||||||
|
};
|
||||||
|
|
||||||
|
self = match settings.client_timeout {
|
||||||
|
Timeout::Default => self,
|
||||||
|
Timeout::Milliseconds(n) => {
|
||||||
|
self.client_request_timeout(Duration::from_millis(n as u64))
|
||||||
|
}
|
||||||
|
Timeout::Seconds(n) => self.client_request_timeout(Duration::from_secs(n as u64)),
|
||||||
|
};
|
||||||
|
|
||||||
|
self = match settings.client_shutdown {
|
||||||
|
Timeout::Default => self,
|
||||||
|
Timeout::Milliseconds(n) => {
|
||||||
|
self.client_disconnect_timeout(Duration::from_millis(n as u64))
|
||||||
|
}
|
||||||
|
Timeout::Seconds(n) => self.client_disconnect_timeout(Duration::from_secs(n as u64)),
|
||||||
|
};
|
||||||
|
|
||||||
|
self = match settings.shutdown_timeout {
|
||||||
|
Timeout::Default => self,
|
||||||
|
Timeout::Milliseconds(_) => self.shutdown_timeout(1),
|
||||||
|
Timeout::Seconds(n) => self.shutdown_timeout(n as u64),
|
||||||
|
};
|
||||||
|
|
||||||
|
Ok(self)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl<F, I, S, B, A> ApplySettings<BasicSettings<A>> for HttpServer<F, I, S, B>
|
||||||
|
where
|
||||||
|
F: Fn() -> I + Send + Clone + 'static,
|
||||||
|
I: IntoServiceFactory<S, Request>,
|
||||||
|
S: ServiceFactory<Request, Config = AppConfig> + 'static,
|
||||||
|
S::Error: Into<WebError> + 'static,
|
||||||
|
S::InitError: fmt::Debug,
|
||||||
|
S::Response: Into<Response<B>> + 'static,
|
||||||
|
S::Future: 'static,
|
||||||
|
B: MessageBody + 'static,
|
||||||
|
A: de::DeserializeOwned,
|
||||||
|
{
|
||||||
|
fn apply_settings(self, settings: &BasicSettings<A>) -> Self {
|
||||||
|
self.try_apply_settings(&settings.actix).unwrap()
|
||||||
|
}
|
||||||
|
|
||||||
|
fn try_apply_settings(self, settings: &BasicSettings<A>) -> AsResult<Self> {
|
||||||
|
self.try_apply_settings(&settings.actix)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(test)]
|
||||||
|
mod tests {
|
||||||
|
use actix_web::App;
|
||||||
|
|
||||||
|
use super::*;
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn apply_settings() {
|
||||||
|
let settings = Settings::parse_toml("Server.toml").unwrap();
|
||||||
|
let server = HttpServer::new(App::new).try_apply_settings(&settings);
|
||||||
|
assert!(server.is_ok());
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_hosts() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
settings.actix.hosts,
|
||||||
|
vec![Address {
|
||||||
|
host: "0.0.0.0".into(),
|
||||||
|
port: 9000
|
||||||
|
},]
|
||||||
|
);
|
||||||
|
|
||||||
|
Settings::override_field(
|
||||||
|
&mut settings.actix.hosts,
|
||||||
|
r#"[
|
||||||
|
["0.0.0.0", 1234],
|
||||||
|
["localhost", 2345]
|
||||||
|
]"#,
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
settings.actix.hosts,
|
||||||
|
vec![
|
||||||
|
Address {
|
||||||
|
host: "0.0.0.0".into(),
|
||||||
|
port: 1234
|
||||||
|
},
|
||||||
|
Address {
|
||||||
|
host: "localhost".into(),
|
||||||
|
port: 2345
|
||||||
|
},
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_with_env_var_hosts() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
settings.actix.hosts,
|
||||||
|
vec![Address {
|
||||||
|
host: "0.0.0.0".into(),
|
||||||
|
port: 9000
|
||||||
|
},]
|
||||||
|
);
|
||||||
|
|
||||||
|
std::env::set_var(
|
||||||
|
"OVERRIDE__HOSTS",
|
||||||
|
r#"[
|
||||||
|
["0.0.0.0", 1234],
|
||||||
|
["localhost", 2345]
|
||||||
|
]"#,
|
||||||
|
);
|
||||||
|
|
||||||
|
Settings::override_field_with_env_var(&mut settings.actix.hosts, "OVERRIDE__HOSTS")
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
settings.actix.hosts,
|
||||||
|
vec![
|
||||||
|
Address {
|
||||||
|
host: "0.0.0.0".into(),
|
||||||
|
port: 1234
|
||||||
|
},
|
||||||
|
Address {
|
||||||
|
host: "localhost".into(),
|
||||||
|
port: 2345
|
||||||
|
},
|
||||||
|
]
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_mode() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert_eq!(settings.actix.mode, Mode::Development);
|
||||||
|
Settings::override_field(&mut settings.actix.mode, "production").unwrap();
|
||||||
|
assert_eq!(settings.actix.mode, Mode::Production);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_with_env_var_mode() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert_eq!(settings.actix.mode, Mode::Development);
|
||||||
|
std::env::set_var("OVERRIDE__MODE", "production");
|
||||||
|
Settings::override_field_with_env_var(&mut settings.actix.mode, "OVERRIDE__MODE").unwrap();
|
||||||
|
assert_eq!(settings.actix.mode, Mode::Production);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_enable_compression() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert!(settings.actix.enable_compression);
|
||||||
|
Settings::override_field(&mut settings.actix.enable_compression, "false").unwrap();
|
||||||
|
assert!(!settings.actix.enable_compression);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_with_env_var_enable_compression() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert!(settings.actix.enable_compression);
|
||||||
|
std::env::set_var("OVERRIDE__ENABLE_COMPRESSION", "false");
|
||||||
|
Settings::override_field_with_env_var(
|
||||||
|
&mut settings.actix.enable_compression,
|
||||||
|
"OVERRIDE__ENABLE_COMPRESSION",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(!settings.actix.enable_compression);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_enable_log() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert!(settings.actix.enable_log);
|
||||||
|
Settings::override_field(&mut settings.actix.enable_log, "false").unwrap();
|
||||||
|
assert!(!settings.actix.enable_log);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_with_env_var_enable_log() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert!(settings.actix.enable_log);
|
||||||
|
std::env::set_var("OVERRIDE__ENABLE_LOG", "false");
|
||||||
|
Settings::override_field_with_env_var(
|
||||||
|
&mut settings.actix.enable_log,
|
||||||
|
"OVERRIDE__ENABLE_LOG",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(!settings.actix.enable_log);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_num_workers() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert_eq!(settings.actix.num_workers, NumWorkers::Default);
|
||||||
|
Settings::override_field(&mut settings.actix.num_workers, "42").unwrap();
|
||||||
|
assert_eq!(settings.actix.num_workers, NumWorkers::Manual(42));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_with_env_var_num_workers() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert_eq!(settings.actix.num_workers, NumWorkers::Default);
|
||||||
|
std::env::set_var("OVERRIDE__NUM_WORKERS", "42");
|
||||||
|
Settings::override_field_with_env_var(
|
||||||
|
&mut settings.actix.num_workers,
|
||||||
|
"OVERRIDE__NUM_WORKERS",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(settings.actix.num_workers, NumWorkers::Manual(42));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_backlog() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert_eq!(settings.actix.backlog, Backlog::Default);
|
||||||
|
Settings::override_field(&mut settings.actix.backlog, "42").unwrap();
|
||||||
|
assert_eq!(settings.actix.backlog, Backlog::Manual(42));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_with_env_var_backlog() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert_eq!(settings.actix.backlog, Backlog::Default);
|
||||||
|
std::env::set_var("OVERRIDE__BACKLOG", "42");
|
||||||
|
Settings::override_field_with_env_var(&mut settings.actix.backlog, "OVERRIDE__BACKLOG")
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(settings.actix.backlog, Backlog::Manual(42));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_max_connections() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert_eq!(settings.actix.max_connections, MaxConnections::Default);
|
||||||
|
Settings::override_field(&mut settings.actix.max_connections, "42").unwrap();
|
||||||
|
assert_eq!(settings.actix.max_connections, MaxConnections::Manual(42));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_with_env_var_max_connections() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert_eq!(settings.actix.max_connections, MaxConnections::Default);
|
||||||
|
std::env::set_var("OVERRIDE__MAX_CONNECTIONS", "42");
|
||||||
|
Settings::override_field_with_env_var(
|
||||||
|
&mut settings.actix.max_connections,
|
||||||
|
"OVERRIDE__MAX_CONNECTIONS",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(settings.actix.max_connections, MaxConnections::Manual(42));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_max_connection_rate() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert_eq!(
|
||||||
|
settings.actix.max_connection_rate,
|
||||||
|
MaxConnectionRate::Default
|
||||||
|
);
|
||||||
|
Settings::override_field(&mut settings.actix.max_connection_rate, "42").unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
settings.actix.max_connection_rate,
|
||||||
|
MaxConnectionRate::Manual(42)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_with_env_var_max_connection_rate() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert_eq!(
|
||||||
|
settings.actix.max_connection_rate,
|
||||||
|
MaxConnectionRate::Default
|
||||||
|
);
|
||||||
|
std::env::set_var("OVERRIDE__MAX_CONNECTION_RATE", "42");
|
||||||
|
Settings::override_field_with_env_var(
|
||||||
|
&mut settings.actix.max_connection_rate,
|
||||||
|
"OVERRIDE__MAX_CONNECTION_RATE",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
settings.actix.max_connection_rate,
|
||||||
|
MaxConnectionRate::Manual(42)
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_keep_alive() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert_eq!(settings.actix.keep_alive, KeepAlive::Default);
|
||||||
|
Settings::override_field(&mut settings.actix.keep_alive, "42 seconds").unwrap();
|
||||||
|
assert_eq!(settings.actix.keep_alive, KeepAlive::Seconds(42));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_with_env_var_keep_alive() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert_eq!(settings.actix.keep_alive, KeepAlive::Default);
|
||||||
|
std::env::set_var("OVERRIDE__KEEP_ALIVE", "42 seconds");
|
||||||
|
Settings::override_field_with_env_var(
|
||||||
|
&mut settings.actix.keep_alive,
|
||||||
|
"OVERRIDE__KEEP_ALIVE",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(settings.actix.keep_alive, KeepAlive::Seconds(42));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_client_timeout() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert_eq!(settings.actix.client_timeout, Timeout::Default);
|
||||||
|
Settings::override_field(&mut settings.actix.client_timeout, "42 seconds").unwrap();
|
||||||
|
assert_eq!(settings.actix.client_timeout, Timeout::Seconds(42));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_with_env_var_client_timeout() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert_eq!(settings.actix.client_timeout, Timeout::Default);
|
||||||
|
std::env::set_var("OVERRIDE__CLIENT_TIMEOUT", "42 seconds");
|
||||||
|
Settings::override_field_with_env_var(
|
||||||
|
&mut settings.actix.client_timeout,
|
||||||
|
"OVERRIDE__CLIENT_TIMEOUT",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(settings.actix.client_timeout, Timeout::Seconds(42));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_client_shutdown() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert_eq!(settings.actix.client_shutdown, Timeout::Default);
|
||||||
|
Settings::override_field(&mut settings.actix.client_shutdown, "42 seconds").unwrap();
|
||||||
|
assert_eq!(settings.actix.client_shutdown, Timeout::Seconds(42));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_with_env_var_client_shutdown() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert_eq!(settings.actix.client_shutdown, Timeout::Default);
|
||||||
|
std::env::set_var("OVERRIDE__CLIENT_SHUTDOWN", "42 seconds");
|
||||||
|
Settings::override_field_with_env_var(
|
||||||
|
&mut settings.actix.client_shutdown,
|
||||||
|
"OVERRIDE__CLIENT_SHUTDOWN",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(settings.actix.client_shutdown, Timeout::Seconds(42));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_shutdown_timeout() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert_eq!(settings.actix.shutdown_timeout, Timeout::Default);
|
||||||
|
Settings::override_field(&mut settings.actix.shutdown_timeout, "42 seconds").unwrap();
|
||||||
|
assert_eq!(settings.actix.shutdown_timeout, Timeout::Seconds(42));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_field_with_env_var_shutdown_timeout() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert_eq!(settings.actix.shutdown_timeout, Timeout::Default);
|
||||||
|
std::env::set_var("OVERRIDE__SHUTDOWN_TIMEOUT", "42 seconds");
|
||||||
|
Settings::override_field_with_env_var(
|
||||||
|
&mut settings.actix.shutdown_timeout,
|
||||||
|
"OVERRIDE__SHUTDOWN_TIMEOUT",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(settings.actix.shutdown_timeout, Timeout::Seconds(42));
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "openssl")]
|
||||||
|
#[test]
|
||||||
|
fn override_field_tls_enabled() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert!(!settings.actix.tls.enabled);
|
||||||
|
Settings::override_field(&mut settings.actix.tls.enabled, "true").unwrap();
|
||||||
|
assert!(settings.actix.tls.enabled);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "openssl")]
|
||||||
|
#[test]
|
||||||
|
fn override_field_with_env_var_tls_enabled() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert!(!settings.actix.tls.enabled);
|
||||||
|
std::env::set_var("OVERRIDE__TLS_ENABLED", "true");
|
||||||
|
Settings::override_field_with_env_var(
|
||||||
|
&mut settings.actix.tls.enabled,
|
||||||
|
"OVERRIDE__TLS_ENABLED",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert!(settings.actix.tls.enabled);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "openssl")]
|
||||||
|
#[test]
|
||||||
|
fn override_field_tls_certificate() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert_eq!(
|
||||||
|
settings.actix.tls.certificate,
|
||||||
|
Path::new("path/to/cert/cert.pem")
|
||||||
|
);
|
||||||
|
Settings::override_field(
|
||||||
|
&mut settings.actix.tls.certificate,
|
||||||
|
"/overridden/path/to/cert/cert.pem",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
settings.actix.tls.certificate,
|
||||||
|
Path::new("/overridden/path/to/cert/cert.pem")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "openssl")]
|
||||||
|
#[test]
|
||||||
|
fn override_field_with_env_var_tls_certificate() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert_eq!(
|
||||||
|
settings.actix.tls.certificate,
|
||||||
|
Path::new("path/to/cert/cert.pem")
|
||||||
|
);
|
||||||
|
std::env::set_var(
|
||||||
|
"OVERRIDE__TLS_CERTIFICATE",
|
||||||
|
"/overridden/path/to/cert/cert.pem",
|
||||||
|
);
|
||||||
|
Settings::override_field_with_env_var(
|
||||||
|
&mut settings.actix.tls.certificate,
|
||||||
|
"OVERRIDE__TLS_CERTIFICATE",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
settings.actix.tls.certificate,
|
||||||
|
Path::new("/overridden/path/to/cert/cert.pem")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "openssl")]
|
||||||
|
#[test]
|
||||||
|
fn override_field_tls_private_key() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert_eq!(
|
||||||
|
settings.actix.tls.private_key,
|
||||||
|
Path::new("path/to/cert/key.pem")
|
||||||
|
);
|
||||||
|
Settings::override_field(
|
||||||
|
&mut settings.actix.tls.private_key,
|
||||||
|
"/overridden/path/to/cert/key.pem",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
settings.actix.tls.private_key,
|
||||||
|
Path::new("/overridden/path/to/cert/key.pem")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[cfg(feature = "openssl")]
|
||||||
|
#[test]
|
||||||
|
fn override_field_with_env_var_tls_private_key() {
|
||||||
|
let mut settings = Settings::from_default_template();
|
||||||
|
assert_eq!(
|
||||||
|
settings.actix.tls.private_key,
|
||||||
|
Path::new("path/to/cert/key.pem")
|
||||||
|
);
|
||||||
|
std::env::set_var(
|
||||||
|
"OVERRIDE__TLS_PRIVATE_KEY",
|
||||||
|
"/overridden/path/to/cert/key.pem",
|
||||||
|
);
|
||||||
|
Settings::override_field_with_env_var(
|
||||||
|
&mut settings.actix.tls.private_key,
|
||||||
|
"OVERRIDE__TLS_PRIVATE_KEY",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
assert_eq!(
|
||||||
|
settings.actix.tls.private_key,
|
||||||
|
Path::new("/overridden/path/to/cert/key.pem")
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
#[test]
|
||||||
|
fn override_extended_field_with_custom_type() {
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||||
|
struct NestedSetting {
|
||||||
|
foo: String,
|
||||||
|
bar: bool,
|
||||||
|
}
|
||||||
|
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
|
||||||
|
#[serde(rename_all = "kebab-case")]
|
||||||
|
struct AppSettings {
|
||||||
|
example_name: String,
|
||||||
|
nested_field: NestedSetting,
|
||||||
|
}
|
||||||
|
|
||||||
|
type CustomSettings = BasicSettings<AppSettings>;
|
||||||
|
|
||||||
|
let mut settings = CustomSettings::from_template(
|
||||||
|
&(CustomSettings::DEFAULT_TOML_TEMPLATE.to_string()
|
||||||
|
// NOTE: Add these entries to the `[application]` table:
|
||||||
|
+ "\nexample-name = \"example value\""
|
||||||
|
+ "\nnested-field = { foo = \"foo\", bar = false }"),
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
settings.application,
|
||||||
|
AppSettings {
|
||||||
|
example_name: "example value".into(),
|
||||||
|
nested_field: NestedSetting {
|
||||||
|
foo: "foo".into(),
|
||||||
|
bar: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
|
||||||
|
CustomSettings::override_field(
|
||||||
|
&mut settings.application.example_name,
|
||||||
|
"/overridden/path/to/cert/key.pem",
|
||||||
|
)
|
||||||
|
.unwrap();
|
||||||
|
|
||||||
|
assert_eq!(
|
||||||
|
settings.application,
|
||||||
|
AppSettings {
|
||||||
|
example_name: "/overridden/path/to/cert/key.pem".into(),
|
||||||
|
nested_field: NestedSetting {
|
||||||
|
foo: "foo".into(),
|
||||||
|
bar: false,
|
||||||
|
},
|
||||||
|
}
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
40
actix-settings/src/parse.rs
Normal file
40
actix-settings/src/parse.rs
Normal file
@ -0,0 +1,40 @@
|
|||||||
|
use std::{path::PathBuf, str::FromStr};
|
||||||
|
|
||||||
|
use crate::Error;
|
||||||
|
|
||||||
|
/// A specialized `FromStr` trait that returns [`Error`] errors
|
||||||
|
pub trait Parse: Sized {
|
||||||
|
/// Parse `Self` from `string`.
|
||||||
|
fn parse(string: &str) -> Result<Self, Error>;
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Parse for bool {
|
||||||
|
fn parse(string: &str) -> Result<Self, Error> {
|
||||||
|
Self::from_str(string).map_err(Error::from)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
macro_rules! impl_parse_for_int_type {
|
||||||
|
($($int_type:ty),+ $(,)?) => {
|
||||||
|
$(
|
||||||
|
impl Parse for $int_type {
|
||||||
|
fn parse(string: &str) -> Result<Self, Error> {
|
||||||
|
Self::from_str(string).map_err(Error::from)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
)+
|
||||||
|
}
|
||||||
|
}
|
||||||
|
impl_parse_for_int_type![i8, i16, i32, i64, i128, u8, u16, u32, u64, u128];
|
||||||
|
|
||||||
|
impl Parse for String {
|
||||||
|
fn parse(string: &str) -> Result<Self, Error> {
|
||||||
|
Ok(string.to_string())
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Parse for PathBuf {
|
||||||
|
fn parse(string: &str) -> Result<Self, Error> {
|
||||||
|
Ok(PathBuf::from(string))
|
||||||
|
}
|
||||||
|
}
|
93
actix-settings/src/settings/address.rs
Normal file
93
actix-settings/src/settings/address.rs
Normal file
@ -0,0 +1,93 @@
|
|||||||
|
use once_cell::sync::Lazy;
|
||||||
|
use regex::Regex;
|
||||||
|
use serde::Deserialize;
|
||||||
|
|
||||||
|
use crate::{Error, Parse};
|
||||||
|
|
||||||
|
static ADDR_REGEX: Lazy<Regex> = Lazy::new(|| {
|
||||||
|
Regex::new(
|
||||||
|
r#"(?x)
|
||||||
|
\[ # opening square bracket
|
||||||
|
(\s)* # optional whitespace
|
||||||
|
"(?P<host>[^"]+)" # host name (string)
|
||||||
|
, # separating comma
|
||||||
|
(\s)* # optional whitespace
|
||||||
|
(?P<port>\d+) # port number (integer)
|
||||||
|
(\s)* # optional whitespace
|
||||||
|
\] # closing square bracket
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.expect("Failed to compile regex: ADDR_REGEX")
|
||||||
|
});
|
||||||
|
|
||||||
|
static ADDR_LIST_REGEX: Lazy<Regex> = Lazy::new(|| {
|
||||||
|
Regex::new(
|
||||||
|
r#"(?x)
|
||||||
|
\[ # opening square bracket (list)
|
||||||
|
(\s)* # optional whitespace
|
||||||
|
(?P<elements>(
|
||||||
|
\[".*", (\s)* \d+\] # element
|
||||||
|
(,)? # element separator
|
||||||
|
(\s)* # optional whitespace
|
||||||
|
)*)
|
||||||
|
(\s)* # optional whitespace
|
||||||
|
\] # closing square bracket (list)
|
||||||
|
"#,
|
||||||
|
)
|
||||||
|
.expect("Failed to compile regex: ADDRS_REGEX")
|
||||||
|
});
|
||||||
|
|
||||||
|
/// A host/port pair for the server to bind to.
|
||||||
|
#[derive(Debug, Clone, PartialEq, Eq, Hash, Deserialize)]
|
||||||
|
pub struct Address {
|
||||||
|
/// Host part of address.
|
||||||
|
pub host: String,
|
||||||
|
|
||||||
|
/// Port part of address.
|
||||||
|
pub port: u16,
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Parse for Address {
|
||||||
|
fn parse(string: &str) -> Result<Self, Error> {
|
||||||
|
let mut items = string
|
||||||
|
.trim()
|
||||||
|
.trim_start_matches('[')
|
||||||
|
.trim_end_matches(']')
|
||||||
|
.split(',');
|
||||||
|
|
||||||
|
let parse_error = || Error::ParseAddressError(string.to_string());
|
||||||
|
|
||||||
|
if !ADDR_REGEX.is_match(string) {
|
||||||
|
return Err(parse_error());
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(Self {
|
||||||
|
host: items.next().ok_or_else(parse_error)?.trim().to_string(),
|
||||||
|
port: items.next().ok_or_else(parse_error)?.trim().parse()?,
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
impl Parse for Vec<Address> {
|
||||||
|
fn parse(string: &str) -> Result<Self, Error> {
|
||||||
|
let parse_error = || Error::ParseAddressError(string.to_string());
|
||||||
|
|
||||||
|
if !ADDR_LIST_REGEX.is_match(string) {
|
||||||
|
return Err(parse_error());
|
||||||
|
}
|
||||||
|
|
||||||
|
let mut addrs = vec![];
|
||||||
|
|
||||||
|
for list_caps in ADDR_LIST_REGEX.captures_iter(string) {
|
||||||
|
let elements = &list_caps["elements"].trim();
|
||||||
|
for elt_caps in ADDR_REGEX.captures_iter(elements) {
|
||||||
|
addrs.push(Address {
|
||||||
|
host: elt_caps["host"].to_string(),
|
||||||
|
port: elt_caps["port"].parse()?,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
Ok(addrs)
|
||||||
|
}
|
||||||
|
}
|
Some files were not shown because too many files have changed in this diff Show More
Loading…
x
Reference in New Issue
Block a user