repo
stringlengths
6
65
file_url
stringlengths
81
311
file_path
stringlengths
6
227
content
stringlengths
0
32.8k
language
stringclasses
1 value
license
stringclasses
7 values
commit_sha
stringlengths
40
40
retrieved_at
stringdate
2026-01-04 15:31:58
2026-01-04 20:25:31
truncated
bool
2 classes
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/fail/returning_request_parts.rs
axum-macros/tests/debug_handler/fail/returning_request_parts.rs
#[axum::debug_handler] async fn handler() -> ( axum::http::request::Parts, // this should be response parts, not request parts axum::http::StatusCode, ) { panic!() } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/fail/not_send.rs
axum-macros/tests/debug_handler/fail/not_send.rs
use axum_macros::debug_handler; #[debug_handler] async fn handler() { let _rc = std::rc::Rc::new(()); async {}.await; } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/fail/output_tuple_too_many.rs
axum-macros/tests/debug_handler/fail/output_tuple_too_many.rs
use axum::response::AppendHeaders; #[axum::debug_handler] async fn handler() -> ( axum::http::StatusCode, AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>, AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>, AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>, AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>, AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>, AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>, AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>, AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>, AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>, AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>, AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>, AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>, AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>, AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>, AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>, AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>, AppendHeaders<[(axum::http::HeaderName, &'static str); 1]>, axum::http::StatusCode, ) { panic!() } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/fail/duplicate_args.rs
axum-macros/tests/debug_handler/fail/duplicate_args.rs
use axum_macros::debug_handler; #[debug_handler(state = (), state = ())] async fn handler() {} fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/fail/not_a_function.rs
axum-macros/tests/debug_handler/fail/not_a_function.rs
use axum_macros::debug_handler; #[debug_handler] struct A; fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/fail/too_many_extractors.rs
axum-macros/tests/debug_handler/fail/too_many_extractors.rs
use axum::http::Uri; use axum_macros::debug_handler; #[debug_handler] async fn handler( _e1: Uri, _e2: Uri, _e3: Uri, _e4: Uri, _e5: Uri, _e6: Uri, _e7: Uri, _e8: Uri, _e9: Uri, _e10: Uri, _e11: Uri, _e12: Uri, _e13: Uri, _e14: Uri, _e15: Uri, _e16: Uri, _e17: Uri, ) { } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/fail/extract_self_ref.rs
axum-macros/tests/debug_handler/fail/extract_self_ref.rs
use axum::extract::{FromRequest, Request}; use axum_macros::debug_handler; struct A; impl<S> FromRequest<S> for A where S: Send + Sync, { type Rejection = (); async fn from_request(_req: Request, _state: &S) -> Result<Self, Self::Rejection> { unimplemented!() } } impl A { #[debug_handler] async fn handler(&self) {} } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/fail/invalid_attrs.rs
axum-macros/tests/debug_handler/fail/invalid_attrs.rs
use axum_macros::debug_handler; #[debug_handler(foo)] async fn handler() {} fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/fail/single_wrong_return_tuple.rs
axum-macros/tests/debug_handler/fail/single_wrong_return_tuple.rs
#![allow(unused_parens)] struct NotIntoResponse; #[axum::debug_handler] async fn handler() -> (NotIntoResponse) { panic!() } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/fail/wrong_order.rs
axum-macros/tests/debug_handler/fail/wrong_order.rs
use axum::{http::Uri, Json}; use axum_macros::debug_handler; #[debug_handler] async fn one(_: Json<()>, _: Uri) {} #[debug_handler] async fn two(_: String, _: Uri) {} fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/pass/mut_extractor.rs
axum-macros/tests/debug_handler/pass/mut_extractor.rs
use axum_macros::debug_handler; #[debug_handler] async fn handler(mut foo: String) -> String { foo += "bar"; foo } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/pass/returns_self.rs
axum-macros/tests/debug_handler/pass/returns_self.rs
use axum::response::{IntoResponse, Response}; use axum_macros::debug_handler; struct A; impl A { #[debug_handler] async fn handler() -> Self { A } } impl IntoResponse for A { fn into_response(self) -> Response { todo!() } } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/pass/impl_future.rs
axum-macros/tests/debug_handler/pass/impl_future.rs
use axum_macros::debug_handler; use std::future::Future; #[debug_handler] fn handler() -> impl Future<Output = ()> { async {} } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/pass/multiple_extractors.rs
axum-macros/tests/debug_handler/pass/multiple_extractors.rs
use axum::http::{Method, Uri}; use axum_macros::debug_handler; #[debug_handler] async fn handler(_one: Method, _two: Uri, _three: String) {} fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/pass/impl_into_response.rs
axum-macros/tests/debug_handler/pass/impl_into_response.rs
use axum::response::IntoResponse; use axum_macros::debug_handler; #[debug_handler] async fn handler() -> impl IntoResponse { "hi!" } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/pass/result_impl_into_response.rs
axum-macros/tests/debug_handler/pass/result_impl_into_response.rs
use axum::{extract::FromRequestParts, http::request::Parts, response::IntoResponse}; use axum_macros::debug_handler; fn main() {} #[debug_handler] fn concrete_future() -> std::future::Ready<Result<impl IntoResponse, ()>> { std::future::ready(Ok(())) } #[debug_handler] fn impl_future() -> impl std::future::Future<Output = Result<impl IntoResponse, ()>> { std::future::ready(Ok(())) } // === no args === #[debug_handler] async fn handler_no_arg_one() -> Result<impl IntoResponse, ()> { Ok(()) } #[debug_handler] async fn handler_no_arg_two() -> Result<(), impl IntoResponse> { Err(()) } #[debug_handler] async fn handler_no_arg_three() -> Result<impl IntoResponse, impl IntoResponse> { Ok::<_, ()>(()) } #[debug_handler] async fn handler_no_arg_four() -> Result<impl IntoResponse, impl IntoResponse> { Err::<(), _>(()) } // === args === #[debug_handler] async fn handler_one(foo: String) -> Result<impl IntoResponse, ()> { dbg!(foo); Ok(()) } #[debug_handler] async fn handler_two(foo: String) -> Result<(), impl IntoResponse> { dbg!(foo); Err(()) } #[debug_handler] async fn handler_three(foo: String) -> Result<impl IntoResponse, impl IntoResponse> { dbg!(foo); Ok::<_, ()>(()) } #[debug_handler] async fn handler_four(foo: String) -> Result<impl IntoResponse, impl IntoResponse> { dbg!(foo); Err::<(), _>(()) } // === no args with receiver === struct A; impl A { #[debug_handler] async fn handler_no_arg_one(self) -> Result<impl IntoResponse, ()> { Ok(()) } #[debug_handler] async fn handler_no_arg_two(self) -> Result<(), impl IntoResponse> { Err(()) } #[debug_handler] async fn handler_no_arg_three(self) -> Result<impl IntoResponse, impl IntoResponse> { Ok::<_, ()>(()) } #[debug_handler] async fn handler_no_arg_four(self) -> Result<impl IntoResponse, impl IntoResponse> { Err::<(), _>(()) } } // === args with receiver === impl A { #[debug_handler] async fn handler_one(self, foo: String) -> Result<impl IntoResponse, ()> { dbg!(foo); Ok(()) } #[debug_handler] async fn handler_two(self, foo: String) -> Result<(), impl IntoResponse> { dbg!(foo); Err(()) } #[debug_handler] async fn handler_three(self, foo: String) -> Result<impl IntoResponse, impl IntoResponse> { dbg!(foo); Ok::<_, ()>(()) } #[debug_handler] async fn handler_four(self, foo: String) -> Result<impl IntoResponse, impl IntoResponse> { dbg!(foo); Err::<(), _>(()) } } impl<S> FromRequestParts<S> for A where S: Send + Sync, { type Rejection = (); async fn from_request_parts(_parts: &mut Parts, _state: &S) -> Result<Self, Self::Rejection> { unimplemented!() } }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/pass/deny_unreachable_code.rs
axum-macros/tests/debug_handler/pass/deny_unreachable_code.rs
#![deny(unreachable_code)] use axum::extract::Path; #[axum_macros::debug_handler] async fn handler(Path(_): Path<String>) {} fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/pass/infer_state.rs
axum-macros/tests/debug_handler/pass/infer_state.rs
use axum::extract::State; use axum_macros::debug_handler; #[debug_handler] async fn handler(_: State<AppState>) {} #[debug_handler] async fn handler_2(_: axum::extract::State<AppState>) {} #[debug_handler] async fn handler_3(_: axum::extract::State<AppState>, _: axum::extract::State<AppState>) {} #[debug_handler] async fn handler_4(_: State<AppState>, _: State<AppState>) {} #[debug_handler] async fn handler_5(_: axum::extract::State<AppState>, _: State<AppState>) {} #[derive(Clone)] struct AppState; fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/pass/ready.rs
axum-macros/tests/debug_handler/pass/ready.rs
use axum_macros::debug_handler; use std::future::{ready, Ready}; #[debug_handler] fn handler() -> Ready<()> { ready(()) } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/pass/self_receiver.rs
axum-macros/tests/debug_handler/pass/self_receiver.rs
use axum::extract::{FromRequest, Request}; use axum_macros::debug_handler; struct A; impl<S> FromRequest<S> for A where S: Send + Sync, { type Rejection = (); async fn from_request(_req: Request, _state: &S) -> Result<Self, Self::Rejection> { unimplemented!() } } impl<S> FromRequest<S> for Box<A> where S: Send + Sync, { type Rejection = (); async fn from_request(_req: Request, _state: &S) -> Result<Self, Self::Rejection> { unimplemented!() } } impl A { #[debug_handler] async fn handler(self) {} #[debug_handler] async fn handler_with_qualified_self(self: Box<Self>) {} } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/pass/state_and_body.rs
axum-macros/tests/debug_handler/pass/state_and_body.rs
use axum::{extract::Request, extract::State}; use axum_macros::debug_handler; #[debug_handler(state = AppState)] async fn handler(_: State<AppState>, _: Request) {} #[derive(Clone)] struct AppState; fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/pass/request_last.rs
axum-macros/tests/debug_handler/pass/request_last.rs
use axum::extract::{Extension, Request}; use axum_macros::debug_handler; #[debug_handler] async fn handler(_: Extension<String>, _: Request) {} fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/pass/set_state.rs
axum-macros/tests/debug_handler/pass/set_state.rs
use axum::extract::{FromRef, FromRequest, Request}; use axum_macros::debug_handler; #[debug_handler(state = AppState)] async fn handler(_: A) {} #[derive(Clone)] struct AppState; struct A; impl<S> FromRequest<S> for A where S: Send + Sync, AppState: FromRef<S>, { type Rejection = (); async fn from_request(_req: Request, _state: &S) -> Result<Self, Self::Rejection> { unimplemented!() } } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_handler/pass/associated_fn_without_self.rs
axum-macros/tests/debug_handler/pass/associated_fn_without_self.rs
use axum_macros::debug_handler; struct A; impl A { #[debug_handler] async fn handler() {} } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/typed_path/fail/not_deserialize.rs
axum-macros/tests/typed_path/fail/not_deserialize.rs
use axum_macros::TypedPath; #[derive(TypedPath)] #[typed_path("/users/{id}")] struct MyPath { id: u32, } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/typed_path/fail/missing_capture.rs
axum-macros/tests/typed_path/fail/missing_capture.rs
use axum_macros::TypedPath; use serde::Deserialize; #[derive(TypedPath, Deserialize)] #[typed_path("/users")] struct MyPath { id: u32, } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/typed_path/fail/unit_with_capture.rs
axum-macros/tests/typed_path/fail/unit_with_capture.rs
use axum_macros::TypedPath; use serde::Deserialize; #[derive(TypedPath, Deserialize)] #[typed_path("/users/{id}")] struct MyPath; fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/typed_path/fail/route_not_starting_with_slash_non_empty.rs
axum-macros/tests/typed_path/fail/route_not_starting_with_slash_non_empty.rs
use axum_extra::routing::TypedPath; #[derive(TypedPath)] #[typed_path("{foo}")] struct MyPath; fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/typed_path/fail/missing_field.rs
axum-macros/tests/typed_path/fail/missing_field.rs
use axum_macros::TypedPath; use serde::Deserialize; #[derive(TypedPath, Deserialize)] #[typed_path("/users/{id}")] struct MyPath {} fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/typed_path/fail/route_not_starting_with_slash.rs
axum-macros/tests/typed_path/fail/route_not_starting_with_slash.rs
use axum_extra::routing::TypedPath; #[derive(TypedPath)] #[typed_path("")] struct MyPath; fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/typed_path/pass/named_fields_struct.rs
axum-macros/tests/typed_path/pass/named_fields_struct.rs
use axum_extra::routing::TypedPath; use serde::Deserialize; #[derive(TypedPath, Deserialize)] #[typed_path("/users/{user_id}/teams/{team_id}")] struct MyPath { user_id: u32, team_id: u32, } fn main() { _ = axum::Router::<()>::new().route("/", axum::routing::get(|_: MyPath| async {})); assert_eq!(MyPath::PATH, "/users/{user_id}/teams/{team_id}"); assert_eq!( format!( "{}", MyPath { user_id: 1, team_id: 2 } ), "/users/1/teams/2" ); }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/typed_path/pass/result_handler.rs
axum-macros/tests/typed_path/pass/result_handler.rs
use axum::{extract::rejection::PathRejection, http::StatusCode}; use axum_extra::routing::{RouterExt, TypedPath}; use serde::Deserialize; #[derive(TypedPath, Deserialize)] #[typed_path("/users/{id}")] struct UsersShow { id: String, } async fn result_handler(_: Result<UsersShow, PathRejection>) {} #[derive(TypedPath, Deserialize)] #[typed_path("/users")] struct UsersIndex; async fn result_handler_unit_struct(_: Result<UsersIndex, StatusCode>) {} fn main() { _ = axum::Router::<()>::new() .typed_post(result_handler) .typed_post(result_handler_unit_struct); }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/typed_path/pass/tuple_struct.rs
axum-macros/tests/typed_path/pass/tuple_struct.rs
use axum_extra::routing::TypedPath; use serde::Deserialize; pub type Result<T> = std::result::Result<T, ()>; #[derive(TypedPath, Deserialize)] #[typed_path("/users/{user_id}/teams/{team_id}")] struct MyPath(u32, u32); fn main() { _ = axum::Router::<()>::new().route("/", axum::routing::get(|_: MyPath| async {})); assert_eq!(MyPath::PATH, "/users/{user_id}/teams/{team_id}"); assert_eq!(format!("{}", MyPath(1, 2)), "/users/1/teams/2"); }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/typed_path/pass/into_uri.rs
axum-macros/tests/typed_path/pass/into_uri.rs
use axum::http::Uri; use axum_extra::routing::TypedPath; use serde::Deserialize; #[derive(TypedPath, Deserialize)] #[typed_path("/{id}")] struct Named { id: u32, } #[derive(TypedPath, Deserialize)] #[typed_path("/{id}")] struct Unnamed(u32); #[derive(TypedPath, Deserialize)] #[typed_path("/")] struct Unit; fn main() { let _: Uri = Named { id: 1 }.to_uri(); let _: Uri = Unnamed(1).to_uri(); let _: Uri = Unit.to_uri(); }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/typed_path/pass/customize_rejection.rs
axum-macros/tests/typed_path/pass/customize_rejection.rs
use axum::{ extract::rejection::PathRejection, response::{IntoResponse, Response}, }; use axum_extra::routing::{RouterExt, TypedPath}; use serde::Deserialize; #[derive(TypedPath, Deserialize)] #[typed_path("/{foo}", rejection(MyRejection))] struct MyPathNamed { foo: String, } #[derive(TypedPath, Deserialize)] #[typed_path("/", rejection(MyRejection))] struct MyPathUnit; #[derive(TypedPath, Deserialize)] #[typed_path("/{foo}", rejection(MyRejection))] struct MyPathUnnamed(String); struct MyRejection; impl IntoResponse for MyRejection { fn into_response(self) -> Response { ().into_response() } } impl From<PathRejection> for MyRejection { fn from(_: PathRejection) -> Self { Self } } impl Default for MyRejection { fn default() -> Self { Self } } fn main() { _ = axum::Router::<()>::new() .typed_get(|_: Result<MyPathNamed, MyRejection>| async {}) .typed_post(|_: Result<MyPathUnnamed, MyRejection>| async {}) .typed_put(|_: Result<MyPathUnit, MyRejection>| async {}); }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/typed_path/pass/wildcards.rs
axum-macros/tests/typed_path/pass/wildcards.rs
use axum_extra::routing::{RouterExt, TypedPath}; use serde::Deserialize; #[derive(TypedPath, Deserialize)] #[typed_path("/{*rest}")] struct MyPath { rest: String, } fn main() { _ = axum::Router::<()>::new().typed_get(|_: MyPath| async {}); }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/typed_path/pass/url_encoding.rs
axum-macros/tests/typed_path/pass/url_encoding.rs
use axum_extra::routing::TypedPath; use serde::Deserialize; #[derive(TypedPath, Deserialize)] #[typed_path("/{param}")] struct Named { param: String, } #[derive(TypedPath, Deserialize)] #[typed_path("/{param}")] struct Unnamed(String); fn main() { assert_eq!( format!( "{}", Named { param: "a b".to_string() } ), "/a%20b" ); assert_eq!(format!("{}", Unnamed("a b".to_string()),), "/a%20b"); }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/typed_path/pass/unit_struct.rs
axum-macros/tests/typed_path/pass/unit_struct.rs
use axum_extra::routing::TypedPath; #[derive(TypedPath)] #[typed_path("/users")] struct MyPath; fn main() { _ = axum::Router::<()>::new().route("/", axum::routing::get(|_: MyPath| async {})); assert_eq!(MyPath::PATH, "/users"); assert_eq!(format!("{}", MyPath), "/users"); }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_middleware/fail/takes_next_twice.rs
axum-macros/tests/debug_middleware/fail/takes_next_twice.rs
use axum::{debug_middleware, extract::Request, middleware::Next, response::Response}; #[debug_middleware] async fn my_middleware(request: Request, next: Next, next2: Next) -> Response { let _ = next2; next.run(request).await } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_middleware/fail/doesnt_take_next.rs
axum-macros/tests/debug_middleware/fail/doesnt_take_next.rs
use axum::{ debug_middleware, extract::Request, response::{IntoResponse, Response}, }; #[debug_middleware] async fn my_middleware(request: Request) -> Response { let _ = request; ().into_response() } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_middleware/fail/next_not_last.rs
axum-macros/tests/debug_middleware/fail/next_not_last.rs
use axum::{debug_middleware, extract::Request, middleware::Next, response::Response}; #[debug_middleware] async fn my_middleware(next: Next, request: Request) -> Response { next.run(request).await } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/debug_middleware/pass/basic.rs
axum-macros/tests/debug_middleware/pass/basic.rs
use axum::{debug_middleware, extract::Request, middleware::Next, response::Response}; #[debug_middleware] async fn my_middleware(request: Request, next: Next) -> Response { next.run(request).await } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_ref/fail/generics.rs
axum-macros/tests/from_ref/fail/generics.rs
use axum::extract::FromRef; #[derive(Clone, FromRef)] struct AppState<T> { foo: T, } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_ref/pass/reference-types.rs
axum-macros/tests/from_ref/pass/reference-types.rs
#![deny(noop_method_call)] use axum_macros::FromRef; #[derive(FromRef)] struct State { inner: &'static str, } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_ref/pass/skip.rs
axum-macros/tests/from_ref/pass/skip.rs
use axum_macros::FromRef; #[derive(Clone, FromRef)] struct AppState { auth_token: String, #[from_ref(skip)] also_string: String, } fn main() {}
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
tokio-rs/axum
https://github.com/tokio-rs/axum/blob/183ace306ab126f034c55d9147ea3513c8a5a139/axum-macros/tests/from_ref/pass/basic.rs
axum-macros/tests/from_ref/pass/basic.rs
use axum::{ extract::{FromRef, State}, routing::get, Router, }; // This will implement `FromRef` for each field in the struct. #[derive(Clone, FromRef)] struct AppState { auth_token: String, } // So those types can be extracted via `State` async fn handler(_: State<String>) {} fn main() { let state = AppState { auth_token: Default::default(), }; let _: axum::Router = Router::new().route("/", get(handler)).with_state(state); }
rust
MIT
183ace306ab126f034c55d9147ea3513c8a5a139
2026-01-04T15:37:41.118512Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-multipart/src/extractor.rs
actix-multipart/src/extractor.rs
use actix_utils::future::{ready, Ready}; use actix_web::{dev::Payload, Error, FromRequest, HttpRequest}; use crate::multipart::Multipart; /// Extract request's payload as multipart stream. /// /// Content-type: multipart/*; /// /// # Examples /// /// ``` /// use actix_web::{web, HttpResponse}; /// use actix_multipart::Multipart; /// use futures_util::StreamExt as _; /// /// async fn index(mut payload: Multipart) -> actix_web::Result<HttpResponse> { /// // iterate over multipart stream /// while let Some(item) = payload.next().await { /// let mut field = item?; /// /// // Field in turn is stream of *Bytes* object /// while let Some(chunk) = field.next().await { /// println!("-- CHUNK: \n{:?}", std::str::from_utf8(&chunk?)); /// } /// } /// /// Ok(HttpResponse::Ok().finish()) /// } /// ``` impl FromRequest for Multipart { type Error = Error; type Future = Ready<Result<Multipart, Error>>; #[inline] fn from_request(req: &HttpRequest, payload: &mut Payload) -> Self::Future { ready(Ok(Multipart::from_req(req, payload))) } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-multipart/src/safety.rs
actix-multipart/src/safety.rs
use std::{cell::Cell, marker::PhantomData, rc::Rc, task}; use local_waker::LocalWaker; /// Counter. It tracks of number of clones of payloads and give access to payload only to top most. /// /// - When dropped, parent task is awakened. This is to support the case where `Field` is dropped in /// a separate task than `Multipart`. /// - Assumes that parent owners don't move to different tasks; only the top-most is allowed to. /// - If dropped and is not top most owner, is_clean flag is set to false. #[derive(Debug)] pub(crate) struct Safety { task: LocalWaker, level: usize, payload: Rc<PhantomData<bool>>, clean: Rc<Cell<bool>>, } impl Safety { pub(crate) fn new() -> Safety { let payload = Rc::new(PhantomData); Safety { task: LocalWaker::new(), level: Rc::strong_count(&payload), clean: Rc::new(Cell::new(true)), payload, } } pub(crate) fn current(&self) -> bool { Rc::strong_count(&self.payload) == self.level && self.clean.get() } pub(crate) fn is_clean(&self) -> bool { self.clean.get() } pub(crate) fn clone(&self, cx: &task::Context<'_>) -> Safety { let payload = Rc::clone(&self.payload); let s = Safety { task: LocalWaker::new(), level: Rc::strong_count(&payload), clean: self.clean.clone(), payload, }; s.task.register(cx.waker()); s } } impl Drop for Safety { fn drop(&mut self) { if Rc::strong_count(&self.payload) != self.level { // Multipart dropped leaving a Field self.clean.set(false); } self.task.wake(); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-multipart/src/field.rs
actix-multipart/src/field.rs
use std::{ cell::RefCell, cmp, fmt, future::poll_fn, mem, pin::Pin, rc::Rc, task::{ready, Context, Poll}, }; use actix_web::{ error::PayloadError, http::header::{self, ContentDisposition, HeaderMap}, web::{Bytes, BytesMut}, }; use derive_more::{Display, Error}; use futures_core::Stream; use mime::Mime; use crate::{ error::Error, payload::{PayloadBuffer, PayloadRef}, safety::Safety, }; /// Error type returned from [`Field::bytes()`] when field data is larger than limit. #[derive(Debug, Display, Error)] #[display("size limit exceeded while collecting field data")] #[non_exhaustive] pub struct LimitExceeded; /// A single field in a multipart stream. pub struct Field { /// Field's Content-Type. content_type: Option<Mime>, /// Field's Content-Disposition. content_disposition: Option<ContentDisposition>, /// Form field name. /// /// A non-optional storage for form field names to avoid unwraps in `form` module. Will be an /// empty string in non-form contexts. /// // INVARIANT: always non-empty when request content-type is multipart/form-data. pub(crate) form_field_name: String, /// Field's header map. headers: HeaderMap, safety: Safety, inner: Rc<RefCell<InnerField>>, } impl Field { pub(crate) fn new( content_type: Option<Mime>, content_disposition: Option<ContentDisposition>, form_field_name: Option<String>, headers: HeaderMap, safety: Safety, inner: Rc<RefCell<InnerField>>, ) -> Self { Field { content_type, content_disposition, form_field_name: form_field_name.unwrap_or_default(), headers, inner, safety, } } /// Returns a reference to the field's header map. pub fn headers(&self) -> &HeaderMap { &self.headers } /// Returns a reference to the field's content (mime) type, if it is supplied by the client. /// /// According to [RFC 7578](https://www.rfc-editor.org/rfc/rfc7578#section-4.4), if it is not /// present, it should default to "text/plain". Note it is the responsibility of the client to /// provide the appropriate content type, there is no attempt to validate this by the server. pub fn content_type(&self) -> Option<&Mime> { self.content_type.as_ref() } /// Returns this field's parsed Content-Disposition header, if set. /// /// # Validation /// /// Per [RFC 7578 §4.2], the parts of a multipart/form-data payload MUST contain a /// Content-Disposition header field where the disposition type is `form-data` and MUST also /// contain an additional parameter of `name` with its value being the original field name from /// the form. This requirement is enforced during extraction for multipart/form-data requests, /// but not other kinds of multipart requests (such as multipart/related). /// /// As such, it is safe to `.unwrap()` calls `.content_disposition()` if you've verified. /// /// The [`name()`](Self::name) method is also provided as a convenience for obtaining the /// aforementioned name parameter. /// /// [RFC 7578 §4.2]: https://datatracker.ietf.org/doc/html/rfc7578#section-4.2 pub fn content_disposition(&self) -> Option<&ContentDisposition> { self.content_disposition.as_ref() } /// Returns the field's name, if set. /// /// See [`content_disposition()`](Self::content_disposition) regarding guarantees on presence of /// the "name" field. pub fn name(&self) -> Option<&str> { self.content_disposition()?.get_name() } /// Collects the raw field data, up to `limit` bytes. /// /// # Errors /// /// Any errors produced by the data stream are returned as `Ok(Err(Error))` immediately. /// /// If the buffered data size would exceed `limit`, an `Err(LimitExceeded)` is returned. Note /// that, in this case, the full data stream is exhausted before returning the error so that /// subsequent fields can still be read. To better defend against malicious/infinite requests, /// it is advisable to also put a timeout on this call. pub async fn bytes(&mut self, limit: usize) -> Result<Result<Bytes, Error>, LimitExceeded> { /// Sensible default (2kB) for initial, bounded allocation when collecting body bytes. const INITIAL_ALLOC_BYTES: usize = 2 * 1024; let mut exceeded_limit = false; let mut buf = BytesMut::with_capacity(INITIAL_ALLOC_BYTES); let mut field = Pin::new(self); match poll_fn(|cx| loop { match ready!(field.as_mut().poll_next(cx)) { // if already over limit, discard chunk to advance multipart request Some(Ok(_chunk)) if exceeded_limit => {} // if limit is exceeded set flag to true and continue Some(Ok(chunk)) if buf.len() + chunk.len() > limit => { exceeded_limit = true; // eagerly de-allocate field data buffer let _ = mem::take(&mut buf); } Some(Ok(chunk)) => buf.extend_from_slice(&chunk), None => return Poll::Ready(Ok(())), Some(Err(err)) => return Poll::Ready(Err(err)), } }) .await { // propagate error returned from body poll Err(err) => Ok(Err(err)), // limit was exceeded while reading body Ok(()) if exceeded_limit => Err(LimitExceeded), // otherwise return body buffer Ok(()) => Ok(Ok(buf.freeze())), } } } impl Stream for Field { type Item = Result<Bytes, Error>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let this = self.get_mut(); let mut inner = this.inner.borrow_mut(); if let Some(mut buffer) = inner .payload .as_ref() .expect("Field should not be polled after completion") .get_mut(&this.safety) { // check safety and poll read payload to buffer. buffer.poll_stream(cx)?; } else if !this.safety.is_clean() { // safety violation return Poll::Ready(Some(Err(Error::NotConsumed))); } else { return Poll::Pending; } inner.poll(&this.safety) } } impl fmt::Debug for Field { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { if let Some(ct) = &self.content_type { writeln!(f, "\nField: {}", ct)?; } else { writeln!(f, "\nField:")?; } writeln!(f, " boundary: {}", self.inner.borrow().boundary)?; writeln!(f, " headers:")?; for (key, val) in self.headers.iter() { writeln!(f, " {:?}: {:?}", key, val)?; } Ok(()) } } pub(crate) struct InnerField { /// Payload is initialized as Some and is `take`n when the field stream finishes. payload: Option<PayloadRef>, /// Field boundary (without "--" prefix). boundary: String, /// True if request payload has been exhausted. eof: bool, /// Field data's stated size according to it's Content-Length header. length: Option<u64>, } impl InnerField { pub(crate) fn new_in_rc( payload: PayloadRef, boundary: String, headers: &HeaderMap, ) -> Result<Rc<RefCell<InnerField>>, PayloadError> { Self::new(payload, boundary, headers).map(|this| Rc::new(RefCell::new(this))) } pub(crate) fn new( payload: PayloadRef, boundary: String, headers: &HeaderMap, ) -> Result<InnerField, PayloadError> { let len = if let Some(len) = headers.get(&header::CONTENT_LENGTH) { match len.to_str().ok().and_then(|len| len.parse::<u64>().ok()) { Some(len) => Some(len), None => return Err(PayloadError::Incomplete(None)), } } else { None }; Ok(InnerField { boundary, payload: Some(payload), eof: false, length: len, }) } /// Reads body part content chunk of the specified size. /// /// The body part must has `Content-Length` header with proper value. pub(crate) fn read_len( payload: &mut PayloadBuffer, size: &mut u64, ) -> Poll<Option<Result<Bytes, Error>>> { if *size == 0 { Poll::Ready(None) } else { match payload.read_max(*size)? { Some(mut chunk) => { let len = cmp::min(chunk.len() as u64, *size); *size -= len; let ch = chunk.split_to(len as usize); if !chunk.is_empty() { payload.unprocessed(chunk); } Poll::Ready(Some(Ok(ch))) } None => { if payload.eof && (*size != 0) { Poll::Ready(Some(Err(Error::Incomplete))) } else { Poll::Pending } } } } } /// Reads content chunk of body part with unknown length. /// /// The `Content-Length` header for body part is not necessary. pub(crate) fn read_stream( payload: &mut PayloadBuffer, boundary: &str, ) -> Poll<Option<Result<Bytes, Error>>> { let mut pos = 0; let len = payload.buf.len(); if len == 0 { return if payload.eof { Poll::Ready(Some(Err(Error::Incomplete))) } else { Poll::Pending }; } // check boundary if len > 4 && payload.buf[0] == b'\r' { let b_len = if payload.buf.starts_with(b"\r\n") && &payload.buf[2..4] == b"--" { Some(4) } else if &payload.buf[1..3] == b"--" { Some(3) } else { None }; if let Some(b_len) = b_len { let b_size = boundary.len() + b_len; if len < b_size { return Poll::Pending; } else if &payload.buf[b_len..b_size] == boundary.as_bytes() { // found boundary return Poll::Ready(None); } } } loop { return if let Some(idx) = memchr::memmem::find(&payload.buf[pos..], b"\r") { let cur = pos + idx; // check if we have enough data for boundary detection if cur + 4 > len { if cur > 0 { Poll::Ready(Some(Ok(payload.buf.split_to(cur).freeze()))) } else { Poll::Pending } } else { // check boundary if (&payload.buf[cur..cur + 2] == b"\r\n" && &payload.buf[cur + 2..cur + 4] == b"--") || (&payload.buf[cur..=cur] == b"\r" && &payload.buf[cur + 1..cur + 3] == b"--") { if cur != 0 { // return buffer Poll::Ready(Some(Ok(payload.buf.split_to(cur).freeze()))) } else { pos = cur + 1; continue; } } else { // not boundary pos = cur + 1; continue; } } } else { Poll::Ready(Some(Ok(payload.buf.split().freeze()))) }; } } pub(crate) fn poll(&mut self, safety: &Safety) -> Poll<Option<Result<Bytes, Error>>> { if self.payload.is_none() { return Poll::Ready(None); } let Some(mut payload) = self .payload .as_ref() .expect("Field should not be polled after completion") .get_mut(safety) else { return Poll::Pending; }; if !self.eof { let res = if let Some(ref mut len) = self.length { Self::read_len(&mut payload, len) } else { Self::read_stream(&mut payload, &self.boundary) }; match ready!(res) { Some(Ok(bytes)) => return Poll::Ready(Some(Ok(bytes))), Some(Err(err)) => return Poll::Ready(Some(Err(err))), None => self.eof = true, } } let result = match payload.readline() { Ok(None) => Poll::Pending, Ok(Some(line)) => { if line.as_ref() != b"\r\n" { log::warn!("multipart field did not read all the data or it is malformed"); } Poll::Ready(None) } Err(err) => Poll::Ready(Some(Err(err))), }; drop(payload); if let Poll::Ready(None) = result { // drop payload buffer and make future un-poll-able let _ = self.payload.take(); } result } } #[cfg(test)] mod tests { use futures_util::{stream, StreamExt as _}; use super::*; use crate::Multipart; // TODO: use test utility when multi-file support is introduced fn create_double_request_with_header() -> (Bytes, HeaderMap) { let bytes = Bytes::from( "testasdadsad\r\n\ --abbc761f78ff4d7cb7573b5a23f96ef0\r\n\ Content-Disposition: form-data; name=\"file\"; filename=\"fn.txt\"\r\n\ Content-Type: text/plain; charset=utf-8\r\n\ \r\n\ one+one+one\r\n\ --abbc761f78ff4d7cb7573b5a23f96ef0\r\n\ Content-Disposition: form-data; name=\"file\"; filename=\"fn.txt\"\r\n\ Content-Type: text/plain; charset=utf-8\r\n\ \r\n\ two+two+two\r\n\ --abbc761f78ff4d7cb7573b5a23f96ef0--\r\n", ); let mut headers = HeaderMap::new(); headers.insert( header::CONTENT_TYPE, header::HeaderValue::from_static( "multipart/mixed; boundary=\"abbc761f78ff4d7cb7573b5a23f96ef0\"", ), ); (bytes, headers) } #[actix_rt::test] async fn bytes_unlimited() { let (body, headers) = create_double_request_with_header(); let mut multipart = Multipart::new(&headers, stream::iter([Ok(body)])); let field = multipart .next() .await .expect("multipart should have two fields") .expect("multipart body should be well formatted") .bytes(usize::MAX) .await .expect("field data should not be size limited") .expect("reading field data should not error"); assert_eq!(field, "one+one+one"); let field = multipart .next() .await .expect("multipart should have two fields") .expect("multipart body should be well formatted") .bytes(usize::MAX) .await .expect("field data should not be size limited") .expect("reading field data should not error"); assert_eq!(field, "two+two+two"); } #[actix_rt::test] async fn bytes_limited() { let (body, headers) = create_double_request_with_header(); let mut multipart = Multipart::new(&headers, stream::iter([Ok(body)])); multipart .next() .await .expect("multipart should have two fields") .expect("multipart body should be well formatted") .bytes(8) // smaller than data size .await .expect_err("field data should be size limited"); // next field still readable let field = multipart .next() .await .expect("multipart should have two fields") .expect("multipart body should be well formatted") .bytes(usize::MAX) .await .expect("field data should not be size limited") .expect("reading field data should not error"); assert_eq!(field, "two+two+two"); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-multipart/src/test.rs
actix-multipart/src/test.rs
//! Multipart testing utilities. use actix_web::{ http::header::{self, HeaderMap}, web::{BufMut as _, Bytes, BytesMut}, }; use mime::Mime; use rand::distr::{Alphanumeric, SampleString as _}; const CRLF: &[u8] = b"\r\n"; const CRLF_CRLF: &[u8] = b"\r\n\r\n"; const HYPHENS: &[u8] = b"--"; const BOUNDARY_PREFIX: &str = "------------------------"; /// Constructs a `multipart/form-data` payload from bytes and metadata. /// /// Returned header map can be extended or merged with existing headers. /// /// Multipart boundary used is a random alphanumeric string. /// /// # Examples /// /// ``` /// use actix_multipart::test::create_form_data_payload_and_headers; /// use actix_web::{test::TestRequest, web::Bytes}; /// use memchr::memmem::find; /// /// let (body, headers) = create_form_data_payload_and_headers( /// "foo", /// Some("lorem.txt".to_owned()), /// Some(mime::TEXT_PLAIN_UTF_8), /// Bytes::from_static(b"Lorem ipsum."), /// ); /// /// assert!(find(&body, b"foo").is_some()); /// assert!(find(&body, b"lorem.txt").is_some()); /// assert!(find(&body, b"text/plain; charset=utf-8").is_some()); /// assert!(find(&body, b"Lorem ipsum.").is_some()); /// /// let req = TestRequest::default(); /// /// // merge header map into existing test request and set multipart body /// let req = headers /// .into_iter() /// .fold(req, |req, hdr| req.insert_header(hdr)) /// .set_payload(body) /// .to_http_request(); /// /// assert!( /// req.headers() /// .get("content-type") /// .unwrap() /// .to_str() /// .unwrap() /// .starts_with("multipart/form-data; boundary=\"") /// ); /// ``` pub fn create_form_data_payload_and_headers( name: &str, filename: Option<String>, content_type: Option<Mime>, file: Bytes, ) -> (Bytes, HeaderMap) { let boundary = Alphanumeric.sample_string(&mut rand::rng(), 32); create_form_data_payload_and_headers_with_boundary( &boundary, name, filename, content_type, file, ) } /// Constructs a `multipart/form-data` payload from bytes and metadata with a fixed boundary. /// /// See [`create_form_data_payload_and_headers`] for more details. pub fn create_form_data_payload_and_headers_with_boundary( boundary: &str, name: &str, filename: Option<String>, content_type: Option<Mime>, file: Bytes, ) -> (Bytes, HeaderMap) { let mut buf = BytesMut::with_capacity(file.len() + 128); let boundary_str = [BOUNDARY_PREFIX, boundary].concat(); let boundary = boundary_str.as_bytes(); buf.put(HYPHENS); buf.put(boundary); buf.put(CRLF); buf.put(format!("Content-Disposition: form-data; name=\"{name}\"").as_bytes()); if let Some(filename) = filename { buf.put(format!("; filename=\"{filename}\"").as_bytes()); } buf.put(CRLF); if let Some(ct) = content_type { buf.put(format!("Content-Type: {ct}").as_bytes()); buf.put(CRLF); } buf.put(format!("Content-Length: {}", file.len()).as_bytes()); buf.put(CRLF_CRLF); buf.put(file); buf.put(CRLF); buf.put(HYPHENS); buf.put(boundary); buf.put(HYPHENS); buf.put(CRLF); let mut headers = HeaderMap::new(); headers.insert( header::CONTENT_TYPE, format!("multipart/form-data; boundary=\"{boundary_str}\"") .parse() .unwrap(), ); (buf.freeze(), headers) } #[cfg(test)] mod tests { use std::convert::Infallible; use futures_util::stream; use super::*; fn find_boundary(headers: &HeaderMap) -> String { headers .get("content-type") .unwrap() .to_str() .unwrap() .parse::<mime::Mime>() .unwrap() .get_param(mime::BOUNDARY) .unwrap() .as_str() .to_owned() } #[test] fn wire_format() { let (pl, headers) = create_form_data_payload_and_headers_with_boundary( "qWeRtYuIoP", "foo", None, None, Bytes::from_static(b"Lorem ipsum dolor\nsit ame."), ); assert_eq!( find_boundary(&headers), "------------------------qWeRtYuIoP", ); assert_eq!( std::str::from_utf8(&pl).unwrap(), "--------------------------qWeRtYuIoP\r\n\ Content-Disposition: form-data; name=\"foo\"\r\n\ Content-Length: 26\r\n\ \r\n\ Lorem ipsum dolor\n\ sit ame.\r\n\ --------------------------qWeRtYuIoP--\r\n", ); let (pl, _headers) = create_form_data_payload_and_headers_with_boundary( "qWeRtYuIoP", "foo", Some("Lorem.txt".to_owned()), Some(mime::TEXT_PLAIN_UTF_8), Bytes::from_static(b"Lorem ipsum dolor\nsit ame."), ); assert_eq!( std::str::from_utf8(&pl).unwrap(), "--------------------------qWeRtYuIoP\r\n\ Content-Disposition: form-data; name=\"foo\"; filename=\"Lorem.txt\"\r\n\ Content-Type: text/plain; charset=utf-8\r\n\ Content-Length: 26\r\n\ \r\n\ Lorem ipsum dolor\n\ sit ame.\r\n\ --------------------------qWeRtYuIoP--\r\n", ); } /// Test using an external library to prevent the two-wrongs-make-a-right class of errors. #[actix_web::test] async fn ecosystem_compat() { let (pl, headers) = create_form_data_payload_and_headers( "foo", None, None, Bytes::from_static(b"Lorem ipsum dolor\nsit ame."), ); let boundary = find_boundary(&headers); let pl = stream::once(async { Ok::<_, Infallible>(pl) }); let mut form = multer::Multipart::new(pl, boundary); let field = form.next_field().await.unwrap().unwrap(); assert_eq!(field.name().unwrap(), "foo"); assert_eq!(field.file_name(), None); assert_eq!(field.content_type(), None); assert!(field.bytes().await.unwrap().starts_with(b"Lorem")); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-multipart/src/lib.rs
actix-multipart/src/lib.rs
//! Multipart request & form support for Actix Web. //! //! The [`Multipart`] extractor aims to support all kinds of `multipart/*` requests, including //! `multipart/form-data`, `multipart/related` and `multipart/mixed`. This is a lower-level //! extractor which supports reading [multipart fields](Field), in the order they are sent by the //! client. //! //! Due to additional requirements for `multipart/form-data` requests, the higher level //! [`MultipartForm`] extractor and derive macro only supports this media type. //! //! # Examples //! //! ```no_run //! use actix_web::{post, App, HttpServer, Responder}; //! //! use actix_multipart::form::{json::Json as MpJson, tempfile::TempFile, MultipartForm, MultipartFormConfig}; //! use serde::Deserialize; //! //! #[derive(Debug, Deserialize)] //! struct Metadata { //! name: String, //! } //! //! #[derive(Debug, MultipartForm)] //! struct UploadForm { //! // Note: the form is also subject to the global limits configured using `MultipartFormConfig`. //! #[multipart(limit = "100MB")] //! file: TempFile, //! json: MpJson<Metadata>, //! } //! //! #[post("/videos")] //! pub async fn post_video(MultipartForm(form): MultipartForm<UploadForm>) -> impl Responder { //! format!( //! "Uploaded file {}, with size: {}", //! form.json.name, form.file.size //! ) //! } //! //! #[actix_web::main] //! async fn main() -> std::io::Result<()> { //! HttpServer::new(move || { //! App::new() //! .service(post_video) //! // Also increase the global total limit to 100MiB. //! .app_data(MultipartFormConfig::default().total_limit(100 * 1024 * 1024)) //! }) //! .bind(("127.0.0.1", 8080))? //! .run() //! .await //! } //! ``` //! //! cURL request: //! //! ```sh //! curl -v --request POST \ //! --url http://localhost:8080/videos \ //! -F 'json={"name": "Cargo.lock"};type=application/json' \ //! -F file=@./Cargo.lock //! ``` //! //! [`MultipartForm`]: struct@form::MultipartForm #![doc(html_logo_url = "https://actix.rs/img/logo.png")] #![doc(html_favicon_url = "https://actix.rs/favicon.ico")] #![cfg_attr(docsrs, feature(doc_cfg))] // This allows us to use the actix_multipart_derive within this crate's tests #[cfg(test)] extern crate self as actix_multipart; mod error; mod extractor; pub(crate) mod field; pub mod form; mod multipart; pub(crate) mod payload; pub(crate) mod safety; pub mod test; pub use self::{ error::Error as MultipartError, field::{Field, LimitExceeded}, multipart::Multipart, };
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-multipart/src/multipart.rs
actix-multipart/src/multipart.rs
//! Multipart response payload support. use std::{ cell::RefCell, pin::Pin, rc::Rc, task::{Context, Poll}, }; use actix_web::{ dev, error::{ParseError, PayloadError}, http::header::{self, ContentDisposition, HeaderMap, HeaderName, HeaderValue}, web::Bytes, HttpRequest, }; use futures_core::stream::Stream; use mime::Mime; use crate::{ error::Error, field::InnerField, payload::{PayloadBuffer, PayloadRef}, safety::Safety, Field, }; const MAX_HEADERS: usize = 32; /// The server-side implementation of `multipart/form-data` requests. /// /// This will parse the incoming stream into `MultipartItem` instances via its `Stream` /// implementation. `MultipartItem::Field` contains multipart field. `MultipartItem::Multipart` is /// used for nested multipart streams. pub struct Multipart { flow: Flow, safety: Safety, } enum Flow { InFlight(Inner), /// Error container is Some until an error is returned out of the flow. Error(Option<Error>), } impl Multipart { /// Creates multipart instance from parts. pub fn new<S>(headers: &HeaderMap, stream: S) -> Self where S: Stream<Item = Result<Bytes, PayloadError>> + 'static, { match Self::find_ct_and_boundary(headers) { Ok((ct, boundary)) => Self::from_ct_and_boundary(ct, boundary, stream), Err(err) => Self::from_error(err), } } /// Creates multipart instance from parts. pub(crate) fn from_req(req: &HttpRequest, payload: &mut dev::Payload) -> Self { match Self::find_ct_and_boundary(req.headers()) { Ok((ct, boundary)) => Self::from_ct_and_boundary(ct, boundary, payload.take()), Err(err) => Self::from_error(err), } } /// Extract Content-Type and boundary info from headers. pub(crate) fn find_ct_and_boundary(headers: &HeaderMap) -> Result<(Mime, String), Error> { let content_type = headers .get(&header::CONTENT_TYPE) .ok_or(Error::ContentTypeMissing)? .to_str() .ok() .and_then(|content_type| content_type.parse::<Mime>().ok()) .ok_or(Error::ContentTypeParse)?; if content_type.type_() != mime::MULTIPART { return Err(Error::ContentTypeIncompatible); } let boundary = content_type .get_param(mime::BOUNDARY) .ok_or(Error::BoundaryMissing)? .as_str() .to_owned(); Ok((content_type, boundary)) } /// Constructs a new multipart reader from given Content-Type, boundary, and stream. pub(crate) fn from_ct_and_boundary<S>(ct: Mime, boundary: String, stream: S) -> Multipart where S: Stream<Item = Result<Bytes, PayloadError>> + 'static, { Multipart { safety: Safety::new(), flow: Flow::InFlight(Inner { payload: PayloadRef::new(PayloadBuffer::new(stream)), content_type: ct, boundary, state: State::FirstBoundary, item: Item::None, }), } } /// Constructs a new multipart reader from given `MultipartError`. pub(crate) fn from_error(err: Error) -> Multipart { Multipart { flow: Flow::Error(Some(err)), safety: Safety::new(), } } /// Return requests parsed Content-Type or raise the stored error. pub(crate) fn content_type_or_bail(&mut self) -> Result<mime::Mime, Error> { match self.flow { Flow::InFlight(ref inner) => Ok(inner.content_type.clone()), Flow::Error(ref mut err) => Err(err .take() .expect("error should not be taken after it was returned")), } } } impl Stream for Multipart { type Item = Result<Field, Error>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let this = self.get_mut(); match this.flow { Flow::InFlight(ref mut inner) => { if let Some(mut buffer) = inner.payload.get_mut(&this.safety) { // check safety and poll read payload to buffer. buffer.poll_stream(cx)?; } else if !this.safety.is_clean() { // safety violation return Poll::Ready(Some(Err(Error::NotConsumed))); } else { return Poll::Pending; } inner.poll(&this.safety, cx) } Flow::Error(ref mut err) => Poll::Ready(Some(Err(err .take() .expect("Multipart polled after finish")))), } } } #[derive(PartialEq, Debug)] enum State { /// Skip data until first boundary. FirstBoundary, /// Reading boundary. Boundary, /// Reading Headers. Headers, /// Stream EOF. Eof, } enum Item { None, Field(Rc<RefCell<InnerField>>), } struct Inner { /// Request's payload stream & buffer. payload: PayloadRef, /// Request's Content-Type. /// /// Guaranteed to have "multipart" top-level media type, i.e., `multipart/*`. content_type: Mime, /// Field boundary. boundary: String, state: State, item: Item, } impl Inner { fn read_field_headers(payload: &mut PayloadBuffer) -> Result<Option<HeaderMap>, Error> { match payload.read_until(b"\r\n\r\n")? { None => { if payload.eof { Err(Error::Incomplete) } else { Ok(None) } } Some(bytes) => { let mut hdrs = [httparse::EMPTY_HEADER; MAX_HEADERS]; match httparse::parse_headers(&bytes, &mut hdrs).map_err(ParseError::from)? { httparse::Status::Complete((_, hdrs)) => { // convert headers let mut headers = HeaderMap::with_capacity(hdrs.len()); for h in hdrs { let name = HeaderName::try_from(h.name).map_err(|_| ParseError::Header)?; let value = HeaderValue::try_from(h.value).map_err(|_| ParseError::Header)?; headers.append(name, value); } Ok(Some(headers)) } httparse::Status::Partial => Err(ParseError::Header.into()), } } } } /// Reads a field boundary from the payload buffer (and discards it). /// /// Reads "in-between" and "final" boundaries. E.g. for boundary = "foo": /// /// ```plain /// --foo <-- in-between fields /// --foo-- <-- end of request body, should be followed by EOF /// ``` /// /// Returns: /// /// - `Ok(Some(true))` - final field boundary read (EOF) /// - `Ok(Some(false))` - field boundary read /// - `Ok(None)` - boundary not found, more data needs reading /// - `Err(BoundaryMissing)` - multipart boundary is missing fn read_boundary(payload: &mut PayloadBuffer, boundary: &str) -> Result<Option<bool>, Error> { // TODO: need to read epilogue let chunk = match payload.readline_or_eof()? { // TODO: this might be okay as a let Some() else return Ok(None) None => return Ok(payload.eof.then_some(true)), Some(chunk) => chunk, }; const BOUNDARY_MARKER: &[u8] = b"--"; const LINE_BREAK: &[u8] = b"\r\n"; let boundary_len = boundary.len(); if chunk.len() < boundary_len + 2 + 2 || !chunk.starts_with(BOUNDARY_MARKER) || &chunk[2..boundary_len + 2] != boundary.as_bytes() { return Err(Error::BoundaryMissing); } // chunk facts: // - long enough to contain boundary + 2 markers or 1 marker and line-break // - starts with boundary marker // - chunk contains correct boundary if &chunk[boundary_len + 2..] == LINE_BREAK { // boundary is followed by line-break, indicating more fields to come return Ok(Some(false)); } // boundary is followed by marker if &chunk[boundary_len + 2..boundary_len + 4] == BOUNDARY_MARKER && ( // chunk is exactly boundary len + 2 markers chunk.len() == boundary_len + 2 + 2 // final boundary is allowed to end with a line-break || &chunk[boundary_len + 4..] == LINE_BREAK ) { return Ok(Some(true)); } Err(Error::BoundaryMissing) } fn skip_until_boundary( payload: &mut PayloadBuffer, boundary: &str, ) -> Result<Option<bool>, Error> { let mut eof = false; loop { match payload.readline()? { Some(chunk) => { if chunk.is_empty() { return Err(Error::BoundaryMissing); } if chunk.len() < boundary.len() { continue; } if &chunk[..2] == b"--" && &chunk[2..chunk.len() - 2] == boundary.as_bytes() { break; } else { if chunk.len() < boundary.len() + 2 { continue; } let b: &[u8] = boundary.as_ref(); if &chunk[..boundary.len()] == b && &chunk[boundary.len()..boundary.len() + 2] == b"--" { eof = true; break; } } } None => { return if payload.eof { Err(Error::Incomplete) } else { Ok(None) }; } } } Ok(Some(eof)) } fn poll(&mut self, safety: &Safety, cx: &Context<'_>) -> Poll<Option<Result<Field, Error>>> { if self.state == State::Eof { Poll::Ready(None) } else { // release field loop { // Nested multipart streams of fields has to be consumed // before switching to next if safety.current() { let stop = match self.item { Item::Field(ref mut field) => match field.borrow_mut().poll(safety) { Poll::Pending => return Poll::Pending, Poll::Ready(Some(Ok(_))) => continue, Poll::Ready(Some(Err(err))) => return Poll::Ready(Some(Err(err))), Poll::Ready(None) => true, }, Item::None => false, }; if stop { self.item = Item::None; } if let Item::None = self.item { break; } } } let field_headers = if let Some(mut payload) = self.payload.get_mut(safety) { match self.state { // read until first boundary State::FirstBoundary => { match Inner::skip_until_boundary(&mut payload, &self.boundary)? { None => return Poll::Pending, Some(eof) => { if eof { self.state = State::Eof; return Poll::Ready(None); } else { self.state = State::Headers; } } } } // read boundary State::Boundary => match Inner::read_boundary(&mut payload, &self.boundary)? { None => return Poll::Pending, Some(eof) => { if eof { self.state = State::Eof; return Poll::Ready(None); } else { self.state = State::Headers; } } }, _ => {} } // read field headers for next field if self.state == State::Headers { if let Some(headers) = Inner::read_field_headers(&mut payload)? { self.state = State::Boundary; headers } else { return Poll::Pending; } } else { unreachable!() } } else { log::debug!("NotReady: field is in flight"); return Poll::Pending; }; let field_content_disposition = field_headers .get(&header::CONTENT_DISPOSITION) .and_then(|cd| ContentDisposition::from_raw(cd).ok()) .filter(|content_disposition| { matches!( content_disposition.disposition, header::DispositionType::FormData, ) }); let form_field_name = if self.content_type.subtype() == mime::FORM_DATA { // According to RFC 7578 §4.2, which relates to "multipart/form-data" requests // specifically, fields must have a Content-Disposition header, its disposition // type must be set as "form-data", and it must have a name parameter. let Some(cd) = &field_content_disposition else { return Poll::Ready(Some(Err(Error::ContentDispositionMissing))); }; let Some(field_name) = cd.get_name() else { return Poll::Ready(Some(Err(Error::ContentDispositionNameMissing))); }; Some(field_name.to_owned()) } else { None }; // TODO: check out other multipart/* RFCs for specific requirements let field_content_type: Option<Mime> = field_headers .get(&header::CONTENT_TYPE) .and_then(|ct| ct.to_str().ok()) .and_then(|ct| ct.parse().ok()); self.state = State::Boundary; // nested multipart stream is not supported if let Some(mime) = &field_content_type { if mime.type_() == mime::MULTIPART { return Poll::Ready(Some(Err(Error::Nested))); } } let field_inner = InnerField::new_in_rc(self.payload.clone(), self.boundary.clone(), &field_headers)?; self.item = Item::Field(Rc::clone(&field_inner)); Poll::Ready(Some(Ok(Field::new( field_content_type, field_content_disposition, form_field_name, field_headers, safety.clone(cx), field_inner, )))) } } } impl Drop for Inner { fn drop(&mut self) { // InnerMultipartItem::Field has to be dropped first because of Safety. self.item = Item::None; } } #[cfg(test)] mod tests { use std::time::Duration; use actix_http::h1; use actix_web::{ http::header::{DispositionParam, DispositionType}, rt, test::TestRequest, web::{BufMut as _, BytesMut}, FromRequest, }; use assert_matches::assert_matches; use futures_test::stream::StreamTestExt as _; use futures_util::{stream, StreamExt as _}; use tokio::sync::mpsc; use tokio_stream::wrappers::UnboundedReceiverStream; use super::*; const BOUNDARY: &str = "abbc761f78ff4d7cb7573b5a23f96ef0"; #[actix_rt::test] async fn test_boundary() { let headers = HeaderMap::new(); match Multipart::find_ct_and_boundary(&headers) { Err(Error::ContentTypeMissing) => {} _ => unreachable!("should not happen"), } let mut headers = HeaderMap::new(); headers.insert( header::CONTENT_TYPE, header::HeaderValue::from_static("test"), ); match Multipart::find_ct_and_boundary(&headers) { Err(Error::ContentTypeParse) => {} _ => unreachable!("should not happen"), } let mut headers = HeaderMap::new(); headers.insert( header::CONTENT_TYPE, header::HeaderValue::from_static("multipart/mixed"), ); match Multipart::find_ct_and_boundary(&headers) { Err(Error::BoundaryMissing) => {} _ => unreachable!("should not happen"), } let mut headers = HeaderMap::new(); headers.insert( header::CONTENT_TYPE, header::HeaderValue::from_static( "multipart/mixed; boundary=\"5c02368e880e436dab70ed54e1c58209\"", ), ); assert_eq!( Multipart::find_ct_and_boundary(&headers).unwrap().1, "5c02368e880e436dab70ed54e1c58209", ); } fn create_stream() -> ( mpsc::UnboundedSender<Result<Bytes, PayloadError>>, impl Stream<Item = Result<Bytes, PayloadError>>, ) { let (tx, rx) = mpsc::unbounded_channel(); ( tx, UnboundedReceiverStream::new(rx).map(|res| res.map_err(|_| panic!())), ) } fn create_simple_request_with_header() -> (Bytes, HeaderMap) { let (body, headers) = crate::test::create_form_data_payload_and_headers_with_boundary( BOUNDARY, "file", Some("fn.txt".to_owned()), Some(mime::TEXT_PLAIN_UTF_8), Bytes::from_static(b"data"), ); let mut buf = BytesMut::with_capacity(body.len() + 14); // add junk before form to test pre-boundary data rejection buf.put("testasdadsad\r\n".as_bytes()); buf.put(body); (buf.freeze(), headers) } // TODO: use test utility when multi-file support is introduced fn create_double_request_with_header() -> (Bytes, HeaderMap) { let bytes = Bytes::from( "testasdadsad\r\n\ --abbc761f78ff4d7cb7573b5a23f96ef0\r\n\ Content-Disposition: form-data; name=\"file\"; filename=\"fn.txt\"\r\n\ Content-Type: text/plain; charset=utf-8\r\nContent-Length: 4\r\n\r\n\ test\r\n\ --abbc761f78ff4d7cb7573b5a23f96ef0\r\n\ Content-Disposition: form-data; name=\"file\"; filename=\"fn.txt\"\r\n\ Content-Type: text/plain; charset=utf-8\r\nContent-Length: 4\r\n\r\n\ data\r\n\ --abbc761f78ff4d7cb7573b5a23f96ef0--\r\n", ); let mut headers = HeaderMap::new(); headers.insert( header::CONTENT_TYPE, header::HeaderValue::from_static( "multipart/mixed; boundary=\"abbc761f78ff4d7cb7573b5a23f96ef0\"", ), ); (bytes, headers) } #[actix_rt::test] async fn test_multipart_no_end_crlf() { let (sender, payload) = create_stream(); let (mut bytes, headers) = create_double_request_with_header(); let bytes_stripped = bytes.split_to(bytes.len()); // strip crlf sender.send(Ok(bytes_stripped)).unwrap(); drop(sender); // eof let mut multipart = Multipart::new(&headers, payload); match multipart.next().await.unwrap() { Ok(_) => {} _ => unreachable!(), } match multipart.next().await.unwrap() { Ok(_) => {} _ => unreachable!(), } match multipart.next().await { None => {} _ => unreachable!(), } } #[actix_rt::test] async fn test_multipart() { let (sender, payload) = create_stream(); let (bytes, headers) = create_double_request_with_header(); sender.send(Ok(bytes)).unwrap(); let mut multipart = Multipart::new(&headers, payload); match multipart.next().await { Some(Ok(mut field)) => { let cd = field.content_disposition().unwrap(); assert_eq!(cd.disposition, DispositionType::FormData); assert_eq!(cd.parameters[0], DispositionParam::Name("file".into())); assert_eq!(field.content_type().unwrap().type_(), mime::TEXT); assert_eq!(field.content_type().unwrap().subtype(), mime::PLAIN); match field.next().await.unwrap() { Ok(chunk) => assert_eq!(chunk, "test"), _ => unreachable!(), } match field.next().await { None => {} _ => unreachable!(), } } _ => unreachable!(), } match multipart.next().await.unwrap() { Ok(mut field) => { assert_eq!(field.content_type().unwrap().type_(), mime::TEXT); assert_eq!(field.content_type().unwrap().subtype(), mime::PLAIN); match field.next().await { Some(Ok(chunk)) => assert_eq!(chunk, "data"), _ => unreachable!(), } match field.next().await { None => {} _ => unreachable!(), } } _ => unreachable!(), } match multipart.next().await { None => {} _ => unreachable!(), } } // Loops, collecting all bytes until end-of-field async fn get_whole_field(field: &mut Field) -> BytesMut { let mut b = BytesMut::new(); loop { match field.next().await { Some(Ok(chunk)) => b.extend_from_slice(&chunk), None => return b, _ => unreachable!(), } } } #[actix_rt::test] async fn test_stream() { let (bytes, headers) = create_double_request_with_header(); let payload = stream::iter(bytes) .map(|byte| Ok(Bytes::copy_from_slice(&[byte]))) .interleave_pending(); let mut multipart = Multipart::new(&headers, payload); match multipart.next().await.unwrap() { Ok(mut field) => { let cd = field.content_disposition().unwrap(); assert_eq!(cd.disposition, DispositionType::FormData); assert_eq!(cd.parameters[0], DispositionParam::Name("file".into())); assert_eq!(field.content_type().unwrap().type_(), mime::TEXT); assert_eq!(field.content_type().unwrap().subtype(), mime::PLAIN); assert_eq!(get_whole_field(&mut field).await, "test"); } _ => unreachable!(), } match multipart.next().await { Some(Ok(mut field)) => { assert_eq!(field.content_type().unwrap().type_(), mime::TEXT); assert_eq!(field.content_type().unwrap().subtype(), mime::PLAIN); assert_eq!(get_whole_field(&mut field).await, "data"); } _ => unreachable!(), } match multipart.next().await { None => {} _ => unreachable!(), } } #[actix_rt::test] async fn test_multipart_from_error() { let err = Error::ContentTypeMissing; let mut multipart = Multipart::from_error(err); assert!(multipart.next().await.unwrap().is_err()) } #[actix_rt::test] async fn test_multipart_from_boundary() { let (_, payload) = create_stream(); let (_, headers) = create_simple_request_with_header(); let (ct, boundary) = Multipart::find_ct_and_boundary(&headers).unwrap(); let _ = Multipart::from_ct_and_boundary(ct, boundary, payload); } #[actix_rt::test] async fn test_multipart_payload_consumption() { // with sample payload and HttpRequest with no headers let (_, inner_payload) = h1::Payload::create(false); let mut payload = actix_web::dev::Payload::from(inner_payload); let req = TestRequest::default().to_http_request(); // multipart should generate an error let mut mp = Multipart::from_request(&req, &mut payload).await.unwrap(); assert!(mp.next().await.unwrap().is_err()); // and should not consume the payload match payload { actix_web::dev::Payload::H1 { .. } => {} //expected _ => unreachable!(), } } #[actix_rt::test] async fn no_content_disposition_form_data() { let bytes = Bytes::from( "testasdadsad\r\n\ --abbc761f78ff4d7cb7573b5a23f96ef0\r\n\ Content-Type: text/plain; charset=utf-8\r\n\ Content-Length: 4\r\n\ \r\n\ test\r\n\ --abbc761f78ff4d7cb7573b5a23f96ef0\r\n", ); let mut headers = HeaderMap::new(); headers.insert( header::CONTENT_TYPE, header::HeaderValue::from_static( "multipart/form-data; boundary=\"abbc761f78ff4d7cb7573b5a23f96ef0\"", ), ); let payload = stream::iter(bytes) .map(|byte| Ok(Bytes::copy_from_slice(&[byte]))) .interleave_pending(); let mut multipart = Multipart::new(&headers, payload); let res = multipart.next().await.unwrap(); assert_matches!( res.expect_err( "according to RFC 7578, form-data fields require a content-disposition header" ), Error::ContentDispositionMissing ); } #[actix_rt::test] async fn no_content_disposition_non_form_data() { let bytes = Bytes::from( "testasdadsad\r\n\ --abbc761f78ff4d7cb7573b5a23f96ef0\r\n\ Content-Type: text/plain; charset=utf-8\r\n\ Content-Length: 4\r\n\ \r\n\ test\r\n\ --abbc761f78ff4d7cb7573b5a23f96ef0\r\n", ); let mut headers = HeaderMap::new(); headers.insert( header::CONTENT_TYPE, header::HeaderValue::from_static( "multipart/mixed; boundary=\"abbc761f78ff4d7cb7573b5a23f96ef0\"", ), ); let payload = stream::iter(bytes) .map(|byte| Ok(Bytes::copy_from_slice(&[byte]))) .interleave_pending(); let mut multipart = Multipart::new(&headers, payload); let res = multipart.next().await.unwrap(); res.unwrap(); } #[actix_rt::test] async fn no_name_in_form_data_content_disposition() { let bytes = Bytes::from( "testasdadsad\r\n\ --abbc761f78ff4d7cb7573b5a23f96ef0\r\n\ Content-Disposition: form-data; filename=\"fn.txt\"\r\n\ Content-Type: text/plain; charset=utf-8\r\n\ Content-Length: 4\r\n\ \r\n\ test\r\n\ --abbc761f78ff4d7cb7573b5a23f96ef0\r\n", ); let mut headers = HeaderMap::new(); headers.insert( header::CONTENT_TYPE, header::HeaderValue::from_static( "multipart/form-data; boundary=\"abbc761f78ff4d7cb7573b5a23f96ef0\"", ), ); let payload = stream::iter(bytes) .map(|byte| Ok(Bytes::copy_from_slice(&[byte]))) .interleave_pending(); let mut multipart = Multipart::new(&headers, payload); let res = multipart.next().await.unwrap(); assert_matches!( res.expect_err("according to RFC 7578, form-data fields require a name attribute"), Error::ContentDispositionNameMissing ); } #[actix_rt::test] async fn test_drop_multipart_dont_hang() { let (sender, payload) = create_stream(); let (bytes, headers) = create_simple_request_with_header(); sender.send(Ok(bytes)).unwrap(); drop(sender); // eof let mut multipart = Multipart::new(&headers, payload); let mut field = multipart.next().await.unwrap().unwrap(); drop(multipart); // should fail immediately match field.next().await { Some(Err(Error::NotConsumed)) => {} _ => panic!(), }; } #[actix_rt::test] async fn test_drop_field_awaken_multipart() { let (sender, payload) = create_stream(); let (bytes, headers) = create_double_request_with_header(); sender.send(Ok(bytes)).unwrap(); drop(sender); // eof let mut multipart = Multipart::new(&headers, payload); let mut field = multipart.next().await.unwrap().unwrap(); let task = rt::spawn(async move { rt::time::sleep(Duration::from_millis(500)).await; assert_eq!(field.next().await.unwrap().unwrap(), "test"); drop(field); }); // dropping field should awaken current task let _ = multipart.next().await.unwrap().unwrap(); task.await.unwrap(); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-multipart/src/error.rs
actix-multipart/src/error.rs
//! Error and Result module use actix_web::{ error::{ParseError, PayloadError}, http::StatusCode, ResponseError, }; use derive_more::{Display, Error, From}; /// A set of errors that can occur during parsing multipart streams. #[derive(Debug, Display, From, Error)] #[non_exhaustive] pub enum Error { /// Could not find Content-Type header. #[display("Could not find Content-Type header")] ContentTypeMissing, /// Could not parse Content-Type header. #[display("Could not parse Content-Type header")] ContentTypeParse, /// Parsed Content-Type did not have "multipart" top-level media type. /// /// Also raised when extracting a [`MultipartForm`] from a request that does not have the /// "multipart/form-data" media type. /// /// [`MultipartForm`]: struct@crate::form::MultipartForm #[display("Parsed Content-Type did not have 'multipart' top-level media type")] ContentTypeIncompatible, /// Multipart boundary is not found. #[display("Multipart boundary is not found")] BoundaryMissing, /// Content-Disposition header was not found or not of disposition type "form-data" when parsing /// a "form-data" field. /// /// As per [RFC 7578 §4.2], a "multipart/form-data" field's Content-Disposition header must /// always be present and have a disposition type of "form-data". /// /// [RFC 7578 §4.2]: https://datatracker.ietf.org/doc/html/rfc7578#section-4.2 #[display("Content-Disposition header was not found when parsing a \"form-data\" field")] ContentDispositionMissing, /// Content-Disposition name parameter was not found when parsing a "form-data" field. /// /// As per [RFC 7578 §4.2], a "multipart/form-data" field's Content-Disposition header must /// always include a "name" parameter. /// /// [RFC 7578 §4.2]: https://datatracker.ietf.org/doc/html/rfc7578#section-4.2 #[display("Content-Disposition header was not found when parsing a \"form-data\" field")] ContentDispositionNameMissing, /// Nested multipart is not supported. #[display("Nested multipart is not supported")] Nested, /// Multipart stream is incomplete. #[display("Multipart stream is incomplete")] Incomplete, /// Field parsing failed. #[display("Error during field parsing")] Parse(ParseError), /// HTTP payload error. #[display("Payload error")] Payload(PayloadError), /// Stream is not consumed. #[display("Stream is not consumed")] NotConsumed, /// Form field handler raised error. #[display("An error occurred processing field: {name}")] Field { name: String, source: actix_web::Error, }, /// Duplicate field found (for structure that opted-in to denying duplicate fields). #[display("Duplicate field found: {_0}")] #[from(ignore)] DuplicateField(#[error(not(source))] String), /// Required field is missing. #[display("Required field is missing: {_0}")] #[from(ignore)] MissingField(#[error(not(source))] String), /// Unknown field (for structure that opted-in to denying unknown fields). #[display("Unknown field: {_0}")] #[from(ignore)] UnknownField(#[error(not(source))] String), } /// Return `BadRequest` for `MultipartError`. impl ResponseError for Error { fn status_code(&self) -> StatusCode { match &self { Error::Field { source, .. } => source.as_response_error().status_code(), Error::ContentTypeIncompatible => StatusCode::UNSUPPORTED_MEDIA_TYPE, _ => StatusCode::BAD_REQUEST, } } } #[cfg(test)] mod tests { use super::*; #[test] fn test_multipart_error() { let resp = Error::BoundaryMissing.error_response(); assert_eq!(resp.status(), StatusCode::BAD_REQUEST); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-multipart/src/payload.rs
actix-multipart/src/payload.rs
use std::{ cell::{RefCell, RefMut}, cmp, mem, pin::Pin, rc::Rc, task::{Context, Poll}, }; use actix_web::{ error::PayloadError, web::{Bytes, BytesMut}, }; use futures_core::stream::{LocalBoxStream, Stream}; use crate::{error::Error, safety::Safety}; pub(crate) struct PayloadRef { payload: Rc<RefCell<PayloadBuffer>>, } impl PayloadRef { pub(crate) fn new(payload: PayloadBuffer) -> PayloadRef { PayloadRef { payload: Rc::new(RefCell::new(payload)), } } pub(crate) fn get_mut(&self, safety: &Safety) -> Option<RefMut<'_, PayloadBuffer>> { if safety.current() { Some(self.payload.borrow_mut()) } else { None } } } impl Clone for PayloadRef { fn clone(&self) -> PayloadRef { PayloadRef { payload: Rc::clone(&self.payload), } } } /// Payload buffer. pub(crate) struct PayloadBuffer { pub(crate) stream: LocalBoxStream<'static, Result<Bytes, PayloadError>>, pub(crate) buf: BytesMut, /// EOF flag. If true, no more payload reads will be attempted. pub(crate) eof: bool, } impl PayloadBuffer { /// Constructs new payload buffer. pub(crate) fn new<S>(stream: S) -> Self where S: Stream<Item = Result<Bytes, PayloadError>> + 'static, { PayloadBuffer { stream: Box::pin(stream), buf: BytesMut::with_capacity(1_024), // pre-allocate 1KiB eof: false, } } pub(crate) fn poll_stream(&mut self, cx: &mut Context<'_>) -> Result<(), PayloadError> { loop { match Pin::new(&mut self.stream).poll_next(cx) { Poll::Ready(Some(Ok(data))) => { self.buf.extend_from_slice(&data); // try to read more data continue; } Poll::Ready(Some(Err(err))) => return Err(err), Poll::Ready(None) => { self.eof = true; return Ok(()); } Poll::Pending => return Ok(()), } } } /// Reads exact number of bytes. #[cfg(test)] pub(crate) fn read_exact(&mut self, size: usize) -> Option<Bytes> { if size <= self.buf.len() { Some(self.buf.split_to(size).freeze()) } else { None } } pub(crate) fn read_max(&mut self, size: u64) -> Result<Option<Bytes>, Error> { if !self.buf.is_empty() { let size = cmp::min(self.buf.len() as u64, size) as usize; Ok(Some(self.buf.split_to(size).freeze())) } else if self.eof { Err(Error::Incomplete) } else { Ok(None) } } /// Reads until specified ending. /// /// Returns: /// /// - `Ok(Some(chunk))` - `needle` is found, with chunk ending after needle /// - `Err(Incomplete)` - `needle` is not found and we're at EOF /// - `Ok(None)` - `needle` is not found otherwise pub(crate) fn read_until(&mut self, needle: &[u8]) -> Result<Option<Bytes>, Error> { match memchr::memmem::find(&self.buf, needle) { // buffer exhausted and EOF without finding needle None if self.eof => Err(Error::Incomplete), // needle not yet found None => Ok(None), // needle found, split chunk out of buf Some(idx) => Ok(Some(self.buf.split_to(idx + needle.len()).freeze())), } } /// Reads bytes until new line delimiter (`\n`, `0x0A`). /// /// Returns: /// /// - `Ok(Some(chunk))` - `needle` is found, with chunk ending after needle /// - `Err(Incomplete)` - `needle` is not found and we're at EOF /// - `Ok(None)` - `needle` is not found otherwise #[inline] pub(crate) fn readline(&mut self) -> Result<Option<Bytes>, Error> { self.read_until(b"\n") } /// Reads bytes until new line delimiter or until EOF. #[inline] pub(crate) fn readline_or_eof(&mut self) -> Result<Option<Bytes>, Error> { match self.readline() { Err(Error::Incomplete) if self.eof => Ok(Some(self.buf.split().freeze())), line => line, } } /// Puts unprocessed data back to the buffer. pub(crate) fn unprocessed(&mut self, data: Bytes) { // TODO: use BytesMut::from when it's released, see https://github.com/tokio-rs/bytes/pull/710 let buf = BytesMut::from(&data[..]); let buf = mem::replace(&mut self.buf, buf); self.buf.extend_from_slice(&buf); } } #[cfg(test)] mod tests { use actix_http::h1; use futures_util::future::lazy; use super::*; #[actix_rt::test] async fn basic() { let (_, payload) = h1::Payload::create(false); let mut payload = PayloadBuffer::new(payload); assert_eq!(payload.buf.len(), 0); lazy(|cx| payload.poll_stream(cx)).await.unwrap(); assert_eq!(None, payload.read_max(1).unwrap()); } #[actix_rt::test] async fn eof() { let (mut sender, payload) = h1::Payload::create(false); let mut payload = PayloadBuffer::new(payload); assert_eq!(None, payload.read_max(4).unwrap()); sender.feed_data(Bytes::from("data")); sender.feed_eof(); lazy(|cx| payload.poll_stream(cx)).await.unwrap(); assert_eq!(Some(Bytes::from("data")), payload.read_max(4).unwrap()); assert_eq!(payload.buf.len(), 0); assert!(payload.read_max(1).is_err()); assert!(payload.eof); } #[actix_rt::test] async fn err() { let (mut sender, payload) = h1::Payload::create(false); let mut payload = PayloadBuffer::new(payload); assert_eq!(None, payload.read_max(1).unwrap()); sender.set_error(PayloadError::Incomplete(None)); lazy(|cx| payload.poll_stream(cx)).await.err().unwrap(); } #[actix_rt::test] async fn read_max() { let (mut sender, payload) = h1::Payload::create(false); let mut payload = PayloadBuffer::new(payload); sender.feed_data(Bytes::from("line1")); sender.feed_data(Bytes::from("line2")); lazy(|cx| payload.poll_stream(cx)).await.unwrap(); assert_eq!(payload.buf.len(), 10); assert_eq!(Some(Bytes::from("line1")), payload.read_max(5).unwrap()); assert_eq!(payload.buf.len(), 5); assert_eq!(Some(Bytes::from("line2")), payload.read_max(5).unwrap()); assert_eq!(payload.buf.len(), 0); } #[actix_rt::test] async fn read_exactly() { let (mut sender, payload) = h1::Payload::create(false); let mut payload = PayloadBuffer::new(payload); assert_eq!(None, payload.read_exact(2)); sender.feed_data(Bytes::from("line1")); sender.feed_data(Bytes::from("line2")); lazy(|cx| payload.poll_stream(cx)).await.unwrap(); assert_eq!(Some(Bytes::from_static(b"li")), payload.read_exact(2)); assert_eq!(payload.buf.len(), 8); assert_eq!(Some(Bytes::from_static(b"ne1l")), payload.read_exact(4)); assert_eq!(payload.buf.len(), 4); } #[actix_rt::test] async fn read_until() { let (mut sender, payload) = h1::Payload::create(false); let mut payload = PayloadBuffer::new(payload); assert_eq!(None, payload.read_until(b"ne").unwrap()); sender.feed_data(Bytes::from("line1")); sender.feed_data(Bytes::from("line2")); lazy(|cx| payload.poll_stream(cx)).await.unwrap(); assert_eq!( Some(Bytes::from("line")), payload.read_until(b"ne").unwrap() ); assert_eq!(payload.buf.len(), 6); assert_eq!( Some(Bytes::from("1line2")), payload.read_until(b"2").unwrap() ); assert_eq!(payload.buf.len(), 0); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-multipart/src/form/bytes.rs
actix-multipart/src/form/bytes.rs
//! Reads a field into memory. use actix_web::{web::BytesMut, HttpRequest}; use futures_core::future::LocalBoxFuture; use futures_util::TryStreamExt as _; use mime::Mime; use crate::{ form::{FieldReader, Limits}, Field, MultipartError, }; /// Read the field into memory. #[derive(Debug)] pub struct Bytes { /// The data. pub data: actix_web::web::Bytes, /// The value of the `Content-Type` header. pub content_type: Option<Mime>, /// The `filename` value in the `Content-Disposition` header. pub file_name: Option<String>, } impl<'t> FieldReader<'t> for Bytes { type Future = LocalBoxFuture<'t, Result<Self, MultipartError>>; fn read_field(_: &'t HttpRequest, mut field: Field, limits: &'t mut Limits) -> Self::Future { Box::pin(async move { let mut buf = BytesMut::with_capacity(131_072); while let Some(chunk) = field.try_next().await? { limits.try_consume_limits(chunk.len(), true)?; buf.extend(chunk); } Ok(Bytes { data: buf.freeze(), content_type: field.content_type().map(ToOwned::to_owned), file_name: field .content_disposition() .expect("multipart form fields should have a content-disposition header") .get_filename() .map(ToOwned::to_owned), }) }) } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-multipart/src/form/json.rs
actix-multipart/src/form/json.rs
//! Deserializes a field as JSON. use std::sync::Arc; use actix_web::{http::StatusCode, web, Error, HttpRequest, ResponseError}; use derive_more::{Deref, DerefMut, Display, Error}; use futures_core::future::LocalBoxFuture; use serde::de::DeserializeOwned; use super::FieldErrorHandler; use crate::{ form::{bytes::Bytes, FieldReader, Limits}, Field, MultipartError, }; /// Deserialize from JSON. #[derive(Debug, Deref, DerefMut)] pub struct Json<T: DeserializeOwned>(pub T); impl<T: DeserializeOwned> Json<T> { pub fn into_inner(self) -> T { self.0 } } impl<'t, T> FieldReader<'t> for Json<T> where T: DeserializeOwned + 'static, { type Future = LocalBoxFuture<'t, Result<Self, MultipartError>>; fn read_field(req: &'t HttpRequest, field: Field, limits: &'t mut Limits) -> Self::Future { Box::pin(async move { let config = JsonConfig::from_req(req); if config.validate_content_type { let valid = if let Some(mime) = field.content_type() { mime.subtype() == mime::JSON || mime.suffix() == Some(mime::JSON) } else { false }; if !valid { return Err(MultipartError::Field { name: field.form_field_name, source: config.map_error(req, JsonFieldError::ContentType), }); } } let form_field_name = field.form_field_name.clone(); let bytes = Bytes::read_field(req, field, limits).await?; Ok(Json(serde_json::from_slice(bytes.data.as_ref()).map_err( |err| MultipartError::Field { name: form_field_name, source: config.map_error(req, JsonFieldError::Deserialize(err)), }, )?)) }) } } #[derive(Debug, Display, Error)] #[non_exhaustive] pub enum JsonFieldError { /// Deserialize error. #[display("Json deserialize error: {}", _0)] Deserialize(serde_json::Error), /// Content type error. #[display("Content type error")] ContentType, } impl ResponseError for JsonFieldError { fn status_code(&self) -> StatusCode { StatusCode::BAD_REQUEST } } /// Configuration for the [`Json`] field reader. #[derive(Clone)] pub struct JsonConfig { err_handler: FieldErrorHandler<JsonFieldError>, validate_content_type: bool, } const DEFAULT_CONFIG: JsonConfig = JsonConfig { err_handler: None, validate_content_type: true, }; impl JsonConfig { pub fn error_handler<F>(mut self, f: F) -> Self where F: Fn(JsonFieldError, &HttpRequest) -> Error + Send + Sync + 'static, { self.err_handler = Some(Arc::new(f)); self } /// Extract payload config from app data. Check both `T` and `Data<T>`, in that order, and fall /// back to the default payload config. fn from_req(req: &HttpRequest) -> &Self { req.app_data::<Self>() .or_else(|| req.app_data::<web::Data<Self>>().map(|d| d.as_ref())) .unwrap_or(&DEFAULT_CONFIG) } fn map_error(&self, req: &HttpRequest, err: JsonFieldError) -> Error { if let Some(err_handler) = self.err_handler.as_ref() { (*err_handler)(err, req) } else { err.into() } } /// Sets whether or not the field must have a valid `Content-Type` header to be parsed. pub fn validate_content_type(mut self, validate_content_type: bool) -> Self { self.validate_content_type = validate_content_type; self } } impl Default for JsonConfig { fn default() -> Self { DEFAULT_CONFIG } } #[cfg(test)] mod tests { use std::collections::HashMap; use actix_web::{http::StatusCode, web, web::Bytes, App, HttpResponse, Responder}; use crate::form::{ json::{Json, JsonConfig}, MultipartForm, }; #[derive(MultipartForm)] struct JsonForm { json: Json<HashMap<String, String>>, } async fn test_json_route(form: MultipartForm<JsonForm>) -> impl Responder { let mut expected = HashMap::new(); expected.insert("key1".to_owned(), "value1".to_owned()); expected.insert("key2".to_owned(), "value2".to_owned()); assert_eq!(&*form.json, &expected); HttpResponse::Ok().finish() } const TEST_JSON: &str = r#"{"key1": "value1", "key2": "value2"}"#; #[actix_rt::test] async fn test_json_without_content_type() { let srv = actix_test::start(|| { App::new() .route("/", web::post().to(test_json_route)) .app_data(JsonConfig::default().validate_content_type(false)) }); let (body, headers) = crate::test::create_form_data_payload_and_headers( "json", None, None, Bytes::from_static(TEST_JSON.as_bytes()), ); let mut req = srv.post("/"); *req.headers_mut() = headers; let res = req.send_body(body).await.unwrap(); assert_eq!(res.status(), StatusCode::OK); } #[actix_rt::test] async fn test_content_type_validation() { let srv = actix_test::start(|| { App::new() .route("/", web::post().to(test_json_route)) .app_data(JsonConfig::default().validate_content_type(true)) }); // Deny because wrong content type let (body, headers) = crate::test::create_form_data_payload_and_headers( "json", None, Some(mime::APPLICATION_OCTET_STREAM), Bytes::from_static(TEST_JSON.as_bytes()), ); let mut req = srv.post("/"); *req.headers_mut() = headers; let res = req.send_body(body).await.unwrap(); assert_eq!(res.status(), StatusCode::BAD_REQUEST); // Allow because correct content type let (body, headers) = crate::test::create_form_data_payload_and_headers( "json", None, Some(mime::APPLICATION_JSON), Bytes::from_static(TEST_JSON.as_bytes()), ); let mut req = srv.post("/"); *req.headers_mut() = headers; let res = req.send_body(body).await.unwrap(); assert_eq!(res.status(), StatusCode::OK); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-multipart/src/form/text.rs
actix-multipart/src/form/text.rs
//! Deserializes a field from plain text. use std::{str, sync::Arc}; use actix_web::{http::StatusCode, web, Error, HttpRequest, ResponseError}; use derive_more::{Deref, DerefMut, Display, Error}; use futures_core::future::LocalBoxFuture; use serde::de::DeserializeOwned; use super::FieldErrorHandler; use crate::{ form::{bytes::Bytes, FieldReader, Limits}, Field, MultipartError, }; /// Deserialize from plain text. /// /// Internally this uses [`serde_plain`] for deserialization, which supports primitive types /// including strings, numbers, and simple enums. #[derive(Debug, Deref, DerefMut)] pub struct Text<T: DeserializeOwned>(pub T); impl<T: DeserializeOwned> Text<T> { /// Unwraps into inner value. pub fn into_inner(self) -> T { self.0 } } impl<'t, T> FieldReader<'t> for Text<T> where T: DeserializeOwned + 'static, { type Future = LocalBoxFuture<'t, Result<Self, MultipartError>>; fn read_field(req: &'t HttpRequest, field: Field, limits: &'t mut Limits) -> Self::Future { Box::pin(async move { let config = TextConfig::from_req(req); if config.validate_content_type { let valid = if let Some(mime) = field.content_type() { mime.subtype() == mime::PLAIN || mime.suffix() == Some(mime::PLAIN) } else { // https://datatracker.ietf.org/doc/html/rfc7578#section-4.4 // content type defaults to text/plain, so None should be considered valid true }; if !valid { return Err(MultipartError::Field { name: field.form_field_name, source: config.map_error(req, TextError::ContentType), }); } } let form_field_name = field.form_field_name.clone(); let bytes = Bytes::read_field(req, field, limits).await?; let text = str::from_utf8(&bytes.data).map_err(|err| MultipartError::Field { name: form_field_name.clone(), source: config.map_error(req, TextError::Utf8Error(err)), })?; Ok(Text(serde_plain::from_str(text).map_err(|err| { MultipartError::Field { name: form_field_name, source: config.map_error(req, TextError::Deserialize(err)), } })?)) }) } } #[derive(Debug, Display, Error)] #[non_exhaustive] pub enum TextError { /// UTF-8 decoding error. #[display("UTF-8 decoding error: {}", _0)] Utf8Error(str::Utf8Error), /// Deserialize error. #[display("Plain text deserialize error: {}", _0)] Deserialize(serde_plain::Error), /// Content type error. #[display("Content type error")] ContentType, } impl ResponseError for TextError { fn status_code(&self) -> StatusCode { StatusCode::BAD_REQUEST } } /// Configuration for the [`Text`] field reader. #[derive(Clone)] pub struct TextConfig { err_handler: FieldErrorHandler<TextError>, validate_content_type: bool, } impl TextConfig { /// Sets custom error handler. pub fn error_handler<F>(mut self, f: F) -> Self where F: Fn(TextError, &HttpRequest) -> Error + Send + Sync + 'static, { self.err_handler = Some(Arc::new(f)); self } /// Extracts payload config from app data. Check both `T` and `Data<T>`, in that order, and fall /// back to the default payload config. fn from_req(req: &HttpRequest) -> &Self { req.app_data::<Self>() .or_else(|| req.app_data::<web::Data<Self>>().map(|d| d.as_ref())) .unwrap_or(&DEFAULT_CONFIG) } fn map_error(&self, req: &HttpRequest, err: TextError) -> Error { if let Some(ref err_handler) = self.err_handler { (err_handler)(err, req) } else { err.into() } } /// Sets whether or not the field must have a valid `Content-Type` header to be parsed. /// /// Note that an empty `Content-Type` is also accepted, as the multipart specification defines /// `text/plain` as the default for text fields. pub fn validate_content_type(mut self, validate_content_type: bool) -> Self { self.validate_content_type = validate_content_type; self } } const DEFAULT_CONFIG: TextConfig = TextConfig { err_handler: None, validate_content_type: true, }; impl Default for TextConfig { fn default() -> Self { DEFAULT_CONFIG } } #[cfg(test)] mod tests { use std::io::Cursor; use actix_multipart_rfc7578::client::multipart; use actix_web::{http::StatusCode, web, App, HttpResponse, Responder}; use crate::form::{ tests::send_form, text::{Text, TextConfig}, MultipartForm, }; #[derive(MultipartForm)] struct TextForm { number: Text<i32>, } async fn test_text_route(form: MultipartForm<TextForm>) -> impl Responder { assert_eq!(*form.number, 1025); HttpResponse::Ok().finish() } #[actix_rt::test] async fn test_content_type_validation() { let srv = actix_test::start(|| { App::new() .route("/", web::post().to(test_text_route)) .app_data(TextConfig::default().validate_content_type(true)) }); // Deny because wrong content type let bytes = Cursor::new("1025"); let mut form = multipart::Form::default(); form.add_reader_file_with_mime("number", bytes, "", mime::APPLICATION_OCTET_STREAM); let response = send_form(&srv, form, "/").await; assert_eq!(response.status(), StatusCode::BAD_REQUEST); // Allow because correct content type let bytes = Cursor::new("1025"); let mut form = multipart::Form::default(); form.add_reader_file_with_mime("number", bytes, "", mime::TEXT_PLAIN); let response = send_form(&srv, form, "/").await; assert_eq!(response.status(), StatusCode::OK); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-multipart/src/form/mod.rs
actix-multipart/src/form/mod.rs
//! Extract and process typed data from fields of a `multipart/form-data` request. use std::{ any::Any, collections::HashMap, future::{ready, Future}, sync::Arc, }; use actix_web::{dev, error::PayloadError, web, Error, FromRequest, HttpRequest}; use derive_more::{Deref, DerefMut}; use futures_core::future::LocalBoxFuture; use futures_util::{TryFutureExt as _, TryStreamExt as _}; use crate::{Field, Multipart, MultipartError}; pub mod bytes; pub mod json; #[cfg(feature = "tempfile")] pub mod tempfile; pub mod text; #[cfg(feature = "derive")] pub use actix_multipart_derive::MultipartForm; type FieldErrorHandler<T> = Option<Arc<dyn Fn(T, &HttpRequest) -> Error + Send + Sync>>; /// Trait that data types to be used in a multipart form struct should implement. /// /// It represents an asynchronous handler that processes a multipart field to produce `Self`. pub trait FieldReader<'t>: Sized + Any { /// Future that resolves to a `Self`. type Future: Future<Output = Result<Self, MultipartError>>; /// The form will call this function to handle the field. /// /// # Panics /// /// When reading the `field` payload using its `Stream` implementation, polling (manually or via /// `next()`/`try_next()`) may panic after the payload is exhausted. If this is a problem for /// your implementation of this method, you should [`fuse()`] the `Field` first. /// /// [`fuse()`]: futures_util::stream::StreamExt::fuse() fn read_field(req: &'t HttpRequest, field: Field, limits: &'t mut Limits) -> Self::Future; } /// Used to accumulate the state of the loaded fields. #[doc(hidden)] #[derive(Default, Deref, DerefMut)] pub struct State(pub HashMap<String, Box<dyn Any>>); /// Trait that the field collection types implement, i.e. `Vec<T>`, `Option<T>`, or `T` itself. #[doc(hidden)] pub trait FieldGroupReader<'t>: Sized + Any { type Future: Future<Output = Result<(), MultipartError>>; /// The form will call this function for each matching field. fn handle_field( req: &'t HttpRequest, field: Field, limits: &'t mut Limits, state: &'t mut State, duplicate_field: DuplicateField, ) -> Self::Future; /// Construct `Self` from the group of processed fields. fn from_state(name: &str, state: &'t mut State) -> Result<Self, MultipartError>; } impl<'t, T> FieldGroupReader<'t> for Option<T> where T: FieldReader<'t>, { type Future = LocalBoxFuture<'t, Result<(), MultipartError>>; fn handle_field( req: &'t HttpRequest, field: Field, limits: &'t mut Limits, state: &'t mut State, duplicate_field: DuplicateField, ) -> Self::Future { if state.contains_key(&field.form_field_name) { match duplicate_field { DuplicateField::Ignore => return Box::pin(ready(Ok(()))), DuplicateField::Deny => { return Box::pin(ready(Err(MultipartError::DuplicateField( field.form_field_name, )))) } DuplicateField::Replace => {} } } Box::pin(async move { let field_name = field.form_field_name.clone(); let t = T::read_field(req, field, limits).await?; state.insert(field_name, Box::new(t)); Ok(()) }) } fn from_state(name: &str, state: &'t mut State) -> Result<Self, MultipartError> { Ok(state.remove(name).map(|m| *m.downcast::<T>().unwrap())) } } impl<'t, T> FieldGroupReader<'t> for Vec<T> where T: FieldReader<'t>, { type Future = LocalBoxFuture<'t, Result<(), MultipartError>>; fn handle_field( req: &'t HttpRequest, field: Field, limits: &'t mut Limits, state: &'t mut State, _duplicate_field: DuplicateField, ) -> Self::Future { Box::pin(async move { // Note: Vec GroupReader always allows duplicates let vec = state .entry(field.form_field_name.clone()) .or_insert_with(|| Box::<Vec<T>>::default()) .downcast_mut::<Vec<T>>() .unwrap(); let item = T::read_field(req, field, limits).await?; vec.push(item); Ok(()) }) } fn from_state(name: &str, state: &'t mut State) -> Result<Self, MultipartError> { Ok(state .remove(name) .map(|m| *m.downcast::<Vec<T>>().unwrap()) .unwrap_or_default()) } } impl<'t, T> FieldGroupReader<'t> for T where T: FieldReader<'t>, { type Future = LocalBoxFuture<'t, Result<(), MultipartError>>; fn handle_field( req: &'t HttpRequest, field: Field, limits: &'t mut Limits, state: &'t mut State, duplicate_field: DuplicateField, ) -> Self::Future { if state.contains_key(&field.form_field_name) { match duplicate_field { DuplicateField::Ignore => return Box::pin(ready(Ok(()))), DuplicateField::Deny => { return Box::pin(ready(Err(MultipartError::DuplicateField( field.form_field_name, )))) } DuplicateField::Replace => {} } } Box::pin(async move { let field_name = field.form_field_name.clone(); let t = T::read_field(req, field, limits).await?; state.insert(field_name, Box::new(t)); Ok(()) }) } fn from_state(name: &str, state: &'t mut State) -> Result<Self, MultipartError> { state .remove(name) .map(|m| *m.downcast::<T>().unwrap()) .ok_or_else(|| MultipartError::MissingField(name.to_owned())) } } /// Trait that allows a type to be used in the [`struct@MultipartForm`] extractor. /// /// You should use the [`macro@MultipartForm`] macro to derive this for your struct. pub trait MultipartCollect: Sized { /// An optional limit in bytes to be applied a given field name. Note this limit will be shared /// across all fields sharing the same name. fn limit(field_name: &str) -> Option<usize>; /// The extractor will call this function for each incoming field, the state can be updated /// with the processed field data. fn handle_field<'t>( req: &'t HttpRequest, field: Field, limits: &'t mut Limits, state: &'t mut State, ) -> LocalBoxFuture<'t, Result<(), MultipartError>>; /// Once all the fields have been processed and stored in the state, this is called /// to convert into the struct representation. fn from_state(state: State) -> Result<Self, MultipartError>; } #[doc(hidden)] pub enum DuplicateField { /// Additional fields are not processed. Ignore, /// An error will be raised. Deny, /// All fields will be processed, the last one will replace all previous. Replace, } /// Used to keep track of the remaining limits for the form and current field. pub struct Limits { pub total_limit_remaining: usize, pub memory_limit_remaining: usize, pub field_limit_remaining: Option<usize>, } impl Limits { pub fn new(total_limit: usize, memory_limit: usize) -> Self { Self { total_limit_remaining: total_limit, memory_limit_remaining: memory_limit, field_limit_remaining: None, } } /// This function should be called within a [`FieldReader`] when reading each chunk of a field /// to ensure that the form limits are not exceeded. /// /// # Arguments /// /// * `bytes` - The number of bytes being read from this chunk /// * `in_memory` - Whether to consume from the memory limits pub fn try_consume_limits( &mut self, bytes: usize, in_memory: bool, ) -> Result<(), MultipartError> { self.total_limit_remaining = self .total_limit_remaining .checked_sub(bytes) .ok_or(MultipartError::Payload(PayloadError::Overflow))?; if in_memory { self.memory_limit_remaining = self .memory_limit_remaining .checked_sub(bytes) .ok_or(MultipartError::Payload(PayloadError::Overflow))?; } if let Some(field_limit) = self.field_limit_remaining { self.field_limit_remaining = Some( field_limit .checked_sub(bytes) .ok_or(MultipartError::Payload(PayloadError::Overflow))?, ); } Ok(()) } } /// Typed `multipart/form-data` extractor. /// /// To extract typed data from a multipart stream, the inner type `T` must implement the /// [`MultipartCollect`] trait. You should use the [`macro@MultipartForm`] macro to derive this /// for your struct. /// /// Note that this extractor rejects requests with any other Content-Type such as `multipart/mixed`, /// `multipart/related`, or non-multipart media types. /// /// Add a [`MultipartFormConfig`] to your app data to configure extraction. #[derive(Deref, DerefMut)] pub struct MultipartForm<T: MultipartCollect>(pub T); impl<T: MultipartCollect> MultipartForm<T> { /// Unwrap into inner `T` value. pub fn into_inner(self) -> T { self.0 } } impl<T> FromRequest for MultipartForm<T> where T: MultipartCollect + 'static, { type Error = Error; type Future = LocalBoxFuture<'static, Result<Self, Self::Error>>; #[inline] fn from_request(req: &HttpRequest, payload: &mut dev::Payload) -> Self::Future { let mut multipart = Multipart::from_req(req, payload); let content_type = match multipart.content_type_or_bail() { Ok(content_type) => content_type, Err(err) => return Box::pin(ready(Err(err.into()))), }; if content_type.subtype() != mime::FORM_DATA { // this extractor only supports multipart/form-data return Box::pin(ready(Err(MultipartError::ContentTypeIncompatible.into()))); }; let config = MultipartFormConfig::from_req(req); let mut limits = Limits::new(config.total_limit, config.memory_limit); let req = req.clone(); let req2 = req.clone(); let err_handler = config.err_handler.clone(); Box::pin( async move { let mut state = State::default(); // ensure limits are shared for all fields with this name let mut field_limits = HashMap::<String, Option<usize>>::new(); while let Some(field) = multipart.try_next().await? { debug_assert!( !field.form_field_name.is_empty(), "multipart form fields should have names", ); // Retrieve the limit for this field let entry = field_limits .entry(field.form_field_name.clone()) .or_insert_with(|| T::limit(&field.form_field_name)); limits.field_limit_remaining.clone_from(entry); T::handle_field(&req, field, &mut limits, &mut state).await?; // Update the stored limit *entry = limits.field_limit_remaining; } let inner = T::from_state(state)?; Ok(MultipartForm(inner)) } .map_err(move |err| { if let Some(handler) = err_handler { (*handler)(err, &req2) } else { err.into() } }), ) } } type MultipartFormErrorHandler = Option<Arc<dyn Fn(MultipartError, &HttpRequest) -> Error + Send + Sync>>; /// [`struct@MultipartForm`] extractor configuration. /// /// Add to your app data to have it picked up by [`struct@MultipartForm`] extractors. #[derive(Clone)] pub struct MultipartFormConfig { total_limit: usize, memory_limit: usize, err_handler: MultipartFormErrorHandler, } impl MultipartFormConfig { /// Sets maximum accepted payload size for the entire form. By default this limit is 50MiB. pub fn total_limit(mut self, total_limit: usize) -> Self { self.total_limit = total_limit; self } /// Sets maximum accepted data that will be read into memory. By default this limit is 2MiB. pub fn memory_limit(mut self, memory_limit: usize) -> Self { self.memory_limit = memory_limit; self } /// Sets custom error handler. pub fn error_handler<F>(mut self, f: F) -> Self where F: Fn(MultipartError, &HttpRequest) -> Error + Send + Sync + 'static, { self.err_handler = Some(Arc::new(f)); self } /// Extracts payload config from app data. Check both `T` and `Data<T>`, in that order, and fall /// back to the default payload config. fn from_req(req: &HttpRequest) -> &Self { req.app_data::<Self>() .or_else(|| req.app_data::<web::Data<Self>>().map(|d| d.as_ref())) .unwrap_or(&DEFAULT_CONFIG) } } const DEFAULT_CONFIG: MultipartFormConfig = MultipartFormConfig { total_limit: 52_428_800, // 50 MiB memory_limit: 2_097_152, // 2 MiB err_handler: None, }; impl Default for MultipartFormConfig { fn default() -> Self { DEFAULT_CONFIG } } #[cfg(test)] mod tests { use actix_http::encoding::Decoder; use actix_multipart_rfc7578::client::multipart; use actix_test::TestServer; use actix_web::{ dev::Payload, http::StatusCode, web, App, HttpRequest, HttpResponse, Resource, Responder, }; use awc::{Client, ClientResponse}; use futures_core::future::LocalBoxFuture; use futures_util::TryStreamExt as _; use super::MultipartForm; use crate::{ form::{ bytes::Bytes, tempfile::TempFile, text::Text, FieldReader, Limits, MultipartFormConfig, }, Field, MultipartError, }; pub async fn send_form( srv: &TestServer, form: multipart::Form<'static>, uri: &'static str, ) -> ClientResponse<Decoder<Payload>> { Client::default() .post(srv.url(uri)) .content_type(form.content_type()) .send_body(multipart::Body::from(form)) .await .unwrap() } /// Test `Option` fields. #[derive(MultipartForm)] struct TestOptions { field1: Option<Text<String>>, field2: Option<Text<String>>, } async fn test_options_route(form: MultipartForm<TestOptions>) -> impl Responder { assert!(form.field1.is_some()); assert!(form.field2.is_none()); HttpResponse::Ok().finish() } #[actix_rt::test] async fn test_options() { let srv = actix_test::start(|| App::new().route("/", web::post().to(test_options_route))); let mut form = multipart::Form::default(); form.add_text("field1", "value"); let response = send_form(&srv, form, "/").await; assert_eq!(response.status(), StatusCode::OK); } /// Test `Vec` fields. #[derive(MultipartForm)] struct TestVec { list1: Vec<Text<String>>, list2: Vec<Text<String>>, } async fn test_vec_route(form: MultipartForm<TestVec>) -> impl Responder { let form = form.into_inner(); let strings = form .list1 .into_iter() .map(|s| s.into_inner()) .collect::<Vec<_>>(); assert_eq!(strings, vec!["value1", "value2", "value3"]); assert_eq!(form.list2.len(), 0); HttpResponse::Ok().finish() } #[actix_rt::test] async fn test_vec() { let srv = actix_test::start(|| App::new().route("/", web::post().to(test_vec_route))); let mut form = multipart::Form::default(); form.add_text("list1", "value1"); form.add_text("list1", "value2"); form.add_text("list1", "value3"); let response = send_form(&srv, form, "/").await; assert_eq!(response.status(), StatusCode::OK); } /// Test the `rename` field attribute. #[derive(MultipartForm)] struct TestFieldRenaming { #[multipart(rename = "renamed")] field1: Text<String>, #[multipart(rename = "field1")] field2: Text<String>, field3: Text<String>, } async fn test_field_renaming_route(form: MultipartForm<TestFieldRenaming>) -> impl Responder { assert_eq!(&*form.field1, "renamed"); assert_eq!(&*form.field2, "field1"); assert_eq!(&*form.field3, "field3"); HttpResponse::Ok().finish() } #[actix_rt::test] async fn test_field_renaming() { let srv = actix_test::start(|| App::new().route("/", web::post().to(test_field_renaming_route))); let mut form = multipart::Form::default(); form.add_text("renamed", "renamed"); form.add_text("field1", "field1"); form.add_text("field3", "field3"); let response = send_form(&srv, form, "/").await; assert_eq!(response.status(), StatusCode::OK); } /// Test the `deny_unknown_fields` struct attribute. #[derive(MultipartForm)] #[multipart(deny_unknown_fields)] struct TestDenyUnknown {} #[derive(MultipartForm)] struct TestAllowUnknown {} async fn test_deny_unknown_route(_: MultipartForm<TestDenyUnknown>) -> impl Responder { HttpResponse::Ok().finish() } async fn test_allow_unknown_route(_: MultipartForm<TestAllowUnknown>) -> impl Responder { HttpResponse::Ok().finish() } #[actix_rt::test] async fn test_deny_unknown() { let srv = actix_test::start(|| { App::new() .route("/deny", web::post().to(test_deny_unknown_route)) .route("/allow", web::post().to(test_allow_unknown_route)) }); let mut form = multipart::Form::default(); form.add_text("unknown", "value"); let response = send_form(&srv, form, "/deny").await; assert_eq!(response.status(), StatusCode::BAD_REQUEST); let mut form = multipart::Form::default(); form.add_text("unknown", "value"); let response = send_form(&srv, form, "/allow").await; assert_eq!(response.status(), StatusCode::OK); } /// Test the `duplicate_field` struct attribute. #[derive(MultipartForm)] #[multipart(duplicate_field = "deny")] struct TestDuplicateDeny { _field: Text<String>, } #[derive(MultipartForm)] #[multipart(duplicate_field = "replace")] struct TestDuplicateReplace { field: Text<String>, } #[derive(MultipartForm)] #[multipart(duplicate_field = "ignore")] struct TestDuplicateIgnore { field: Text<String>, } async fn test_duplicate_deny_route(_: MultipartForm<TestDuplicateDeny>) -> impl Responder { HttpResponse::Ok().finish() } async fn test_duplicate_replace_route( form: MultipartForm<TestDuplicateReplace>, ) -> impl Responder { assert_eq!(&*form.field, "second_value"); HttpResponse::Ok().finish() } async fn test_duplicate_ignore_route( form: MultipartForm<TestDuplicateIgnore>, ) -> impl Responder { assert_eq!(&*form.field, "first_value"); HttpResponse::Ok().finish() } #[actix_rt::test] async fn test_duplicate_field() { let srv = actix_test::start(|| { App::new() .route("/deny", web::post().to(test_duplicate_deny_route)) .route("/replace", web::post().to(test_duplicate_replace_route)) .route("/ignore", web::post().to(test_duplicate_ignore_route)) }); let mut form = multipart::Form::default(); form.add_text("_field", "first_value"); form.add_text("_field", "second_value"); let response = send_form(&srv, form, "/deny").await; assert_eq!(response.status(), StatusCode::BAD_REQUEST); let mut form = multipart::Form::default(); form.add_text("field", "first_value"); form.add_text("field", "second_value"); let response = send_form(&srv, form, "/replace").await; assert_eq!(response.status(), StatusCode::OK); let mut form = multipart::Form::default(); form.add_text("field", "first_value"); form.add_text("field", "second_value"); let response = send_form(&srv, form, "/ignore").await; assert_eq!(response.status(), StatusCode::OK); } /// Test the Limits. #[derive(MultipartForm)] struct TestMemoryUploadLimits { field: Bytes, } #[derive(MultipartForm)] struct TestFileUploadLimits { field: TempFile, } async fn test_upload_limits_memory( form: MultipartForm<TestMemoryUploadLimits>, ) -> impl Responder { assert!(!form.field.data.is_empty()); HttpResponse::Ok().finish() } async fn test_upload_limits_file(form: MultipartForm<TestFileUploadLimits>) -> impl Responder { assert!(form.field.size > 0); HttpResponse::Ok().finish() } #[actix_rt::test] async fn test_memory_limits() { let srv = actix_test::start(|| { App::new() .route("/text", web::post().to(test_upload_limits_memory)) .route("/file", web::post().to(test_upload_limits_file)) .app_data( MultipartFormConfig::default() .memory_limit(20) .total_limit(usize::MAX), ) }); // Exceeds the 20 byte memory limit let mut form = multipart::Form::default(); form.add_text("field", "this string is 28 bytes long"); let response = send_form(&srv, form, "/text").await; assert_eq!(response.status(), StatusCode::BAD_REQUEST); // Memory limit should not apply when the data is being streamed to disk let mut form = multipart::Form::default(); form.add_text("field", "this string is 28 bytes long"); let response = send_form(&srv, form, "/file").await; assert_eq!(response.status(), StatusCode::OK); } #[actix_rt::test] async fn test_total_limit() { let srv = actix_test::start(|| { App::new() .route("/text", web::post().to(test_upload_limits_memory)) .route("/file", web::post().to(test_upload_limits_file)) .app_data( MultipartFormConfig::default() .memory_limit(usize::MAX) .total_limit(20), ) }); // Within the 20 byte limit let mut form = multipart::Form::default(); form.add_text("field", "7 bytes"); let response = send_form(&srv, form, "/text").await; assert_eq!(response.status(), StatusCode::OK); // Exceeds the 20 byte overall limit let mut form = multipart::Form::default(); form.add_text("field", "this string is 28 bytes long"); let response = send_form(&srv, form, "/text").await; assert_eq!(response.status(), StatusCode::BAD_REQUEST); // Exceeds the 20 byte overall limit let mut form = multipart::Form::default(); form.add_text("field", "this string is 28 bytes long"); let response = send_form(&srv, form, "/file").await; assert_eq!(response.status(), StatusCode::BAD_REQUEST); } #[derive(MultipartForm)] struct TestFieldLevelLimits { #[multipart(limit = "30B")] field: Vec<Bytes>, } async fn test_field_level_limits_route( form: MultipartForm<TestFieldLevelLimits>, ) -> impl Responder { assert!(!form.field.is_empty()); HttpResponse::Ok().finish() } #[actix_rt::test] async fn test_field_level_limits() { let srv = actix_test::start(|| { App::new() .route("/", web::post().to(test_field_level_limits_route)) .app_data( MultipartFormConfig::default() .memory_limit(usize::MAX) .total_limit(usize::MAX), ) }); // Within the 30 byte limit let mut form = multipart::Form::default(); form.add_text("field", "this string is 28 bytes long"); let response = send_form(&srv, form, "/").await; assert_eq!(response.status(), StatusCode::OK); // Exceeds the the 30 byte limit let mut form = multipart::Form::default(); form.add_text("field", "this string is more than 30 bytes long"); let response = send_form(&srv, form, "/").await; assert_eq!(response.status(), StatusCode::BAD_REQUEST); // Total of values (14 bytes) is within 30 byte limit for "field" let mut form = multipart::Form::default(); form.add_text("field", "7 bytes"); form.add_text("field", "7 bytes"); let response = send_form(&srv, form, "/").await; assert_eq!(response.status(), StatusCode::OK); // Total of values exceeds 30 byte limit for "field" let mut form = multipart::Form::default(); form.add_text("field", "this string is 28 bytes long"); form.add_text("field", "this string is 28 bytes long"); let response = send_form(&srv, form, "/").await; assert_eq!(response.status(), StatusCode::BAD_REQUEST); } #[actix_rt::test] async fn non_multipart_form_data() { #[derive(MultipartForm)] struct TestNonMultipartFormData { #[allow(unused)] #[multipart(limit = "30B")] foo: Text<String>, } async fn non_multipart_form_data_route( _form: MultipartForm<TestNonMultipartFormData>, ) -> String { unreachable!("request is sent with multipart/mixed"); } let srv = actix_test::start(|| { App::new().route("/", web::post().to(non_multipart_form_data_route)) }); let mut form = multipart::Form::default(); form.add_text("foo", "foo"); // mangle content-type, keeping the boundary let ct = form.content_type().replacen("/form-data", "/mixed", 1); let res = Client::default() .post(srv.url("/")) .content_type(ct) .send_body(multipart::Body::from(form)) .await .unwrap(); assert_eq!(res.status(), StatusCode::UNSUPPORTED_MEDIA_TYPE); } #[should_panic(expected = "called `Result::unwrap()` on an `Err` value: Connect(Disconnected)")] #[actix_web::test] async fn field_try_next_panic() { #[derive(Debug)] struct NullSink; impl<'t> FieldReader<'t> for NullSink { type Future = LocalBoxFuture<'t, Result<Self, MultipartError>>; fn read_field( _: &'t HttpRequest, mut field: Field, _limits: &'t mut Limits, ) -> Self::Future { Box::pin(async move { // exhaust field stream while let Some(_chunk) = field.try_next().await? {} // poll again, crash let _post = field.try_next().await; Ok(Self) }) } } #[allow(dead_code)] #[derive(MultipartForm)] struct NullSinkForm { foo: NullSink, } async fn null_sink(_form: MultipartForm<NullSinkForm>) -> impl Responder { "unreachable" } let srv = actix_test::start(|| App::new().service(Resource::new("/").post(null_sink))); let mut form = multipart::Form::default(); form.add_text("foo", "data is not important to this test"); // panics with Err(Connect(Disconnected)) due to form NullSink panic let _res = send_form(&srv, form, "/").await; } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-multipart/src/form/tempfile.rs
actix-multipart/src/form/tempfile.rs
//! Writes a field to a temporary file on disk. use std::{ io, path::{Path, PathBuf}, sync::Arc, }; use actix_web::{http::StatusCode, web, Error, HttpRequest, ResponseError}; use derive_more::{Display, Error}; use futures_core::future::LocalBoxFuture; use futures_util::TryStreamExt as _; use mime::Mime; use tempfile::NamedTempFile; use tokio::io::AsyncWriteExt; use super::FieldErrorHandler; use crate::{ form::{FieldReader, Limits}, Field, MultipartError, }; /// Write the field to a temporary file on disk. #[derive(Debug)] pub struct TempFile { /// The temporary file on disk. pub file: NamedTempFile, /// The value of the `content-type` header. pub content_type: Option<Mime>, /// The `filename` value in the `content-disposition` header. pub file_name: Option<String>, /// The size in bytes of the file. pub size: usize, } impl<'t> FieldReader<'t> for TempFile { type Future = LocalBoxFuture<'t, Result<Self, MultipartError>>; fn read_field(req: &'t HttpRequest, mut field: Field, limits: &'t mut Limits) -> Self::Future { Box::pin(async move { let config = TempFileConfig::from_req(req); let mut size = 0; let file = config.create_tempfile().map_err(|err| { config.map_error(req, &field.form_field_name, TempFileError::FileIo(err)) })?; let mut file_async = tokio::fs::File::from_std(file.reopen().map_err(|err| { config.map_error(req, &field.form_field_name, TempFileError::FileIo(err)) })?); while let Some(chunk) = field.try_next().await? { limits.try_consume_limits(chunk.len(), false)?; size += chunk.len(); file_async.write_all(chunk.as_ref()).await.map_err(|err| { config.map_error(req, &field.form_field_name, TempFileError::FileIo(err)) })?; } file_async.flush().await.map_err(|err| { config.map_error(req, &field.form_field_name, TempFileError::FileIo(err)) })?; Ok(TempFile { file, content_type: field.content_type().map(ToOwned::to_owned), file_name: field .content_disposition() .expect("multipart form fields should have a content-disposition header") .get_filename() .map(ToOwned::to_owned), size, }) }) } } #[derive(Debug, Display, Error)] #[non_exhaustive] pub enum TempFileError { /// File I/O Error #[display("File I/O error: {}", _0)] FileIo(std::io::Error), } impl ResponseError for TempFileError { fn status_code(&self) -> StatusCode { StatusCode::INTERNAL_SERVER_ERROR } } /// Configuration for the [`TempFile`] field reader. #[derive(Clone)] pub struct TempFileConfig { err_handler: FieldErrorHandler<TempFileError>, directory: Option<PathBuf>, } impl TempFileConfig { fn create_tempfile(&self) -> io::Result<NamedTempFile> { if let Some(ref dir) = self.directory { NamedTempFile::new_in(dir) } else { NamedTempFile::new() } } } impl TempFileConfig { /// Sets custom error handler. pub fn error_handler<F>(mut self, f: F) -> Self where F: Fn(TempFileError, &HttpRequest) -> Error + Send + Sync + 'static, { self.err_handler = Some(Arc::new(f)); self } /// Extracts payload config from app data. Check both `T` and `Data<T>`, in that order, and fall /// back to the default payload config. fn from_req(req: &HttpRequest) -> &Self { req.app_data::<Self>() .or_else(|| req.app_data::<web::Data<Self>>().map(|d| d.as_ref())) .unwrap_or(&DEFAULT_CONFIG) } fn map_error(&self, req: &HttpRequest, field_name: &str, err: TempFileError) -> MultipartError { let source = if let Some(ref err_handler) = self.err_handler { (err_handler)(err, req) } else { err.into() }; MultipartError::Field { name: field_name.to_owned(), source, } } /// Sets the directory that temp files will be created in. /// /// The default temporary file location is platform dependent. pub fn directory(mut self, dir: impl AsRef<Path>) -> Self { self.directory = Some(dir.as_ref().to_owned()); self } } const DEFAULT_CONFIG: TempFileConfig = TempFileConfig { err_handler: None, directory: None, }; impl Default for TempFileConfig { fn default() -> Self { DEFAULT_CONFIG } } #[cfg(test)] mod tests { use std::io::{Cursor, Read}; use actix_multipart_rfc7578::client::multipart; use actix_web::{http::StatusCode, web, App, HttpResponse, Responder}; use crate::form::{tempfile::TempFile, tests::send_form, MultipartForm}; #[derive(MultipartForm)] struct FileForm { file: TempFile, } async fn test_file_route(form: MultipartForm<FileForm>) -> impl Responder { let mut form = form.into_inner(); let mut contents = String::new(); form.file.file.read_to_string(&mut contents).unwrap(); assert_eq!(contents, "Hello, world!"); assert_eq!(form.file.file_name.unwrap(), "testfile.txt"); assert_eq!(form.file.content_type.unwrap(), mime::TEXT_PLAIN); HttpResponse::Ok().finish() } #[actix_rt::test] async fn test_file_upload() { let srv = actix_test::start(|| App::new().route("/", web::post().to(test_file_route))); let mut form = multipart::Form::default(); let bytes = Cursor::new("Hello, world!"); form.add_reader_file_with_mime("file", bytes, "testfile.txt", mime::TEXT_PLAIN); let response = send_form(&srv, form, "/").await; assert_eq!(response.status(), StatusCode::OK); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-multipart/examples/form.rs
actix-multipart/examples/form.rs
use actix_multipart::form::{ json::Json as MpJson, tempfile::TempFile, MultipartForm, MultipartFormConfig, }; use actix_web::{middleware::Logger, post, App, HttpServer, Responder}; use serde::Deserialize; #[derive(Debug, Deserialize)] struct Metadata { name: String, } #[derive(Debug, MultipartForm)] struct UploadForm { // Note: the form is also subject to the global limits configured using `MultipartFormConfig`. #[multipart(limit = "100MB")] file: TempFile, json: MpJson<Metadata>, } #[post("/videos")] async fn post_video(MultipartForm(form): MultipartForm<UploadForm>) -> impl Responder { format!( "Uploaded file {}, with size: {}\ntemporary file ({}) was deleted\n", form.json.name, form.file.size, form.file.file.path().display(), ) } #[actix_web::main] async fn main() -> std::io::Result<()> { env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); HttpServer::new(move || { App::new() .service(post_video) .wrap(Logger::default()) // Also increase the global total limit to 100MiB. .app_data(MultipartFormConfig::default().total_limit(100 * 1024 * 1024)) }) .workers(2) .bind(("127.0.0.1", 8080))? .run() .await }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/src/lib.rs
actix-web-codegen/src/lib.rs
//! Routing and runtime macros for Actix Web. //! //! # Actix Web Re-exports //! Actix Web re-exports a version of this crate in it's entirety so you usually don't have to //! specify a dependency on this crate explicitly. Sometimes, however, updates are made to this //! crate before the actix-web dependency is updated. Therefore, code examples here will show //! explicit imports. Check the latest [actix-web attributes docs] to see which macros //! are re-exported. //! //! # Runtime Setup //! Used for setting up the actix async runtime. See [macro@main] macro docs. //! //! ``` //! #[actix_web_codegen::main] // or `#[actix_web::main]` in Actix Web apps //! async fn main() { //! async { println!("Hello world"); }.await //! } //! ``` //! //! # Single Method Handler //! There is a macro to set up a handler for each of the most common HTTP methods that also define //! additional guards and route-specific middleware. //! //! See docs for: [GET], [POST], [PATCH], [PUT], [DELETE], [HEAD], [CONNECT], [OPTIONS], [TRACE] //! //! ``` //! # use actix_web::HttpResponse; //! # use actix_web_codegen::get; //! #[get("/test")] //! async fn get_handler() -> HttpResponse { //! HttpResponse::Ok().finish() //! } //! ``` //! //! # Multiple Method Handlers //! Similar to the single method handler macro but takes one or more arguments for the HTTP methods //! it should respond to. See [macro@route] macro docs. //! //! ``` //! # use actix_web::HttpResponse; //! # use actix_web_codegen::route; //! #[route("/test", method = "GET", method = "HEAD")] //! async fn get_and_head_handler() -> HttpResponse { //! HttpResponse::Ok().finish() //! } //! ``` //! //! # Multiple Path Handlers //! Acts as a wrapper for multiple single method handler macros. It takes no arguments and //! delegates those to the macros for the individual methods. See [macro@routes] macro docs. //! //! ``` //! # use actix_web::HttpResponse; //! # use actix_web_codegen::routes; //! #[routes] //! #[get("/test")] //! #[get("/test2")] //! #[delete("/test")] //! async fn example() -> HttpResponse { //! HttpResponse::Ok().finish() //! } //! ``` //! //! [actix-web attributes docs]: https://docs.rs/actix-web/latest/actix_web/#attributes //! [GET]: macro@get //! [POST]: macro@post //! [PUT]: macro@put //! [HEAD]: macro@head //! [CONNECT]: macro@macro@connect //! [OPTIONS]: macro@options //! [TRACE]: macro@trace //! [PATCH]: macro@patch //! [DELETE]: macro@delete #![recursion_limit = "512"] #![doc(html_logo_url = "https://actix.rs/img/logo.png")] #![doc(html_favicon_url = "https://actix.rs/favicon.ico")] #![cfg_attr(docsrs, feature(doc_cfg))] use proc_macro::TokenStream; use quote::quote; mod route; mod scope; /// Creates resource handler, allowing multiple HTTP method guards. /// /// # Syntax /// ```plain /// #[route("path", method="HTTP_METHOD"[, attributes])] /// ``` /// /// # Attributes /// - `"path"`: Raw literal string with path for which to register handler. /// - `name = "resource_name"`: Specifies resource name for the handler. If not set, the function /// name of handler is used. /// - `method = "HTTP_METHOD"`: Registers HTTP method to provide guard for. Upper-case string, /// "GET", "POST" for example. /// - `guard = "function_name"`: Registers function as guard using `actix_web::guard::fn_guard`. /// - `wrap = "Middleware"`: Registers a resource middleware. /// /// # Notes /// Function name can be specified as any expression that is going to be accessible to the generate /// code, e.g `my_guard` or `my_module::my_guard`. /// /// # Examples /// ``` /// # use actix_web::HttpResponse; /// # use actix_web_codegen::route; /// #[route("/test", method = "GET", method = "HEAD", method = "CUSTOM")] /// async fn example() -> HttpResponse { /// HttpResponse::Ok().finish() /// } /// ``` #[proc_macro_attribute] pub fn route(args: TokenStream, input: TokenStream) -> TokenStream { route::with_method(None, args, input) } /// Creates resource handler, allowing multiple HTTP methods and paths. /// /// # Syntax /// ```plain /// #[routes] /// #[<method>("path", ...)] /// #[<method>("path", ...)] /// ... /// ``` /// /// # Attributes /// The `routes` macro itself has no parameters, but allows specifying the attribute macros for /// the multiple paths and/or methods, e.g. [`GET`](macro@get) and [`POST`](macro@post). /// /// These helper attributes take the same parameters as the [single method handlers](crate#single-method-handler). /// /// # Examples /// ``` /// # use actix_web::HttpResponse; /// # use actix_web_codegen::routes; /// #[routes] /// #[get("/test")] /// #[get("/test2")] /// #[delete("/test")] /// async fn example() -> HttpResponse { /// HttpResponse::Ok().finish() /// } /// ``` #[proc_macro_attribute] pub fn routes(_: TokenStream, input: TokenStream) -> TokenStream { route::with_methods(input) } macro_rules! method_macro { ($variant:ident, $method:ident) => { #[doc = concat!("Creates route handler with `actix_web::guard::", stringify!($variant), "`.")] /// /// # Syntax /// ```plain #[doc = concat!("#[", stringify!($method), r#"("path"[, attributes])]"#)] /// ``` /// /// # Attributes /// - `"path"`: Raw literal string with path for which to register handler. /// - `name = "resource_name"`: Specifies resource name for the handler. If not set, the /// function name of handler is used. /// - `guard = "function_name"`: Registers function as guard using `actix_web::guard::fn_guard`. /// - `wrap = "Middleware"`: Registers a resource middleware. /// /// # Notes /// Function name can be specified as any expression that is going to be accessible to the /// generate code, e.g `my_guard` or `my_module::my_guard`. /// /// # Examples /// ``` /// # use actix_web::HttpResponse; #[doc = concat!("# use actix_web_codegen::", stringify!($method), ";")] #[doc = concat!("#[", stringify!($method), r#"("/")]"#)] /// async fn example() -> HttpResponse { /// HttpResponse::Ok().finish() /// } /// ``` #[proc_macro_attribute] pub fn $method(args: TokenStream, input: TokenStream) -> TokenStream { route::with_method(Some(route::MethodType::$variant), args, input) } }; } method_macro!(Get, get); method_macro!(Post, post); method_macro!(Put, put); method_macro!(Delete, delete); method_macro!(Head, head); method_macro!(Connect, connect); method_macro!(Options, options); method_macro!(Trace, trace); method_macro!(Patch, patch); /// Prepends a path prefix to all handlers using routing macros inside the attached module. /// /// # Syntax /// /// ``` /// # use actix_web_codegen::scope; /// #[scope("/prefix")] /// mod api { /// // ... /// } /// ``` /// /// # Arguments /// /// - `"/prefix"` - Raw literal string to be prefixed onto contained handlers' paths. /// /// # Example /// /// ``` /// # use actix_web_codegen::{scope, get}; /// # use actix_web::Responder; /// #[scope("/api")] /// mod api { /// # use super::*; /// #[get("/hello")] /// pub async fn hello() -> impl Responder { /// // this has path /api/hello /// "Hello, world!" /// } /// } /// # fn main() {} /// ``` #[proc_macro_attribute] pub fn scope(args: TokenStream, input: TokenStream) -> TokenStream { scope::with_scope(args, input) } /// Marks async main function as the Actix Web system entry-point. /// /// Note that Actix Web also works under `#[tokio::main]` since version 4.0. However, this macro is /// still necessary for actor support (since actors use a `System`). Read more in the /// [`actix_web::rt`](https://docs.rs/actix-web/4/actix_web/rt) module docs. /// /// # Examples /// ``` /// #[actix_web::main] /// async fn main() { /// async { println!("Hello world"); }.await /// } /// ``` #[proc_macro_attribute] pub fn main(_: TokenStream, item: TokenStream) -> TokenStream { let mut output: TokenStream = (quote! { #[::actix_web::rt::main(system = "::actix_web::rt::System")] }) .into(); output.extend(item); output } /// Marks async test functions to use the Actix Web system entry-point. /// /// # Examples /// ``` /// #[actix_web::test] /// async fn test() { /// assert_eq!(async { "Hello world" }.await, "Hello world"); /// } /// ``` #[proc_macro_attribute] pub fn test(_: TokenStream, item: TokenStream) -> TokenStream { let mut output: TokenStream = (quote! { #[::actix_web::rt::test(system = "::actix_web::rt::System")] }) .into(); output.extend(item); output } /// Converts the error to a token stream and appends it to the original input. /// /// Returning the original input in addition to the error is good for IDEs which can gracefully /// recover and show more precise errors within the macro body. /// /// See <https://github.com/rust-analyzer/rust-analyzer/issues/10468> for more info. fn input_and_compile_error(mut item: TokenStream, err: syn::Error) -> TokenStream { let compile_err = TokenStream::from(err.to_compile_error()); item.extend(compile_err); item }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/src/scope.rs
actix-web-codegen/src/scope.rs
use proc_macro::TokenStream; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::{quote, ToTokens as _}; use crate::{ input_and_compile_error, route::{MethodType, RouteArgs}, }; pub fn with_scope(args: TokenStream, input: TokenStream) -> TokenStream { match with_scope_inner(args, input.clone()) { Ok(stream) => stream, Err(err) => input_and_compile_error(input, err), } } fn with_scope_inner(args: TokenStream, input: TokenStream) -> syn::Result<TokenStream> { if args.is_empty() { return Err(syn::Error::new( Span::call_site(), "missing arguments for scope macro, expected: #[scope(\"/prefix\")]", )); } let scope_prefix = syn::parse::<syn::LitStr>(args.clone()).map_err(|err| { syn::Error::new( err.span(), "argument to scope macro is not a string literal, expected: #[scope(\"/prefix\")]", ) })?; let scope_prefix_value = scope_prefix.value(); if scope_prefix_value.ends_with('/') { // trailing slashes cause non-obvious problems // it's better to point them out to developers rather than return Err(syn::Error::new( scope_prefix.span(), "scopes should not have trailing slashes; see https://docs.rs/actix-web/4/actix_web/struct.Scope.html#avoid-trailing-slashes", )); } let mut module = syn::parse::<syn::ItemMod>(input).map_err(|err| { syn::Error::new(err.span(), "#[scope] macro must be attached to a module") })?; // modify any routing macros (method or route[s]) attached to // functions by prefixing them with this scope macro's argument if let Some((_, items)) = &mut module.content { for item in items { if let syn::Item::Fn(fun) = item { fun.attrs = fun .attrs .iter() .map(|attr| modify_attribute_with_scope(attr, &scope_prefix_value)) .collect(); } } } Ok(module.to_token_stream().into()) } /// Checks if the attribute is a method type and has a route path, then modifies it. fn modify_attribute_with_scope(attr: &syn::Attribute, scope_path: &str) -> syn::Attribute { match (attr.parse_args::<RouteArgs>(), attr.clone().meta) { (Ok(route_args), syn::Meta::List(meta_list)) if has_allowed_methods_in_scope(attr) => { let modified_path = format!("{}{}", scope_path, route_args.path.value()); let options_tokens: Vec<TokenStream2> = route_args .options .iter() .map(|option| { quote! { ,#option } }) .collect(); let combined_options_tokens: TokenStream2 = options_tokens .into_iter() .fold(TokenStream2::new(), |mut acc, ts| { acc.extend(std::iter::once(ts)); acc }); syn::Attribute { meta: syn::Meta::List(syn::MetaList { tokens: quote! { #modified_path #combined_options_tokens }, ..meta_list.clone() }), ..attr.clone() } } _ => attr.clone(), } } fn has_allowed_methods_in_scope(attr: &syn::Attribute) -> bool { MethodType::from_path(attr.path()).is_ok() || attr.path().is_ident("route") || attr.path().is_ident("ROUTE") }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/src/route.rs
actix-web-codegen/src/route.rs
use std::collections::HashSet; use actix_router::ResourceDef; use proc_macro::TokenStream; use proc_macro2::{Span, TokenStream as TokenStream2}; use quote::{quote, ToTokens, TokenStreamExt}; use syn::{punctuated::Punctuated, Ident, LitStr, Path, Token}; use crate::input_and_compile_error; #[derive(Debug)] pub struct RouteArgs { pub(crate) path: syn::LitStr, pub(crate) options: Punctuated<syn::MetaNameValue, Token![,]>, } impl syn::parse::Parse for RouteArgs { fn parse(input: syn::parse::ParseStream<'_>) -> syn::Result<Self> { // path to match: "/foo" let path = input.parse::<syn::LitStr>().map_err(|mut err| { err.combine(syn::Error::new( err.span(), r#"invalid service definition, expected #[<method>("<path>")]"#, )); err })?; // verify that path pattern is valid let _ = ResourceDef::new(path.value()); // if there's no comma, assume that no options are provided if !input.peek(Token![,]) { return Ok(Self { path, options: Punctuated::new(), }); } // advance past comma separator input.parse::<Token![,]>()?; // if next char is a literal, assume that it is a string and show multi-path error if input.cursor().literal().is_some() { return Err(syn::Error::new( Span::call_site(), r#"Multiple paths specified! There should be only one."#, )); } // zero or more options: name = "foo" let options = input.parse_terminated(syn::MetaNameValue::parse, Token![,])?; Ok(Self { path, options }) } } macro_rules! standard_method_type { ( $($variant:ident, $upper:ident, $lower:ident,)+ ) => { #[doc(hidden)] #[derive(Debug, Clone, PartialEq, Eq, Hash)] pub enum MethodType { $( $variant, )+ } impl MethodType { fn as_str(&self) -> &'static str { match self { $(Self::$variant => stringify!($variant),)+ } } fn parse(method: &str) -> Result<Self, String> { match method { $(stringify!($upper) => Ok(Self::$variant),)+ _ => Err(format!("HTTP method must be uppercase: `{}`", method)), } } pub(crate) fn from_path(method: &Path) -> Result<Self, ()> { match () { $(_ if method.is_ident(stringify!($lower)) => Ok(Self::$variant),)+ _ => Err(()), } } } }; } standard_method_type! { Get, GET, get, Post, POST, post, Put, PUT, put, Delete, DELETE, delete, Head, HEAD, head, Connect, CONNECT, connect, Options, OPTIONS, options, Trace, TRACE, trace, Patch, PATCH, patch, } impl TryFrom<&syn::LitStr> for MethodType { type Error = syn::Error; fn try_from(value: &syn::LitStr) -> Result<Self, Self::Error> { Self::parse(value.value().as_str()) .map_err(|message| syn::Error::new_spanned(value, message)) } } impl ToTokens for MethodType { fn to_tokens(&self, stream: &mut TokenStream2) { let ident = Ident::new(self.as_str(), Span::call_site()); stream.append(ident); } } #[derive(Debug, Clone, PartialEq, Eq, Hash)] enum MethodTypeExt { Standard(MethodType), Custom(LitStr), } impl MethodTypeExt { /// Returns a single method guard token stream. fn to_tokens_single_guard(&self) -> TokenStream2 { match self { MethodTypeExt::Standard(method) => { quote! { .guard(::actix_web::guard::#method()) } } MethodTypeExt::Custom(lit) => { quote! { .guard(::actix_web::guard::Method( ::actix_web::http::Method::from_bytes(#lit.as_bytes()).unwrap() )) } } } } /// Returns a multi-method guard chain token stream. fn to_tokens_multi_guard(&self, or_chain: Vec<impl ToTokens>) -> TokenStream2 { debug_assert!( !or_chain.is_empty(), "empty or_chain passed to multi-guard constructor" ); match self { MethodTypeExt::Standard(method) => { quote! { .guard( ::actix_web::guard::Any(::actix_web::guard::#method()) #(#or_chain)* ) } } MethodTypeExt::Custom(lit) => { quote! { .guard( ::actix_web::guard::Any( ::actix_web::guard::Method( ::actix_web::http::Method::from_bytes(#lit.as_bytes()).unwrap() ) ) #(#or_chain)* ) } } } } /// Returns a token stream containing the `.or` chain to be passed in to /// [`MethodTypeExt::to_tokens_multi_guard()`]. fn to_tokens_multi_guard_or_chain(&self) -> TokenStream2 { match self { MethodTypeExt::Standard(method_type) => { quote! { .or(::actix_web::guard::#method_type()) } } MethodTypeExt::Custom(lit) => { quote! { .or( ::actix_web::guard::Method( ::actix_web::http::Method::from_bytes(#lit.as_bytes()).unwrap() ) ) } } } } } impl ToTokens for MethodTypeExt { fn to_tokens(&self, stream: &mut TokenStream2) { match self { MethodTypeExt::Custom(lit_str) => { let ident = Ident::new(lit_str.value().as_str(), Span::call_site()); stream.append(ident); } MethodTypeExt::Standard(method) => method.to_tokens(stream), } } } impl TryFrom<&syn::LitStr> for MethodTypeExt { type Error = syn::Error; fn try_from(value: &syn::LitStr) -> Result<Self, Self::Error> { match MethodType::try_from(value) { Ok(method) => Ok(MethodTypeExt::Standard(method)), Err(_) if value.value().chars().all(|c| c.is_ascii_uppercase()) => { Ok(MethodTypeExt::Custom(value.clone())) } Err(err) => Err(err), } } } struct Args { path: syn::LitStr, resource_name: Option<syn::LitStr>, guards: Vec<Path>, wrappers: Vec<syn::Expr>, methods: HashSet<MethodTypeExt>, } impl Args { fn new(args: RouteArgs, method: Option<MethodType>) -> syn::Result<Self> { let mut resource_name = None; let mut guards = Vec::new(); let mut wrappers = Vec::new(); let mut methods = HashSet::new(); let is_route_macro = method.is_none(); if let Some(method) = method { methods.insert(MethodTypeExt::Standard(method)); } for nv in args.options { if nv.path.is_ident("name") { if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(lit), .. }) = nv.value { resource_name = Some(lit); } else { return Err(syn::Error::new_spanned( nv.value, "Attribute name expects literal string", )); } } else if nv.path.is_ident("guard") { if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(lit), .. }) = nv.value { guards.push(lit.parse::<Path>()?); } else { return Err(syn::Error::new_spanned( nv.value, "Attribute guard expects literal string", )); } } else if nv.path.is_ident("wrap") { if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(lit), .. }) = nv.value { wrappers.push(lit.parse()?); } else { return Err(syn::Error::new_spanned( nv.value, "Attribute wrap expects type", )); } } else if nv.path.is_ident("method") { if !is_route_macro { return Err(syn::Error::new_spanned( &nv, "HTTP method forbidden here; to handle multiple methods, use `route` instead", )); } else if let syn::Expr::Lit(syn::ExprLit { lit: syn::Lit::Str(lit), .. }) = nv.value.clone() { if !methods.insert(MethodTypeExt::try_from(&lit)?) { return Err(syn::Error::new_spanned( nv.value, format!("HTTP method defined more than once: `{}`", lit.value()), )); } } else { return Err(syn::Error::new_spanned( nv.value, "Attribute method expects literal string", )); } } else { return Err(syn::Error::new_spanned( nv.path, "Unknown attribute key is specified; allowed: guard, method and wrap", )); } } Ok(Args { path: args.path, resource_name, guards, wrappers, methods, }) } } pub struct Route { /// Name of the handler function being annotated. name: syn::Ident, /// Args passed to routing macro. /// /// When using `#[routes]`, this will contain args for each specific routing macro. args: Vec<Args>, /// AST of the handler function being annotated. ast: syn::ItemFn, /// The doc comment attributes to copy to generated struct, if any. doc_attributes: Vec<syn::Attribute>, } impl Route { pub fn new(args: RouteArgs, ast: syn::ItemFn, method: Option<MethodType>) -> syn::Result<Self> { let name = ast.sig.ident.clone(); // Try and pull out the doc comments so that we can reapply them to the generated struct. // Note that multi line doc comments are converted to multiple doc attributes. let doc_attributes = ast .attrs .iter() .filter(|attr| attr.path().is_ident("doc")) .cloned() .collect(); let args = Args::new(args, method)?; if args.methods.is_empty() { return Err(syn::Error::new( Span::call_site(), "The #[route(..)] macro requires at least one `method` attribute", )); } if matches!(ast.sig.output, syn::ReturnType::Default) { return Err(syn::Error::new_spanned( ast, "Function has no return type. Cannot be used as handler", )); } Ok(Self { name, args: vec![args], ast, doc_attributes, }) } fn multiple(args: Vec<Args>, ast: syn::ItemFn) -> syn::Result<Self> { let name = ast.sig.ident.clone(); // Try and pull out the doc comments so that we can reapply them to the generated struct. // Note that multi line doc comments are converted to multiple doc attributes. let doc_attributes = ast .attrs .iter() .filter(|attr| attr.path().is_ident("doc")) .cloned() .collect(); if matches!(ast.sig.output, syn::ReturnType::Default) { return Err(syn::Error::new_spanned( ast, "Function has no return type. Cannot be used as handler", )); } Ok(Self { name, args, ast, doc_attributes, }) } } impl ToTokens for Route { fn to_tokens(&self, output: &mut TokenStream2) { let Self { name, ast, args, doc_attributes, } = self; #[allow(unused_variables)] // used when force-pub feature is disabled let vis = &ast.vis; // TODO(breaking): remove this force-pub forwards-compatibility feature #[cfg(feature = "compat-routing-macros-force-pub")] let vis = syn::Visibility::Public(<Token![pub]>::default()); let registrations: TokenStream2 = args .iter() .map(|args| { let Args { path, resource_name, guards, wrappers, methods, } = args; let resource_name = resource_name .as_ref() .map_or_else(|| name.to_string(), LitStr::value); let method_guards = { debug_assert!(!methods.is_empty(), "Args::methods should not be empty"); let mut others = methods.iter(); let first = others.next().unwrap(); if methods.len() > 1 { let other_method_guards = others .map(|method_ext| method_ext.to_tokens_multi_guard_or_chain()) .collect(); first.to_tokens_multi_guard(other_method_guards) } else { first.to_tokens_single_guard() } }; quote! { let __resource = ::actix_web::Resource::new(#path) .name(#resource_name) #method_guards #(.guard(::actix_web::guard::fn_guard(#guards)))* #(.wrap(#wrappers))* .to(#name); ::actix_web::dev::HttpServiceFactory::register(__resource, __config); } }) .collect(); let stream = quote! { #(#doc_attributes)* #[allow(non_camel_case_types)] #vis struct #name; impl ::actix_web::dev::HttpServiceFactory for #name { fn register(self, __config: &mut actix_web::dev::AppService) { #ast #registrations } } }; output.extend(stream); } } pub(crate) fn with_method( method: Option<MethodType>, args: TokenStream, input: TokenStream, ) -> TokenStream { let args = match syn::parse(args) { Ok(args) => args, // on parse error, make IDEs happy; see fn docs Err(err) => return input_and_compile_error(input, err), }; let ast = match syn::parse::<syn::ItemFn>(input.clone()) { Ok(ast) => ast, // on parse error, make IDEs happy; see fn docs Err(err) => return input_and_compile_error(input, err), }; match Route::new(args, ast, method) { Ok(route) => route.into_token_stream().into(), // on macro related error, make IDEs happy; see fn docs Err(err) => input_and_compile_error(input, err), } } pub(crate) fn with_methods(input: TokenStream) -> TokenStream { let mut ast = match syn::parse::<syn::ItemFn>(input.clone()) { Ok(ast) => ast, // on parse error, make IDEs happy; see fn docs Err(err) => return input_and_compile_error(input, err), }; let (methods, others) = ast .attrs .into_iter() .map(|attr| match MethodType::from_path(attr.path()) { Ok(method) => Ok((method, attr)), Err(_) => Err(attr), }) .partition::<Vec<_>, _>(Result::is_ok); ast.attrs = others.into_iter().map(Result::unwrap_err).collect(); let methods = match methods .into_iter() .map(Result::unwrap) .map(|(method, attr)| { attr.parse_args() .and_then(|args| Args::new(args, Some(method))) }) .collect::<Result<Vec<_>, _>>() { Ok(methods) if methods.is_empty() => { return input_and_compile_error( input, syn::Error::new( Span::call_site(), "The #[routes] macro requires at least one `#[<method>(..)]` attribute.", ), ) } Ok(methods) => methods, Err(err) => return input_and_compile_error(input, err), }; match Route::multiple(methods, ast) { Ok(route) => route.into_token_stream().into(), // on macro related error, make IDEs happy; see fn docs Err(err) => input_and_compile_error(input, err), } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/tests/trybuild.rs
actix-web-codegen/tests/trybuild.rs
#[rustversion_msrv::msrv] #[test] fn compile_macros() { let t = trybuild::TestCases::new(); t.pass("tests/trybuild/simple.rs"); t.compile_fail("tests/trybuild/simple-fail.rs"); t.pass("tests/trybuild/route-ok.rs"); t.compile_fail("tests/trybuild/route-missing-method-fail.rs"); t.compile_fail("tests/trybuild/route-duplicate-method-fail.rs"); t.compile_fail("tests/trybuild/route-malformed-path-fail.rs"); t.pass("tests/trybuild/route-custom-method.rs"); t.compile_fail("tests/trybuild/route-custom-lowercase.rs"); t.pass("tests/trybuild/routes-ok.rs"); t.compile_fail("tests/trybuild/routes-missing-method-fail.rs"); t.compile_fail("tests/trybuild/routes-missing-args-fail.rs"); t.compile_fail("tests/trybuild/scope-on-handler.rs"); t.compile_fail("tests/trybuild/scope-missing-args.rs"); t.compile_fail("tests/trybuild/scope-invalid-args.rs"); t.compile_fail("tests/trybuild/scope-trailing-slash.rs"); t.pass("tests/trybuild/docstring-ok.rs"); t.pass("tests/trybuild/test-runtime.rs"); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/tests/routes.rs
actix-web-codegen/tests/routes.rs
use std::future::Future; use actix_utils::future::{ok, Ready}; use actix_web::{ dev::{Service, ServiceRequest, ServiceResponse, Transform}, http::{ self, header::{HeaderName, HeaderValue}, StatusCode, }, web, App, Error, HttpRequest, HttpResponse, Responder, }; use actix_web_codegen::{ connect, delete, get, head, options, patch, post, put, route, routes, trace, }; use futures_core::future::LocalBoxFuture; // Make sure that we can name function as 'config' #[get("/config")] async fn config() -> impl Responder { HttpResponse::Ok() } #[get("/test")] async fn test_handler() -> impl Responder { HttpResponse::Ok() } #[put("/test")] async fn put_test() -> impl Responder { HttpResponse::Created() } #[patch("/test")] async fn patch_test() -> impl Responder { HttpResponse::Ok() } #[post("/test")] async fn post_test() -> impl Responder { HttpResponse::NoContent() } #[head("/test")] async fn head_test() -> impl Responder { HttpResponse::Ok() } #[connect("/test")] async fn connect_test() -> impl Responder { HttpResponse::Ok() } #[options("/test")] async fn options_test() -> impl Responder { HttpResponse::Ok() } #[trace("/test")] async fn trace_test() -> impl Responder { HttpResponse::Ok() } #[get("/test")] fn auto_async() -> impl Future<Output = Result<HttpResponse, actix_web::Error>> { ok(HttpResponse::Ok().finish()) } #[get("/test")] fn auto_sync() -> impl Future<Output = Result<HttpResponse, actix_web::Error>> { ok(HttpResponse::Ok().finish()) } #[put("/test/{param}")] async fn put_param_test(_: web::Path<String>) -> impl Responder { HttpResponse::Created() } #[delete("/test/{param}")] async fn delete_param_test(_: web::Path<String>) -> impl Responder { HttpResponse::NoContent() } #[get("/test/{param}")] async fn get_param_test(_: web::Path<String>) -> impl Responder { HttpResponse::Ok() } #[route("/hello", method = "HELLO")] async fn custom_route_test() -> impl Responder { HttpResponse::Ok() } #[route( "/multi", method = "GET", method = "POST", method = "HEAD", method = "HELLO" )] async fn route_test() -> impl Responder { HttpResponse::Ok() } #[routes] #[get("/routes/test")] #[get("/routes/test2")] #[post("/routes/test")] async fn routes_test() -> impl Responder { HttpResponse::Ok() } // routes overlap with the more specific route first, therefore accessible #[routes] #[get("/routes/overlap/test")] #[get("/routes/overlap/{foo}")] async fn routes_overlapping_test(req: HttpRequest) -> impl Responder { // foo is only populated when route is not /routes/overlap/test match req.match_info().get("foo") { None => assert!(req.uri() == "/routes/overlap/test"), Some(_) => assert!(req.uri() != "/routes/overlap/test"), } HttpResponse::Ok() } // routes overlap with the more specific route last, therefore inaccessible #[routes] #[get("/routes/overlap2/{foo}")] #[get("/routes/overlap2/test")] async fn routes_overlapping_inaccessible_test(req: HttpRequest) -> impl Responder { // foo is always populated even when path is /routes/overlap2/test assert!(req.match_info().get("foo").is_some()); HttpResponse::Ok() } #[get("/custom_resource_name", name = "custom")] async fn custom_resource_name_test(req: HttpRequest) -> impl Responder { assert!(req.url_for_static("custom").is_ok()); assert!(req.url_for_static("custom_resource_name_test").is_err()); HttpResponse::Ok() } mod guard_module { use actix_web::{guard::GuardContext, http::header}; pub fn guard(ctx: &GuardContext<'_>) -> bool { ctx.header::<header::Accept>() .map(|h| h.preference() == "image/*") .unwrap_or(false) } } #[get("/test/guard", guard = "guard_module::guard")] async fn guard_test() -> impl Responder { HttpResponse::Ok() } pub struct ChangeStatusCode; impl<S, B> Transform<S, ServiceRequest> for ChangeStatusCode where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, S::Future: 'static, B: 'static, { type Response = ServiceResponse<B>; type Error = Error; type Transform = ChangeStatusCodeMiddleware<S>; type InitError = (); type Future = Ready<Result<Self::Transform, Self::InitError>>; fn new_transform(&self, service: S) -> Self::Future { ok(ChangeStatusCodeMiddleware { service }) } } pub struct ChangeStatusCodeMiddleware<S> { service: S, } impl<S, B> Service<ServiceRequest> for ChangeStatusCodeMiddleware<S> where S: Service<ServiceRequest, Response = ServiceResponse<B>, Error = Error>, S::Future: 'static, B: 'static, { type Response = ServiceResponse<B>; type Error = Error; type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; actix_web::dev::forward_ready!(service); fn call(&self, req: ServiceRequest) -> Self::Future { let fut = self.service.call(req); Box::pin(async move { let mut res = fut.await?; let headers = res.headers_mut(); let header_name = HeaderName::from_lowercase(b"custom-header").unwrap(); let header_value = HeaderValue::from_str("hello").unwrap(); headers.insert(header_name, header_value); Ok(res) }) } } #[get("/test/wrap", wrap = "ChangeStatusCode")] async fn get_wrap(_: web::Path<String>) -> impl Responder { // panic!("actually never gets called because path failed to extract"); HttpResponse::Ok() } /// Using expression, not just path to type, in wrap attribute. /// /// Regression from <https://github.com/actix/actix-web/issues/3118>. #[route( "/catalog", method = "GET", method = "HEAD", wrap = "actix_web::middleware::Compress::default()" )] async fn get_catalog() -> impl Responder { HttpResponse::Ok().body("123123123") } #[actix_rt::test] async fn test_params() { let srv = actix_test::start(|| { App::new() .service(get_param_test) .service(put_param_test) .service(delete_param_test) }); let request = srv.request(http::Method::GET, srv.url("/test/it")); let response = request.send().await.unwrap(); assert_eq!(response.status(), http::StatusCode::OK); let request = srv.request(http::Method::PUT, srv.url("/test/it")); let response = request.send().await.unwrap(); assert_eq!(response.status(), http::StatusCode::CREATED); let request = srv.request(http::Method::DELETE, srv.url("/test/it")); let response = request.send().await.unwrap(); assert_eq!(response.status(), http::StatusCode::NO_CONTENT); } #[actix_rt::test] async fn test_body() { let srv = actix_test::start(|| { App::new() .service(post_test) .service(put_test) .service(head_test) .service(connect_test) .service(options_test) .service(trace_test) .service(patch_test) .service(test_handler) .service(route_test) .service(routes_overlapping_test) .service(routes_overlapping_inaccessible_test) .service(routes_test) .service(custom_resource_name_test) .service(guard_test) }); let request = srv.request(http::Method::GET, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::HEAD, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::CONNECT, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::OPTIONS, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::TRACE, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::PATCH, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::PUT, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); assert_eq!(response.status(), http::StatusCode::CREATED); let request = srv.request(http::Method::POST, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); assert_eq!(response.status(), http::StatusCode::NO_CONTENT); let request = srv.request(http::Method::GET, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/multi")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::POST, srv.url("/multi")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::HEAD, srv.url("/multi")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::PATCH, srv.url("/multi")); let response = request.send().await.unwrap(); assert!(!response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/routes/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/routes/test2")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::POST, srv.url("/routes/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/routes/not-set")); let response = request.send().await.unwrap(); assert!(response.status().is_client_error()); let request = srv.request(http::Method::GET, srv.url("/routes/overlap/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/routes/overlap/bar")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/routes/overlap2/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/routes/overlap2/bar")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::GET, srv.url("/custom_resource_name")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv .request(http::Method::GET, srv.url("/test/guard")) .insert_header(("Accept", "image/*")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } #[actix_rt::test] async fn test_auto_async() { let srv = actix_test::start(|| App::new().service(auto_async)); let request = srv.request(http::Method::GET, srv.url("/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } #[actix_web::test] async fn test_wrap() { let srv = actix_test::start(|| App::new().service(get_wrap)); let request = srv.request(http::Method::GET, srv.url("/test/wrap")); let mut response = request.send().await.unwrap(); assert_eq!(response.status(), StatusCode::NOT_FOUND); assert!(response.headers().contains_key("custom-header")); let body = response.body().await.unwrap(); let body = String::from_utf8(body.to_vec()).unwrap(); assert!(body.contains("wrong number of parameters")); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/tests/scopes.rs
actix-web-codegen/tests/scopes.rs
use actix_web::{guard::GuardContext, http, http::header, web, App, HttpResponse, Responder}; use actix_web_codegen::{delete, get, post, route, routes, scope}; pub fn image_guard(ctx: &GuardContext<'_>) -> bool { ctx.header::<header::Accept>() .map(|h| h.preference() == "image/*") .unwrap_or(false) } #[scope("/test")] mod scope_module { // ensure that imports can be brought into the scope use super::*; #[get("/test/guard", guard = "image_guard")] pub async fn guard() -> impl Responder { HttpResponse::Ok() } #[get("/test")] pub async fn test() -> impl Responder { HttpResponse::Ok().finish() } #[get("/twice-test/{value}")] pub async fn twice(value: web::Path<String>) -> impl actix_web::Responder { let int_value: i32 = value.parse().unwrap_or(0); let doubled = int_value * 2; HttpResponse::Ok().body(format!("Twice value: {}", doubled)) } #[post("/test")] pub async fn post() -> impl Responder { HttpResponse::Ok().body("post works") } #[delete("/test")] pub async fn delete() -> impl Responder { "delete works" } #[route("/test", method = "PUT", method = "PATCH", method = "CUSTOM")] pub async fn multiple_shared_path() -> impl Responder { HttpResponse::Ok().finish() } #[routes] #[head("/test1")] #[connect("/test2")] #[options("/test3")] #[trace("/test4")] pub async fn multiple_separate_paths() -> impl Responder { HttpResponse::Ok().finish() } // test calling this from other mod scope with scope attribute... pub fn mod_common(message: String) -> impl actix_web::Responder { HttpResponse::Ok().body(message) } } /// Scope doc string to check in cargo expand. #[scope("/v1")] mod mod_scope_v1 { use super::*; /// Route doc string to check in cargo expand. #[get("/test")] pub async fn test() -> impl Responder { scope_module::mod_common("version1 works".to_string()) } } #[scope("/v2")] mod mod_scope_v2 { use super::*; // check to make sure non-function tokens in the scope block are preserved... enum TestEnum { Works, } #[get("/test")] pub async fn test() -> impl Responder { // make sure this type still exists... let test_enum = TestEnum::Works; match test_enum { TestEnum::Works => scope_module::mod_common("version2 works".to_string()), } } } #[actix_rt::test] async fn scope_get_async() { let srv = actix_test::start(|| App::new().service(scope_module::test)); let request = srv.request(http::Method::GET, srv.url("/test/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } #[actix_rt::test] async fn scope_get_param_async() { let srv = actix_test::start(|| App::new().service(scope_module::twice)); let request = srv.request(http::Method::GET, srv.url("/test/twice-test/4")); let mut response = request.send().await.unwrap(); let body = response.body().await.unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap(); assert_eq!(body_str, "Twice value: 8"); } #[actix_rt::test] async fn scope_post_async() { let srv = actix_test::start(|| App::new().service(scope_module::post)); let request = srv.request(http::Method::POST, srv.url("/test/test")); let mut response = request.send().await.unwrap(); let body = response.body().await.unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap(); assert_eq!(body_str, "post works"); } #[actix_rt::test] async fn multiple_shared_path_async() { let srv = actix_test::start(|| App::new().service(scope_module::multiple_shared_path)); let request = srv.request(http::Method::PUT, srv.url("/test/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::PATCH, srv.url("/test/test")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } #[actix_rt::test] async fn multiple_multi_path_async() { let srv = actix_test::start(|| App::new().service(scope_module::multiple_separate_paths)); let request = srv.request(http::Method::HEAD, srv.url("/test/test1")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::CONNECT, srv.url("/test/test2")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::OPTIONS, srv.url("/test/test3")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(http::Method::TRACE, srv.url("/test/test4")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } #[actix_rt::test] async fn scope_delete_async() { let srv = actix_test::start(|| App::new().service(scope_module::delete)); let request = srv.request(http::Method::DELETE, srv.url("/test/test")); let mut response = request.send().await.unwrap(); let body = response.body().await.unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap(); assert_eq!(body_str, "delete works"); } #[actix_rt::test] async fn scope_get_with_guard_async() { let srv = actix_test::start(|| App::new().service(scope_module::guard)); let request = srv .request(http::Method::GET, srv.url("/test/test/guard")) .insert_header(("Accept", "image/*")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); } #[actix_rt::test] async fn scope_v1_v2_async() { let srv = actix_test::start(|| { App::new() .service(mod_scope_v1::test) .service(mod_scope_v2::test) }); let request = srv.request(http::Method::GET, srv.url("/v1/test")); let mut response = request.send().await.unwrap(); let body = response.body().await.unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap(); assert_eq!(body_str, "version1 works"); let request = srv.request(http::Method::GET, srv.url("/v2/test")); let mut response = request.send().await.unwrap(); let body = response.body().await.unwrap(); let body_str = String::from_utf8(body.to_vec()).unwrap(); assert_eq!(body_str, "version2 works"); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/tests/trybuild/route-custom-method.rs
actix-web-codegen/tests/trybuild/route-custom-method.rs
use std::str::FromStr; use actix_web::http::Method; use actix_web_codegen::route; #[route("/single", method = "CUSTOM")] async fn index() -> String { "Hello Single!".to_owned() } #[route("/multi", method = "GET", method = "CUSTOM")] async fn custom() -> String { "Hello Multi!".to_owned() } #[actix_web::main] async fn main() { use actix_web::App; let srv = actix_test::start(|| App::new().service(index).service(custom)); let request = srv.request(Method::GET, srv.url("/")); let response = request.send().await.unwrap(); assert!(response.status().is_client_error()); let request = srv.request(Method::from_str("CUSTOM").unwrap(), srv.url("/single")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(Method::GET, srv.url("/multi")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.request(Method::from_str("CUSTOM").unwrap(), srv.url("/multi")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/tests/trybuild/scope-on-handler.rs
actix-web-codegen/tests/trybuild/scope-on-handler.rs
use actix_web_codegen::scope; #[scope("/api")] async fn index() -> &'static str { "Hello World!" } fn main() {}
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/tests/trybuild/simple-fail.rs
actix-web-codegen/tests/trybuild/simple-fail.rs
use actix_web_codegen::*; #[get("/one", other)] async fn one() -> String { "Hello World!".to_owned() } #[post(/two)] async fn two() -> String { "Hello World!".to_owned() } static PATCH_PATH: &str = "/three"; #[patch(PATCH_PATH)] async fn three() -> String { "Hello World!".to_owned() } #[delete("/four", "/five")] async fn four() -> String { "Hello World!".to_owned() } #[delete("/five", method="GET")] async fn five() -> String { "Hello World!".to_owned() } fn main() {}
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/tests/trybuild/routes-ok.rs
actix-web-codegen/tests/trybuild/routes-ok.rs
use actix_web_codegen::*; #[routes] #[get("/")] #[post("/")] async fn index() -> String { "Hello World!".to_owned() } #[actix_web::main] async fn main() { use actix_web::App; let srv = actix_test::start(|| App::new().service(index)); let request = srv.get("/"); let response = request.send().await.unwrap(); assert!(response.status().is_success()); let request = srv.post("/"); let response = request.send().await.unwrap(); assert!(response.status().is_success()); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/tests/trybuild/routes-missing-method-fail.rs
actix-web-codegen/tests/trybuild/routes-missing-method-fail.rs
use actix_web_codegen::*; #[routes] async fn index() -> String { "Hello World!".to_owned() } #[actix_web::main] async fn main() { use actix_web::App; let srv = actix_test::start(|| App::new().service(index)); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/tests/trybuild/route-ok.rs
actix-web-codegen/tests/trybuild/route-ok.rs
use actix_web_codegen::*; #[route("/", method="GET", method="HEAD")] async fn index() -> String { "Hello World!".to_owned() } #[actix_web::main] async fn main() { use actix_web::App; let srv = actix_test::start(|| App::new().service(index)); let request = srv.get("/"); let response = request.send().await.unwrap(); assert!(response.status().is_success()); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/tests/trybuild/route-malformed-path-fail.rs
actix-web-codegen/tests/trybuild/route-malformed-path-fail.rs
use actix_web_codegen::get; #[get("/{")] async fn zero() -> &'static str { "malformed resource def" } #[get("/{foo")] async fn one() -> &'static str { "malformed resource def" } #[get("/{}")] async fn two() -> &'static str { "malformed resource def" } #[get("/*")] async fn three() -> &'static str { "malformed resource def" } #[get("/{tail:\\d+}*")] async fn four() -> &'static str { "malformed resource def" } #[get("/{a}/{b}/{c}/{d}/{e}/{f}/{g}/{h}/{i}/{j}/{k}/{l}/{m}/{n}/{o}/{p}/{q}")] async fn five() -> &'static str { "malformed resource def" } fn main() {}
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/tests/trybuild/scope-missing-args.rs
actix-web-codegen/tests/trybuild/scope-missing-args.rs
use actix_web_codegen::scope; #[scope] mod api {} fn main() {}
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/tests/trybuild/test-runtime.rs
actix-web-codegen/tests/trybuild/test-runtime.rs
#[actix_web::test] async fn my_test() { assert!(async { 1 }.await, 1); } fn main() {}
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/tests/trybuild/docstring-ok.rs
actix-web-codegen/tests/trybuild/docstring-ok.rs
use actix_web::{Responder, HttpResponse, App}; use actix_web_codegen::*; /// doc comments shouldn't break anything #[get("/")] async fn index() -> impl Responder { HttpResponse::Ok() } #[actix_web::main] async fn main() { let srv = actix_test::start(|| App::new().service(index)); let request = srv.get("/"); let response = request.send().await.unwrap(); assert!(response.status().is_success()); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/tests/trybuild/routes-missing-args-fail.rs
actix-web-codegen/tests/trybuild/routes-missing-args-fail.rs
use actix_web_codegen::*; #[routes] #[get] async fn index() -> String { "Hello World!".to_owned() } #[actix_web::main] async fn main() { use actix_web::App; let srv = actix_test::start(|| App::new().service(index)); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/tests/trybuild/scope-trailing-slash.rs
actix-web-codegen/tests/trybuild/scope-trailing-slash.rs
use actix_web_codegen::scope; #[scope("/api/")] mod api {} fn main() {}
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/tests/trybuild/simple.rs
actix-web-codegen/tests/trybuild/simple.rs
use actix_web::{Responder, HttpResponse, App}; use actix_web_codegen::*; #[get("/config")] async fn config() -> impl Responder { HttpResponse::Ok() } #[actix_web::main] async fn main() { let srv = actix_test::start(|| App::new().service(config)); let request = srv.get("/config"); let response = request.send().await.unwrap(); assert!(response.status().is_success()); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/tests/trybuild/scope-invalid-args.rs
actix-web-codegen/tests/trybuild/scope-invalid-args.rs
use actix_web_codegen::scope; const PATH: &str = "/api"; #[scope(PATH)] mod api_const {} #[scope(true)] mod api_bool {} #[scope(123)] mod api_num {} fn main() {}
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/tests/trybuild/route-custom-lowercase.rs
actix-web-codegen/tests/trybuild/route-custom-lowercase.rs
use actix_web_codegen::*; use actix_web::http::Method; use std::str::FromStr; #[route("/", method = "hello")] async fn index() -> String { "Hello World!".to_owned() } #[actix_web::main] async fn main() { use actix_web::App; let srv = actix_test::start(|| App::new().service(index)); let request = srv.request(Method::from_str("hello").unwrap(), srv.url("/")); let response = request.send().await.unwrap(); assert!(response.status().is_success()); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/tests/trybuild/route-missing-method-fail.rs
actix-web-codegen/tests/trybuild/route-missing-method-fail.rs
use actix_web_codegen::*; #[route("/")] async fn index() -> String { "Hello World!".to_owned() } #[actix_web::main] async fn main() { use actix_web::App; let srv = actix_test::start(|| App::new().service(index)); let request = srv.get("/"); let response = request.send().await.unwrap(); assert!(response.status().is_success()); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-codegen/tests/trybuild/route-duplicate-method-fail.rs
actix-web-codegen/tests/trybuild/route-duplicate-method-fail.rs
use actix_web_codegen::*; #[route("/", method="GET", method="GET")] async fn index() -> String { "Hello World!".to_owned() } #[actix_web::main] async fn main() { use actix_web::App; let srv = actix_test::start(|| App::new().service(index)); let request = srv.get("/"); let response = request.send().await.unwrap(); assert!(response.status().is_success()); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-files/src/chunked.rs
actix-files/src/chunked.rs
use std::{ cmp, fmt, future::Future, io, pin::Pin, task::{Context, Poll}, }; use actix_web::{error::Error, web::Bytes}; #[cfg(feature = "experimental-io-uring")] use bytes::BytesMut; use futures_core::{ready, Stream}; use pin_project_lite::pin_project; use super::named::File; #[derive(Debug, Clone, Copy)] pub(crate) enum ReadMode { Sync, Async, } pin_project! { /// Adapter to read a `std::file::File` in chunks. #[doc(hidden)] pub struct ChunkedReadFile<F, Fut> { size: u64, offset: u64, #[pin] state: ChunkedReadFileState<Fut>, counter: u64, callback: F, read_mode: ReadMode, } } #[cfg(not(feature = "experimental-io-uring"))] pin_project! { #[project = ChunkedReadFileStateProj] #[project_replace = ChunkedReadFileStateProjReplace] enum ChunkedReadFileState<Fut> { File { file: Option<File>, }, Future { #[pin] fut: Fut }, } } #[cfg(feature = "experimental-io-uring")] pin_project! { #[project = ChunkedReadFileStateProj] #[project_replace = ChunkedReadFileStateProjReplace] enum ChunkedReadFileState<Fut> { File { file: Option<(File, BytesMut)> }, Future { #[pin] fut: Fut }, } } impl<F, Fut> fmt::Debug for ChunkedReadFile<F, Fut> { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("ChunkedReadFile") } } pub(crate) fn new_chunked_read( size: u64, offset: u64, file: File, read_mode_threshold: u64, ) -> impl Stream<Item = Result<Bytes, Error>> { ChunkedReadFile { size, offset, #[cfg(not(feature = "experimental-io-uring"))] state: ChunkedReadFileState::File { file: Some(file) }, #[cfg(feature = "experimental-io-uring")] state: ChunkedReadFileState::File { file: Some((file, BytesMut::new())), }, counter: 0, callback: chunked_read_file_callback, read_mode: if size < read_mode_threshold { ReadMode::Sync } else { ReadMode::Async }, } } #[cfg(not(feature = "experimental-io-uring"))] fn chunked_read_file_callback_sync( mut file: File, offset: u64, max_bytes: usize, ) -> Result<(File, Bytes), io::Error> { use io::{Read as _, Seek as _}; let mut buf = Vec::with_capacity(max_bytes); file.seek(io::SeekFrom::Start(offset))?; let n_bytes = file.by_ref().take(max_bytes as u64).read_to_end(&mut buf)?; if n_bytes == 0 { Err(io::Error::from(io::ErrorKind::UnexpectedEof)) } else { Ok((file, Bytes::from(buf))) } } #[cfg(not(feature = "experimental-io-uring"))] #[inline] async fn chunked_read_file_callback( file: File, offset: u64, max_bytes: usize, read_mode: ReadMode, ) -> Result<(File, Bytes), Error> { let res = match read_mode { ReadMode::Sync => chunked_read_file_callback_sync(file, offset, max_bytes)?, ReadMode::Async => { actix_web::web::block(move || chunked_read_file_callback_sync(file, offset, max_bytes)) .await?? } }; Ok(res) } #[cfg(feature = "experimental-io-uring")] async fn chunked_read_file_callback( file: File, offset: u64, max_bytes: usize, mut bytes_mut: BytesMut, ) -> io::Result<(File, Bytes, BytesMut)> { bytes_mut.reserve(max_bytes); let (res, mut bytes_mut) = file.read_at(bytes_mut, offset).await; let n_bytes = res?; if n_bytes == 0 { return Err(io::ErrorKind::UnexpectedEof.into()); } let bytes = bytes_mut.split_to(n_bytes).freeze(); Ok((file, bytes, bytes_mut)) } #[cfg(feature = "experimental-io-uring")] impl<F, Fut> Stream for ChunkedReadFile<F, Fut> where F: Fn(File, u64, usize, BytesMut) -> Fut, Fut: Future<Output = io::Result<(File, Bytes, BytesMut)>>, { type Item = Result<Bytes, Error>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let mut this = self.as_mut().project(); match this.state.as_mut().project() { ChunkedReadFileStateProj::File { file } => { let size = *this.size; let offset = *this.offset; let counter = *this.counter; if size == counter { Poll::Ready(None) } else { let max_bytes = cmp::min(size.saturating_sub(counter), 65_536) as usize; let (file, bytes_mut) = file .take() .expect("ChunkedReadFile polled after completion"); let fut = (this.callback)(file, offset, max_bytes, bytes_mut); this.state .project_replace(ChunkedReadFileState::Future { fut }); self.poll_next(cx) } } ChunkedReadFileStateProj::Future { fut } => { let (file, bytes, bytes_mut) = ready!(fut.poll(cx))?; this.state.project_replace(ChunkedReadFileState::File { file: Some((file, bytes_mut)), }); *this.offset += bytes.len() as u64; *this.counter += bytes.len() as u64; Poll::Ready(Some(Ok(bytes))) } } } } #[cfg(not(feature = "experimental-io-uring"))] impl<F, Fut> Stream for ChunkedReadFile<F, Fut> where F: Fn(File, u64, usize, ReadMode) -> Fut, Fut: Future<Output = Result<(File, Bytes), Error>>, { type Item = Result<Bytes, Error>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let mut this = self.as_mut().project(); match this.state.as_mut().project() { ChunkedReadFileStateProj::File { file } => { let size = *this.size; let offset = *this.offset; let counter = *this.counter; if size == counter { Poll::Ready(None) } else { let max_bytes = cmp::min(size.saturating_sub(counter), 65_536) as usize; let file = file .take() .expect("ChunkedReadFile polled after completion"); let fut = (this.callback)(file, offset, max_bytes, *this.read_mode); this.state .project_replace(ChunkedReadFileState::Future { fut }); self.poll_next(cx) } } ChunkedReadFileStateProj::Future { fut } => { let (file, bytes) = ready!(fut.poll(cx))?; this.state .project_replace(ChunkedReadFileState::File { file: Some(file) }); *this.offset += bytes.len() as u64; *this.counter += bytes.len() as u64; Poll::Ready(Some(Ok(bytes))) } } } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-files/src/lib.rs
actix-files/src/lib.rs
//! Static file serving for Actix Web. //! //! Provides a non-blocking service for serving static files from disk. //! //! # Examples //! ``` //! use actix_web::App; //! use actix_files::Files; //! //! let app = App::new() //! .service(Files::new("/static", ".").prefer_utf8(true)); //! ``` #![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_cfg))] use std::path::Path; use actix_service::boxed::{BoxService, BoxServiceFactory}; use actix_web::{ dev::{RequestHead, ServiceRequest, ServiceResponse}, error::Error, http::header::DispositionType, }; use mime_guess::from_ext; mod chunked; mod directory; mod encoding; mod error; mod files; mod named; mod path_buf; mod range; mod service; pub use self::{ chunked::ChunkedReadFile, directory::Directory, files::Files, named::NamedFile, range::HttpRange, service::FilesService, }; use self::{ directory::{directory_listing, DirectoryRenderer}, error::FilesError, path_buf::PathBufWrap, }; type HttpService = BoxService<ServiceRequest, ServiceResponse, Error>; type HttpNewService = BoxServiceFactory<(), ServiceRequest, ServiceResponse, Error, ()>; /// Return the MIME type associated with a filename extension (case-insensitive). /// If `ext` is empty or no associated type for the extension was found, returns /// the type `application/octet-stream`. #[inline] pub fn file_extension_to_mime(ext: &str) -> mime::Mime { from_ext(ext).first_or_octet_stream() } type MimeOverride = dyn Fn(&mime::Name<'_>) -> DispositionType; type PathFilter = dyn Fn(&Path, &RequestHead) -> bool; #[cfg(test)] mod tests { use std::{ fmt::Write as _, fs::{self}, ops::Add, time::{Duration, SystemTime}, }; use actix_web::{ dev::ServiceFactory, guard, http::{ header::{self, ContentDisposition, DispositionParam}, Method, StatusCode, }, middleware::Compress, test::{self, TestRequest}, web::{self, Bytes}, App, HttpResponse, Responder, }; use super::*; use crate::named::File; #[actix_web::test] async fn test_file_extension_to_mime() { let m = file_extension_to_mime(""); assert_eq!(m, mime::APPLICATION_OCTET_STREAM); let m = file_extension_to_mime("jpg"); assert_eq!(m, mime::IMAGE_JPEG); let m = file_extension_to_mime("invalid extension!!"); assert_eq!(m, mime::APPLICATION_OCTET_STREAM); let m = file_extension_to_mime(""); assert_eq!(m, mime::APPLICATION_OCTET_STREAM); } #[actix_rt::test] async fn test_if_modified_since_without_if_none_match() { let file = NamedFile::open_async("Cargo.toml").await.unwrap(); let since = header::HttpDate::from(SystemTime::now().add(Duration::from_secs(60))); let req = TestRequest::default() .insert_header((header::IF_MODIFIED_SINCE, since)) .to_http_request(); let resp = file.respond_to(&req); assert_eq!(resp.status(), StatusCode::NOT_MODIFIED); } #[actix_rt::test] async fn test_if_modified_since_without_if_none_match_same() { let file = NamedFile::open_async("Cargo.toml").await.unwrap(); let since = file.last_modified().unwrap(); let req = TestRequest::default() .insert_header((header::IF_MODIFIED_SINCE, since)) .to_http_request(); let resp = file.respond_to(&req); assert_eq!(resp.status(), StatusCode::NOT_MODIFIED); } #[actix_rt::test] async fn test_if_modified_since_with_if_none_match() { let file = NamedFile::open_async("Cargo.toml").await.unwrap(); let since = header::HttpDate::from(SystemTime::now().add(Duration::from_secs(60))); let req = TestRequest::default() .insert_header((header::IF_NONE_MATCH, "miss_etag")) .insert_header((header::IF_MODIFIED_SINCE, since)) .to_http_request(); let resp = file.respond_to(&req); assert_ne!(resp.status(), StatusCode::NOT_MODIFIED); } #[actix_rt::test] async fn test_if_unmodified_since() { let file = NamedFile::open_async("Cargo.toml").await.unwrap(); let since = file.last_modified().unwrap(); let req = TestRequest::default() .insert_header((header::IF_UNMODIFIED_SINCE, since)) .to_http_request(); let resp = file.respond_to(&req); assert_eq!(resp.status(), StatusCode::OK); } #[actix_rt::test] async fn test_if_unmodified_since_failed() { let file = NamedFile::open_async("Cargo.toml").await.unwrap(); let since = header::HttpDate::from(SystemTime::UNIX_EPOCH); let req = TestRequest::default() .insert_header((header::IF_UNMODIFIED_SINCE, since)) .to_http_request(); let resp = file.respond_to(&req); assert_eq!(resp.status(), StatusCode::PRECONDITION_FAILED); } #[actix_rt::test] async fn test_named_file_text() { assert!(NamedFile::open_async("test--").await.is_err()); let mut file = NamedFile::open_async("Cargo.toml").await.unwrap(); { file.file(); let _f: &File = &file; } { let _f: &mut File = &mut file; } let req = TestRequest::default().to_http_request(); let resp = file.respond_to(&req); assert_eq!( resp.headers().get(header::CONTENT_TYPE).unwrap(), "text/x-toml" ); assert_eq!( resp.headers().get(header::CONTENT_DISPOSITION).unwrap(), "inline; filename=\"Cargo.toml\"" ); } #[actix_rt::test] async fn test_named_file_content_disposition() { assert!(NamedFile::open_async("test--").await.is_err()); let mut file = NamedFile::open_async("Cargo.toml").await.unwrap(); { file.file(); let _f: &File = &file; } { let _f: &mut File = &mut file; } let req = TestRequest::default().to_http_request(); let resp = file.respond_to(&req); assert_eq!( resp.headers().get(header::CONTENT_DISPOSITION).unwrap(), "inline; filename=\"Cargo.toml\"" ); let file = NamedFile::open_async("Cargo.toml") .await .unwrap() .disable_content_disposition(); let req = TestRequest::default().to_http_request(); let resp = file.respond_to(&req); assert!(resp.headers().get(header::CONTENT_DISPOSITION).is_none()); } #[actix_rt::test] async fn test_named_file_non_ascii_file_name() { let file = { #[cfg(feature = "experimental-io-uring")] { crate::named::File::open("Cargo.toml").await.unwrap() } #[cfg(not(feature = "experimental-io-uring"))] { crate::named::File::open("Cargo.toml").unwrap() } }; let mut file = NamedFile::from_file(file, "貨物.toml").unwrap(); { file.file(); let _f: &File = &file; } { let _f: &mut File = &mut file; } let req = TestRequest::default().to_http_request(); let resp = file.respond_to(&req); assert_eq!( resp.headers().get(header::CONTENT_TYPE).unwrap(), "text/x-toml" ); assert_eq!( resp.headers().get(header::CONTENT_DISPOSITION).unwrap(), "inline; filename=\"貨物.toml\"; filename*=UTF-8''%E8%B2%A8%E7%89%A9.toml" ); } #[actix_rt::test] async fn test_named_file_set_content_type() { let mut file = NamedFile::open_async("Cargo.toml") .await .unwrap() .set_content_type(mime::TEXT_XML); { file.file(); let _f: &File = &file; } { let _f: &mut File = &mut file; } let req = TestRequest::default().to_http_request(); let resp = file.respond_to(&req); assert_eq!( resp.headers().get(header::CONTENT_TYPE).unwrap(), "text/xml" ); assert_eq!( resp.headers().get(header::CONTENT_DISPOSITION).unwrap(), "inline; filename=\"Cargo.toml\"" ); } #[actix_rt::test] async fn test_named_file_image() { let mut file = NamedFile::open_async("tests/test.png").await.unwrap(); { file.file(); let _f: &File = &file; } { let _f: &mut File = &mut file; } let req = TestRequest::default().to_http_request(); let resp = file.respond_to(&req); assert_eq!( resp.headers().get(header::CONTENT_TYPE).unwrap(), "image/png" ); assert_eq!( resp.headers().get(header::CONTENT_DISPOSITION).unwrap(), "inline; filename=\"test.png\"" ); } #[actix_rt::test] async fn test_named_file_javascript() { let file = NamedFile::open_async("tests/test.js").await.unwrap(); let req = TestRequest::default().to_http_request(); let resp = file.respond_to(&req); assert_eq!( resp.headers().get(header::CONTENT_TYPE).unwrap(), "text/javascript", ); assert_eq!( resp.headers().get(header::CONTENT_DISPOSITION).unwrap(), "inline; filename=\"test.js\"", ); } #[actix_rt::test] async fn test_named_file_image_attachment() { let cd = ContentDisposition { disposition: DispositionType::Attachment, parameters: vec![DispositionParam::Filename(String::from("test.png"))], }; let mut file = NamedFile::open_async("tests/test.png") .await .unwrap() .set_content_disposition(cd); { file.file(); let _f: &File = &file; } { let _f: &mut File = &mut file; } let req = TestRequest::default().to_http_request(); let resp = file.respond_to(&req); assert_eq!( resp.headers().get(header::CONTENT_TYPE).unwrap(), "image/png" ); assert_eq!( resp.headers().get(header::CONTENT_DISPOSITION).unwrap(), "attachment; filename=\"test.png\"" ); } #[actix_rt::test] async fn test_named_file_binary() { let mut file = NamedFile::open_async("tests/test.binary").await.unwrap(); { file.file(); let _f: &File = &file; } { let _f: &mut File = &mut file; } let req = TestRequest::default().to_http_request(); let resp = file.respond_to(&req); assert_eq!( resp.headers().get(header::CONTENT_TYPE).unwrap(), "application/octet-stream" ); assert_eq!( resp.headers().get(header::CONTENT_DISPOSITION).unwrap(), "attachment; filename=\"test.binary\"" ); } #[allow(deprecated)] #[actix_rt::test] async fn status_code_customize_same_output() { let file1 = NamedFile::open_async("Cargo.toml") .await .unwrap() .set_status_code(StatusCode::NOT_FOUND); let file2 = NamedFile::open_async("Cargo.toml") .await .unwrap() .customize() .with_status(StatusCode::NOT_FOUND); let req = TestRequest::default().to_http_request(); let res1 = file1.respond_to(&req); let res2 = file2.respond_to(&req); assert_eq!(res1.status(), StatusCode::NOT_FOUND); assert_eq!(res2.status(), StatusCode::NOT_FOUND); } #[actix_rt::test] async fn test_named_file_status_code_text() { let mut file = NamedFile::open_async("Cargo.toml").await.unwrap(); { file.file(); let _f: &File = &file; } { let _f: &mut File = &mut file; } let file = file.customize().with_status(StatusCode::NOT_FOUND); let req = TestRequest::default().to_http_request(); let resp = file.respond_to(&req); assert_eq!( resp.headers().get(header::CONTENT_TYPE).unwrap(), "text/x-toml" ); assert_eq!( resp.headers().get(header::CONTENT_DISPOSITION).unwrap(), "inline; filename=\"Cargo.toml\"" ); assert_eq!(resp.status(), StatusCode::NOT_FOUND); } #[actix_rt::test] async fn test_mime_override() { fn all_attachment(_: &mime::Name<'_>) -> DispositionType { DispositionType::Attachment } let srv = test::init_service( App::new().service( Files::new("/", ".") .mime_override(all_attachment) .index_file("Cargo.toml"), ), ) .await; let request = TestRequest::get().uri("/").to_request(); let response = test::call_service(&srv, request).await; assert_eq!(response.status(), StatusCode::OK); let content_disposition = response .headers() .get(header::CONTENT_DISPOSITION) .expect("To have CONTENT_DISPOSITION"); let content_disposition = content_disposition .to_str() .expect("Convert CONTENT_DISPOSITION to str"); assert_eq!(content_disposition, "attachment; filename=\"Cargo.toml\""); } #[actix_rt::test] async fn test_named_file_ranges_status_code() { let srv = test::init_service( App::new().service(Files::new("/test", ".").index_file("Cargo.toml")), ) .await; // Valid range header let request = TestRequest::get() .uri("/t%65st/Cargo.toml") .insert_header((header::RANGE, "bytes=10-20")) .to_request(); let response = test::call_service(&srv, request).await; assert_eq!(response.status(), StatusCode::PARTIAL_CONTENT); // Invalid range header let request = TestRequest::get() .uri("/t%65st/Cargo.toml") .insert_header((header::RANGE, "bytes=1-0")) .to_request(); let response = test::call_service(&srv, request).await; assert_eq!(response.status(), StatusCode::RANGE_NOT_SATISFIABLE); } #[actix_rt::test] async fn test_named_file_content_range_headers() { let srv = actix_test::start(|| App::new().service(Files::new("/", "."))); // Valid range header let response = srv .get("/tests/test.binary") .insert_header((header::RANGE, "bytes=10-20")) .send() .await .unwrap(); let content_range = response.headers().get(header::CONTENT_RANGE).unwrap(); assert_eq!(content_range.to_str().unwrap(), "bytes 10-20/100"); // Invalid range header let response = srv .get("/tests/test.binary") .insert_header((header::RANGE, "bytes=10-5")) .send() .await .unwrap(); let content_range = response.headers().get(header::CONTENT_RANGE).unwrap(); assert_eq!(content_range.to_str().unwrap(), "bytes */100"); } #[actix_rt::test] async fn test_named_file_content_length_headers() { let srv = actix_test::start(|| App::new().service(Files::new("/", "."))); // Valid range header let response = srv .get("/tests/test.binary") .insert_header((header::RANGE, "bytes=10-20")) .send() .await .unwrap(); let content_length = response.headers().get(header::CONTENT_LENGTH).unwrap(); assert_eq!(content_length.to_str().unwrap(), "11"); // Valid range header, starting from 0 let response = srv .get("/tests/test.binary") .insert_header((header::RANGE, "bytes=0-20")) .send() .await .unwrap(); let content_length = response.headers().get(header::CONTENT_LENGTH).unwrap(); assert_eq!(content_length.to_str().unwrap(), "21"); // Without range header let mut response = srv.get("/tests/test.binary").send().await.unwrap(); let content_length = response.headers().get(header::CONTENT_LENGTH).unwrap(); assert_eq!(content_length.to_str().unwrap(), "100"); // Should be no transfer-encoding let transfer_encoding = response.headers().get(header::TRANSFER_ENCODING); assert!(transfer_encoding.is_none()); // Check file contents let bytes = response.body().await.unwrap(); let data = web::Bytes::from(fs::read("tests/test.binary").unwrap()); assert_eq!(bytes, data); } #[actix_rt::test] async fn test_head_content_length_headers() { let srv = actix_test::start(|| App::new().service(Files::new("/", "."))); let response = srv.head("/tests/test.binary").send().await.unwrap(); let content_length = response .headers() .get(header::CONTENT_LENGTH) .unwrap() .to_str() .unwrap(); assert_eq!(content_length, "100"); } #[actix_rt::test] async fn test_static_files_with_spaces() { let srv = test::init_service(App::new().service(Files::new("/", ".").index_file("Cargo.toml"))) .await; let request = TestRequest::get() .uri("/tests/test%20space.binary") .to_request(); let response = test::call_service(&srv, request).await; assert_eq!(response.status(), StatusCode::OK); let bytes = test::read_body(response).await; let data = web::Bytes::from(fs::read("tests/test space.binary").unwrap()); assert_eq!(bytes, data); } #[cfg(not(target_os = "windows"))] #[actix_rt::test] async fn test_static_files_with_special_characters() { // Create the file we want to test against ad-hoc. We can't check it in as otherwise // Windows can't even checkout this repository. let temp_dir = tempfile::tempdir().unwrap(); let file_with_newlines = temp_dir.path().join("test\n\x0B\x0C\rnewline.text"); fs::write(&file_with_newlines, "Look at my newlines").unwrap(); let srv = test::init_service( App::new().service(Files::new("/", temp_dir.path()).index_file("Cargo.toml")), ) .await; let request = TestRequest::get() .uri("/test%0A%0B%0C%0Dnewline.text") .to_request(); let response = test::call_service(&srv, request).await; assert_eq!(response.status(), StatusCode::OK); let bytes = test::read_body(response).await; let data = web::Bytes::from(fs::read(file_with_newlines).unwrap()); assert_eq!(bytes, data); } #[actix_rt::test] async fn test_files_not_allowed() { let srv = test::init_service(App::new().service(Files::new("/", "."))).await; let req = TestRequest::default() .uri("/Cargo.toml") .method(Method::POST) .to_request(); let resp = test::call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED); let srv = test::init_service(App::new().service(Files::new("/", "."))).await; let req = TestRequest::default() .method(Method::PUT) .uri("/Cargo.toml") .to_request(); let resp = test::call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::METHOD_NOT_ALLOWED); } #[actix_rt::test] async fn test_files_guards() { let srv = test::init_service( App::new().service(Files::new("/", ".").method_guard(guard::Post())), ) .await; let req = TestRequest::default() .uri("/Cargo.toml") .method(Method::POST) .to_request(); let resp = test::call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); } #[actix_rt::test] async fn test_named_file_content_encoding() { let srv = test::init_service(App::new().wrap(Compress::default()).service( web::resource("/").to(|| async { NamedFile::open_async("Cargo.toml") .await .unwrap() .set_content_encoding(header::ContentEncoding::Identity) }), )) .await; let request = TestRequest::get() .uri("/") .insert_header((header::ACCEPT_ENCODING, "gzip")) .to_request(); let res = test::call_service(&srv, request).await; assert_eq!(res.status(), StatusCode::OK); assert!(res.headers().contains_key(header::CONTENT_ENCODING)); assert!(!test::read_body(res).await.is_empty()); } #[actix_rt::test] async fn test_named_file_content_encoding_gzip() { let srv = test::init_service(App::new().wrap(Compress::default()).service( web::resource("/").to(|| async { NamedFile::open_async("Cargo.toml") .await .unwrap() .set_content_encoding(header::ContentEncoding::Gzip) }), )) .await; let request = TestRequest::get() .uri("/") .insert_header((header::ACCEPT_ENCODING, "gzip")) .to_request(); let res = test::call_service(&srv, request).await; assert_eq!(res.status(), StatusCode::OK); assert_eq!( res.headers() .get(header::CONTENT_ENCODING) .unwrap() .to_str() .unwrap(), "gzip" ); } #[actix_rt::test] async fn test_named_file_allowed_method() { let req = TestRequest::default().method(Method::GET).to_http_request(); let file = NamedFile::open_async("Cargo.toml").await.unwrap(); let resp = file.respond_to(&req); assert_eq!(resp.status(), StatusCode::OK); } #[actix_rt::test] async fn test_static_files() { let srv = test::init_service(App::new().service(Files::new("/", ".").show_files_listing())).await; let req = TestRequest::with_uri("/missing").to_request(); let resp = test::call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::NOT_FOUND); let srv = test::init_service(App::new().service(Files::new("/", "."))).await; let req = TestRequest::default().to_request(); let resp = test::call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::NOT_FOUND); let srv = test::init_service(App::new().service(Files::new("/", ".").show_files_listing())).await; let req = TestRequest::with_uri("/tests").to_request(); let resp = test::call_service(&srv, req).await; assert_eq!( resp.headers().get(header::CONTENT_TYPE).unwrap(), "text/html; charset=utf-8" ); let bytes = test::read_body(resp).await; assert!(format!("{:?}", bytes).contains("/tests/test.png")); } #[actix_rt::test] async fn test_redirect_to_slash_directory() { // should not redirect if no index and files listing is disabled let srv = test::init_service( App::new().service(Files::new("/", ".").redirect_to_slash_directory()), ) .await; let req = TestRequest::with_uri("/tests").to_request(); let resp = test::call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::NOT_FOUND); // should redirect if index present let srv = test::init_service( App::new().service( Files::new("/", ".") .index_file("test.png") .redirect_to_slash_directory(), ), ) .await; let req = TestRequest::with_uri("/tests").to_request(); let resp = test::call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::TEMPORARY_REDIRECT); // should redirect if index present with permanent redirect let srv = test::init_service( App::new().service( Files::new("/", ".") .index_file("test.png") .redirect_to_slash_directory() .with_permanent_redirect(), ), ) .await; let req = TestRequest::with_uri("/tests").to_request(); let resp = test::call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::PERMANENT_REDIRECT); // should redirect if files listing is enabled let srv = test::init_service( App::new().service( Files::new("/", ".") .show_files_listing() .redirect_to_slash_directory(), ), ) .await; let req = TestRequest::with_uri("/tests").to_request(); let resp = test::call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::TEMPORARY_REDIRECT); // should not redirect if the path is wrong let req = TestRequest::with_uri("/not_existing").to_request(); let resp = test::call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::NOT_FOUND); } #[actix_rt::test] async fn test_static_files_bad_directory() { let service = Files::new("/", "./missing").new_service(()).await.unwrap(); let req = TestRequest::with_uri("/").to_srv_request(); let resp = test::call_service(&service, req).await; assert_eq!(resp.status(), StatusCode::NOT_FOUND); } #[actix_rt::test] async fn test_default_handler_file_missing() { let st = Files::new("/", ".") .default_handler(|req: ServiceRequest| async { Ok(req.into_response(HttpResponse::Ok().body("default content"))) }) .new_service(()) .await .unwrap(); let req = TestRequest::with_uri("/missing").to_srv_request(); let resp = test::call_service(&st, req).await; assert_eq!(resp.status(), StatusCode::OK); let bytes = test::read_body(resp).await; assert_eq!(bytes, web::Bytes::from_static(b"default content")); } #[actix_rt::test] async fn test_serve_index_nested() { let service = Files::new(".", ".") .index_file("lib.rs") .new_service(()) .await .unwrap(); let req = TestRequest::default().uri("/src").to_srv_request(); let resp = test::call_service(&service, req).await; assert_eq!(resp.status(), StatusCode::OK); assert_eq!( resp.headers().get(header::CONTENT_TYPE).unwrap(), "text/x-rust" ); assert_eq!( resp.headers().get(header::CONTENT_DISPOSITION).unwrap(), "inline; filename=\"lib.rs\"" ); } #[actix_rt::test] async fn integration_serve_index() { let srv = test::init_service( App::new().service(Files::new("test", ".").index_file("Cargo.toml")), ) .await; let req = TestRequest::get().uri("/test").to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::OK); let bytes = test::read_body(res).await; let data = Bytes::from(fs::read("Cargo.toml").unwrap()); assert_eq!(bytes, data); let req = TestRequest::get().uri("/test/").to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::OK); let bytes = test::read_body(res).await; let data = Bytes::from(fs::read("Cargo.toml").unwrap()); assert_eq!(bytes, data); // nonexistent index file let req = TestRequest::get().uri("/test/unknown").to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::NOT_FOUND); let req = TestRequest::get().uri("/test/unknown/").to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::NOT_FOUND); } #[actix_rt::test] async fn integration_percent_encoded() { let srv = test::init_service( App::new().service(Files::new("test", ".").index_file("Cargo.toml")), ) .await; let req = TestRequest::get().uri("/test/%43argo.toml").to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::OK); // `%2F` == `/` let req = TestRequest::get().uri("/test%2Ftest.binary").to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::NOT_FOUND); let req = TestRequest::get().uri("/test/Cargo.toml%00").to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::NOT_FOUND); } #[actix_rt::test] async fn test_percent_encoding_2() { let temp_dir = tempfile::tempdir().unwrap(); let filename = match cfg!(unix) { true => "ض:?#[]{}<>()@!$&'`|*+,;= %20\n.test", false => "ض#[]{}()@!$&'`+,;= %20.test", }; let filename_encoded = filename .as_bytes() .iter() .fold(String::new(), |mut buf, c| { write!(&mut buf, "%{:02X}", c).unwrap(); buf }); std::fs::File::create(temp_dir.path().join(filename)).unwrap(); let srv = test::init_service(App::new().service(Files::new("/", temp_dir.path()))).await; let req = TestRequest::get() .uri(&format!("/{}", filename_encoded)) .to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::OK); } #[actix_rt::test] async fn test_serve_named_file() { let factory = NamedFile::open_async("Cargo.toml").await.unwrap(); let srv = test::init_service(App::new().service(factory)).await; let req = TestRequest::get().uri("/Cargo.toml").to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::OK); let bytes = test::read_body(res).await; let data = Bytes::from(fs::read("Cargo.toml").unwrap()); assert_eq!(bytes, data); let req = TestRequest::get().uri("/test/unknown").to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::NOT_FOUND); } #[actix_rt::test] async fn test_serve_named_file_prefix() { let factory = NamedFile::open_async("Cargo.toml").await.unwrap(); let srv = test::init_service(App::new().service(web::scope("/test").service(factory))).await; let req = TestRequest::get().uri("/test/Cargo.toml").to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::OK); let bytes = test::read_body(res).await; let data = Bytes::from(fs::read("Cargo.toml").unwrap()); assert_eq!(bytes, data); let req = TestRequest::get().uri("/Cargo.toml").to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::NOT_FOUND); } #[actix_rt::test] async fn test_named_file_default_service() { let factory = NamedFile::open_async("Cargo.toml").await.unwrap(); let srv = test::init_service(App::new().default_service(factory)).await; for route in ["/foobar", "/baz", "/"].iter() { let req = TestRequest::get().uri(route).to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::OK); let bytes = test::read_body(res).await; let data = Bytes::from(fs::read("Cargo.toml").unwrap()); assert_eq!(bytes, data); } } #[actix_rt::test] async fn test_default_handler_named_file() {
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
true
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-files/src/range.rs
actix-files/src/range.rs
use std::fmt; use derive_more::Error; /// Copy of `http_range::HttpRangeParseError`. #[derive(Debug, Clone)] enum HttpRangeParseError { InvalidRange, NoOverlap, } impl From<http_range::HttpRangeParseError> for HttpRangeParseError { fn from(err: http_range::HttpRangeParseError) -> Self { match err { http_range::HttpRangeParseError::InvalidRange => Self::InvalidRange, http_range::HttpRangeParseError::NoOverlap => Self::NoOverlap, } } } #[derive(Debug, Clone, Error)] #[non_exhaustive] pub struct ParseRangeErr(#[error(not(source))] HttpRangeParseError); impl fmt::Display for ParseRangeErr { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("invalid Range header: ")?; f.write_str(match self.0 { HttpRangeParseError::InvalidRange => "invalid syntax", HttpRangeParseError::NoOverlap => "range starts after end of content", }) } } /// HTTP Range header representation. #[derive(Debug, Clone, Copy)] pub struct HttpRange { /// Start of range. pub start: u64, /// Length of range. pub length: u64, } impl HttpRange { /// Parses Range HTTP header string as per RFC 2616. /// /// `header` is HTTP Range header (e.g. `bytes=bytes=0-9`). /// `size` is full size of response (file). pub fn parse(header: &str, size: u64) -> Result<Vec<HttpRange>, ParseRangeErr> { let ranges = http_range::HttpRange::parse(header, size).map_err(|err| ParseRangeErr(err.into()))?; Ok(ranges .iter() .map(|range| HttpRange { start: range.start, length: range.length, }) .collect()) } } #[cfg(test)] mod tests { use super::*; struct T(&'static str, u64, Vec<HttpRange>); #[test] fn test_parse() { let tests = vec![ T("", 0, vec![]), T("", 1000, vec![]), T("foo", 0, vec![]), T("bytes=", 0, vec![]), T("bytes=7", 10, vec![]), T("bytes= 7 ", 10, vec![]), T("bytes=1-", 0, vec![]), T("bytes=5-4", 10, vec![]), T("bytes=0-2,5-4", 10, vec![]), T("bytes=2-5,4-3", 10, vec![]), T("bytes=--5,4--3", 10, vec![]), T("bytes=A-", 10, vec![]), T("bytes=A- ", 10, vec![]), T("bytes=A-Z", 10, vec![]), T("bytes= -Z", 10, vec![]), T("bytes=5-Z", 10, vec![]), T("bytes=Ran-dom, garbage", 10, vec![]), T("bytes=0x01-0x02", 10, vec![]), T("bytes= ", 10, vec![]), T("bytes= , , , ", 10, vec![]), T( "bytes=0-9", 10, vec![HttpRange { start: 0, length: 10, }], ), T( "bytes=0-", 10, vec![HttpRange { start: 0, length: 10, }], ), T( "bytes=5-", 10, vec![HttpRange { start: 5, length: 5, }], ), T( "bytes=0-20", 10, vec![HttpRange { start: 0, length: 10, }], ), T( "bytes=15-,0-5", 10, vec![HttpRange { start: 0, length: 6, }], ), T( "bytes=1-2,5-", 10, vec![ HttpRange { start: 1, length: 2, }, HttpRange { start: 5, length: 5, }, ], ), T( "bytes=-2 , 7-", 11, vec![ HttpRange { start: 9, length: 2, }, HttpRange { start: 7, length: 4, }, ], ), T( "bytes=0-0 ,2-2, 7-", 11, vec![ HttpRange { start: 0, length: 1, }, HttpRange { start: 2, length: 1, }, HttpRange { start: 7, length: 4, }, ], ), T( "bytes=-5", 10, vec![HttpRange { start: 5, length: 5, }], ), T( "bytes=-15", 10, vec![HttpRange { start: 0, length: 10, }], ), T( "bytes=0-499", 10000, vec![HttpRange { start: 0, length: 500, }], ), T( "bytes=500-999", 10000, vec![HttpRange { start: 500, length: 500, }], ), T( "bytes=-500", 10000, vec![HttpRange { start: 9500, length: 500, }], ), T( "bytes=9500-", 10000, vec![HttpRange { start: 9500, length: 500, }], ), T( "bytes=0-0,-1", 10000, vec![ HttpRange { start: 0, length: 1, }, HttpRange { start: 9999, length: 1, }, ], ), T( "bytes=500-600,601-999", 10000, vec![ HttpRange { start: 500, length: 101, }, HttpRange { start: 601, length: 399, }, ], ), T( "bytes=500-700,601-999", 10000, vec![ HttpRange { start: 500, length: 201, }, HttpRange { start: 601, length: 399, }, ], ), // Match Apache laxity: T( "bytes= 1 -2 , 4- 5, 7 - 8 , ,,", 11, vec![ HttpRange { start: 1, length: 2, }, HttpRange { start: 4, length: 2, }, HttpRange { start: 7, length: 2, }, ], ), ]; for t in tests { let header = t.0; let size = t.1; let expected = t.2; let res = HttpRange::parse(header, size); if let Err(err) = res { if expected.is_empty() { continue; } else { panic!("parse({header}, {size}) returned error {err:?}"); } } let got = res.unwrap(); if got.len() != expected.len() { panic!( "len(parseRange({}, {})) = {}, want {}", header, size, got.len(), expected.len() ); } for i in 0..expected.len() { if got[i].start != expected[i].start { panic!( "parseRange({}, {})[{}].start = {}, want {}", header, size, i, got[i].start, expected[i].start ) } if got[i].length != expected[i].length { panic!( "parseRange({}, {})[{}].length = {}, want {}", header, size, i, got[i].length, expected[i].length ) } } } } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-files/src/error.rs
actix-files/src/error.rs
use actix_web::{http::StatusCode, ResponseError}; use derive_more::Display; /// Errors which can occur when serving static files. #[derive(Debug, PartialEq, Eq, Display)] pub enum FilesError { /// Path is not a directory. #[allow(dead_code)] #[display("path is not a directory. Unable to serve static files")] IsNotDirectory, /// Cannot render directory. #[display("unable to render directory without index file")] IsDirectory, } impl ResponseError for FilesError { /// Returns `404 Not Found`. fn status_code(&self) -> StatusCode { StatusCode::NOT_FOUND } } #[derive(Debug, PartialEq, Eq, Display)] #[non_exhaustive] pub enum UriSegmentError { /// Segment started with the wrapped invalid character. #[display("segment started with invalid character: ('{_0}')")] BadStart(char), /// Segment contained the wrapped invalid character. #[display("segment contained invalid character ('{_0}')")] BadChar(char), /// Segment ended with the wrapped invalid character. #[display("segment ended with invalid character: ('{_0}')")] BadEnd(char), /// Path is not a valid UTF-8 string after percent-decoding. #[display("path is not a valid UTF-8 string after percent-decoding")] NotValidUtf8, } impl ResponseError for UriSegmentError { /// Returns `400 Bad Request`. fn status_code(&self) -> StatusCode { StatusCode::BAD_REQUEST } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-files/src/service.rs
actix-files/src/service.rs
use std::{fmt, io, ops::Deref, path::PathBuf, rc::Rc}; use actix_web::{ body::BoxBody, dev::{self, Service, ServiceRequest, ServiceResponse}, error::Error, guard::Guard, http::{header, Method}, HttpResponse, }; use futures_core::future::LocalBoxFuture; use crate::{ named, Directory, DirectoryRenderer, FilesError, HttpService, MimeOverride, NamedFile, PathBufWrap, PathFilter, }; /// Assembled file serving service. #[derive(Clone)] pub struct FilesService(pub(crate) Rc<FilesServiceInner>); impl Deref for FilesService { type Target = FilesServiceInner; fn deref(&self) -> &Self::Target { &self.0 } } pub struct FilesServiceInner { pub(crate) directory: PathBuf, pub(crate) index: Option<String>, pub(crate) show_index: bool, pub(crate) redirect_to_slash: bool, pub(crate) default: Option<HttpService>, pub(crate) renderer: Rc<DirectoryRenderer>, pub(crate) mime_override: Option<Rc<MimeOverride>>, pub(crate) path_filter: Option<Rc<PathFilter>>, pub(crate) file_flags: named::Flags, pub(crate) guards: Option<Rc<dyn Guard>>, pub(crate) hidden_files: bool, pub(crate) size_threshold: u64, pub(crate) with_permanent_redirect: bool, } impl fmt::Debug for FilesServiceInner { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("FilesServiceInner") } } impl FilesService { async fn handle_err( &self, err: io::Error, req: ServiceRequest, ) -> Result<ServiceResponse, Error> { log::debug!("error handling {}: {}", req.path(), err); if let Some(ref default) = self.default { default.call(req).await } else { Ok(req.error_response(err)) } } fn serve_named_file(&self, req: ServiceRequest, mut named_file: NamedFile) -> ServiceResponse { if let Some(ref mime_override) = self.mime_override { let new_disposition = mime_override(&named_file.content_type.type_()); named_file.content_disposition.disposition = new_disposition; } named_file.flags = self.file_flags; let (req, _) = req.into_parts(); let res = named_file .read_mode_threshold(self.size_threshold) .into_response(&req); ServiceResponse::new(req, res) } fn show_index(&self, req: ServiceRequest, path: PathBuf) -> ServiceResponse { let dir = Directory::new(self.directory.clone(), path); let (req, _) = req.into_parts(); (self.renderer)(&dir, &req).unwrap_or_else(|err| ServiceResponse::from_err(err, req)) } } impl fmt::Debug for FilesService { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("FilesService") } } impl Service<ServiceRequest> for FilesService { type Response = ServiceResponse<BoxBody>; type Error = Error; type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; dev::always_ready!(); fn call(&self, req: ServiceRequest) -> Self::Future { let is_method_valid = if let Some(guard) = &self.guards { // execute user defined guards (**guard).check(&req.guard_ctx()) } else { // default behavior matches!(*req.method(), Method::HEAD | Method::GET) }; let this = self.clone(); Box::pin(async move { if !is_method_valid { return Ok(req.into_response( HttpResponse::MethodNotAllowed() .insert_header(header::ContentType(mime::TEXT_PLAIN_UTF_8)) .body("Request did not meet this resource's requirements."), )); } let path_on_disk = match PathBufWrap::parse_path(req.match_info().unprocessed(), this.hidden_files) { Ok(item) => item, Err(err) => return Ok(req.error_response(err)), }; if let Some(filter) = &this.path_filter { if !filter(path_on_disk.as_ref(), req.head()) { if let Some(ref default) = this.default { return default.call(req).await; } else { return Ok(req.into_response(HttpResponse::NotFound().finish())); } } } // full file path let path = this.directory.join(&path_on_disk); if let Err(err) = path.canonicalize() { return this.handle_err(err, req).await; } if path.is_dir() { if this.redirect_to_slash && !req.path().ends_with('/') && (this.index.is_some() || this.show_index) { let redirect_to = format!("{}/", req.path()); let response = if this.with_permanent_redirect { HttpResponse::PermanentRedirect() } else { HttpResponse::TemporaryRedirect() } .insert_header((header::LOCATION, redirect_to)) .finish(); return Ok(req.into_response(response)); } match this.index { Some(ref index) => { let named_path = path.join(index); match NamedFile::open_async(named_path).await { Ok(named_file) => Ok(this.serve_named_file(req, named_file)), Err(_) if this.show_index => Ok(this.show_index(req, path)), Err(err) => this.handle_err(err, req).await, } } None if this.show_index => Ok(this.show_index(req, path)), None => Ok(ServiceResponse::from_err( FilesError::IsDirectory, req.into_parts().0, )), } } else { match NamedFile::open_async(&path).await { Ok(named_file) => Ok(this.serve_named_file(req, named_file)), Err(err) => this.handle_err(err, req).await, } } }) } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-files/src/path_buf.rs
actix-files/src/path_buf.rs
use std::{ path::{Component, Path, PathBuf}, str::FromStr, }; use actix_utils::future::{ready, Ready}; use actix_web::{dev::Payload, FromRequest, HttpRequest}; use crate::error::UriSegmentError; #[derive(Debug, PartialEq, Eq)] pub(crate) struct PathBufWrap(PathBuf); impl FromStr for PathBufWrap { type Err = UriSegmentError; fn from_str(path: &str) -> Result<Self, Self::Err> { Self::parse_path(path, false) } } impl PathBufWrap { /// Parse a path, giving the choice of allowing hidden files to be considered valid segments. /// /// Path traversal is guarded by this method. pub fn parse_path(path: &str, hidden_files: bool) -> Result<Self, UriSegmentError> { let mut buf = PathBuf::new(); // equivalent to `path.split('/').count()` let mut segment_count = path.matches('/').count() + 1; // we can decode the whole path here (instead of per-segment decoding) // because we will reject `%2F` in paths using `segment_count`. let path = percent_encoding::percent_decode_str(path) .decode_utf8() .map_err(|_| UriSegmentError::NotValidUtf8)?; // disallow decoding `%2F` into `/` if segment_count != path.matches('/').count() + 1 { return Err(UriSegmentError::BadChar('/')); } for segment in path.split('/') { if segment == ".." { segment_count -= 1; buf.pop(); } else if !hidden_files && segment.starts_with('.') { return Err(UriSegmentError::BadStart('.')); } else if segment.starts_with('*') { return Err(UriSegmentError::BadStart('*')); } else if segment.ends_with(':') { return Err(UriSegmentError::BadEnd(':')); } else if segment.ends_with('>') { return Err(UriSegmentError::BadEnd('>')); } else if segment.ends_with('<') { return Err(UriSegmentError::BadEnd('<')); } else if segment.is_empty() { segment_count -= 1; continue; } else if cfg!(windows) && segment.contains('\\') { return Err(UriSegmentError::BadChar('\\')); } else if cfg!(windows) && segment.contains(':') { return Err(UriSegmentError::BadChar(':')); } else { buf.push(segment) } } // make sure we agree with stdlib parser for (i, component) in buf.components().enumerate() { assert!( matches!(component, Component::Normal(_)), "component `{:?}` is not normal", component ); assert!(i < segment_count); } Ok(PathBufWrap(buf)) } } impl AsRef<Path> for PathBufWrap { fn as_ref(&self) -> &Path { self.0.as_ref() } } impl FromRequest for PathBufWrap { type Error = UriSegmentError; type Future = Ready<Result<Self, Self::Error>>; fn from_request(req: &HttpRequest, _: &mut Payload) -> Self::Future { ready(req.match_info().unprocessed().parse()) } } #[cfg(test)] mod tests { use super::*; #[test] fn test_path_buf() { assert_eq!( PathBufWrap::from_str("/test/.tt").map(|t| t.0), Err(UriSegmentError::BadStart('.')) ); assert_eq!( PathBufWrap::from_str("/test/*tt").map(|t| t.0), Err(UriSegmentError::BadStart('*')) ); assert_eq!( PathBufWrap::from_str("/test/tt:").map(|t| t.0), Err(UriSegmentError::BadEnd(':')) ); assert_eq!( PathBufWrap::from_str("/test/tt<").map(|t| t.0), Err(UriSegmentError::BadEnd('<')) ); assert_eq!( PathBufWrap::from_str("/test/tt>").map(|t| t.0), Err(UriSegmentError::BadEnd('>')) ); assert_eq!( PathBufWrap::from_str("/seg1/seg2/").unwrap().0, PathBuf::from_iter(vec!["seg1", "seg2"]) ); assert_eq!( PathBufWrap::from_str("/seg1/../seg2/").unwrap().0, PathBuf::from_iter(vec!["seg2"]) ); } #[test] fn test_parse_path() { assert_eq!( PathBufWrap::parse_path("/test/.tt", false).map(|t| t.0), Err(UriSegmentError::BadStart('.')) ); assert_eq!( PathBufWrap::parse_path("/test/.tt", true).unwrap().0, PathBuf::from_iter(vec!["test", ".tt"]) ); } #[test] fn path_traversal() { assert_eq!( PathBufWrap::parse_path("/../README.md", false).unwrap().0, PathBuf::from_iter(vec!["README.md"]) ); assert_eq!( PathBufWrap::parse_path("/../README.md", true).unwrap().0, PathBuf::from_iter(vec!["README.md"]) ); assert_eq!( PathBufWrap::parse_path("/../../../../../../../../../../etc/passwd", false) .unwrap() .0, PathBuf::from_iter(vec!["etc/passwd"]) ); } #[test] #[cfg_attr(windows, should_panic)] fn windows_drive_traversal() { // detect issues in windows that could lead to path traversal // see <https://github.com/SergioBenitez/Rocket/issues/1949 assert_eq!( PathBufWrap::parse_path("C:test.txt", false).unwrap().0, PathBuf::from_iter(vec!["C:test.txt"]) ); assert_eq!( PathBufWrap::parse_path("C:../whatever", false).unwrap().0, PathBuf::from_iter(vec!["C:../whatever"]) ); assert_eq!( PathBufWrap::parse_path(":test.txt", false).unwrap().0, PathBuf::from_iter(vec![":test.txt"]) ); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-files/src/named.rs
actix-files/src/named.rs
use std::{ fs::Metadata, io, path::{Path, PathBuf}, time::{SystemTime, UNIX_EPOCH}, }; use actix_web::{ body::{self, BoxBody, SizedStream}, dev::{ self, AppService, HttpServiceFactory, ResourceDef, Service, ServiceFactory, ServiceRequest, ServiceResponse, }, http::{ header::{ self, Charset, ContentDisposition, ContentEncoding, DispositionParam, DispositionType, ExtendedValue, HeaderValue, }, StatusCode, }, Error, HttpMessage, HttpRequest, HttpResponse, Responder, }; use bitflags::bitflags; use derive_more::{Deref, DerefMut}; use futures_core::future::LocalBoxFuture; use mime::Mime; use crate::{encoding::equiv_utf8_text, range::HttpRange}; bitflags! { #[derive(Debug, Clone, Copy)] pub(crate) struct Flags: u8 { const ETAG = 0b0000_0001; const LAST_MD = 0b0000_0010; const CONTENT_DISPOSITION = 0b0000_0100; const PREFER_UTF8 = 0b0000_1000; } } impl Default for Flags { fn default() -> Self { Flags::from_bits_truncate(0b0000_1111) } } /// A file with an associated name. /// /// `NamedFile` can be registered as services: /// ``` /// use actix_web::App; /// use actix_files::NamedFile; /// /// # async fn run() -> Result<(), Box<dyn std::error::Error>> { /// let file = NamedFile::open_async("./static/index.html").await?; /// let app = App::new().service(file); /// # Ok(()) /// # } /// ``` /// /// They can also be returned from handlers: /// ``` /// use actix_web::{Responder, get}; /// use actix_files::NamedFile; /// /// #[get("/")] /// async fn index() -> impl Responder { /// NamedFile::open_async("./static/index.html").await /// } /// ``` #[derive(Debug, Deref, DerefMut)] pub struct NamedFile { #[deref] #[deref_mut] file: File, path: PathBuf, modified: Option<SystemTime>, pub(crate) md: Metadata, pub(crate) flags: Flags, pub(crate) status_code: StatusCode, pub(crate) content_type: Mime, pub(crate) content_disposition: ContentDisposition, pub(crate) encoding: Option<ContentEncoding>, pub(crate) read_mode_threshold: u64, } #[cfg(not(feature = "experimental-io-uring"))] pub(crate) use std::fs::File; #[cfg(feature = "experimental-io-uring")] pub(crate) use tokio_uring::fs::File; use super::chunked; impl NamedFile { /// Creates an instance from a previously opened file. /// /// The given `path` need not exist and is only used to determine the `ContentType` and /// `ContentDisposition` headers. /// /// # Examples /// ```ignore /// use std::{ /// io::{self, Write as _}, /// env, /// fs::File /// }; /// use actix_files::NamedFile; /// /// let mut file = File::create("foo.txt")?; /// file.write_all(b"Hello, world!")?; /// let named_file = NamedFile::from_file(file, "bar.txt")?; /// # std::fs::remove_file("foo.txt"); /// Ok(()) /// ``` pub fn from_file<P: AsRef<Path>>(file: File, path: P) -> io::Result<NamedFile> { let path = path.as_ref().to_path_buf(); // Get the name of the file and use it to construct default Content-Type // and Content-Disposition values let (content_type, content_disposition) = { let filename = match path.file_name() { Some(name) => name.to_string_lossy(), None => { return Err(io::Error::new( io::ErrorKind::InvalidInput, "Provided path has no filename", )); } }; let ct = mime_guess::from_path(&path).first_or_octet_stream(); let disposition = match ct.type_() { mime::IMAGE | mime::TEXT | mime::AUDIO | mime::VIDEO => DispositionType::Inline, mime::APPLICATION => match ct.subtype() { mime::JAVASCRIPT | mime::JSON => DispositionType::Inline, name if name == "wasm" || name == "xhtml" => DispositionType::Inline, _ => DispositionType::Attachment, }, _ => DispositionType::Attachment, }; // replace special characters in filenames which could occur on some filesystems let filename_s = filename .replace('\n', "%0A") // \n line break .replace('\x0B', "%0B") // \v vertical tab .replace('\x0C', "%0C") // \f form feed .replace('\r', "%0D"); // \r carriage return let mut parameters = vec![DispositionParam::Filename(filename_s)]; if !filename.is_ascii() { parameters.push(DispositionParam::FilenameExt(ExtendedValue { charset: Charset::Ext(String::from("UTF-8")), language_tag: None, value: filename.into_owned().into_bytes(), })) } let cd = ContentDisposition { disposition, parameters, }; (ct, cd) }; let md = { #[cfg(not(feature = "experimental-io-uring"))] { file.metadata()? } #[cfg(feature = "experimental-io-uring")] { use std::os::unix::prelude::{AsRawFd, FromRawFd}; let fd = file.as_raw_fd(); // SAFETY: fd is borrowed and lives longer than the unsafe block unsafe { let file = std::fs::File::from_raw_fd(fd); let md = file.metadata(); // SAFETY: forget the fd before exiting block in success or error case but don't // run destructor (that would close file handle) std::mem::forget(file); md? } } }; let modified = md.modified().ok(); let encoding = None; Ok(NamedFile { path, file, content_type, content_disposition, md, modified, encoding, status_code: StatusCode::OK, flags: Flags::default(), read_mode_threshold: 0, }) } /// Attempts to open a file in read-only mode. /// /// # Examples /// ``` /// use actix_files::NamedFile; /// let file = NamedFile::open("foo.txt"); /// ``` #[cfg(not(feature = "experimental-io-uring"))] pub fn open<P: AsRef<Path>>(path: P) -> io::Result<NamedFile> { let file = File::open(&path)?; Self::from_file(file, path) } /// Attempts to open a file asynchronously in read-only mode. /// /// When the `experimental-io-uring` crate feature is enabled, this will be async. Otherwise, it /// will behave just like `open`. /// /// # Examples /// ``` /// use actix_files::NamedFile; /// # async fn open() { /// let file = NamedFile::open_async("foo.txt").await.unwrap(); /// # } /// ``` pub async fn open_async<P: AsRef<Path>>(path: P) -> io::Result<NamedFile> { let file = { #[cfg(not(feature = "experimental-io-uring"))] { File::open(&path)? } #[cfg(feature = "experimental-io-uring")] { File::open(&path).await? } }; Self::from_file(file, path) } /// Returns reference to the underlying file object. #[inline] pub fn file(&self) -> &File { &self.file } /// Returns the filesystem path to this file. /// /// # Examples /// ``` /// # use std::io; /// use actix_files::NamedFile; /// /// # async fn path() -> io::Result<()> { /// let file = NamedFile::open_async("test.txt").await?; /// assert_eq!(file.path().as_os_str(), "foo.txt"); /// # Ok(()) /// # } /// ``` #[inline] pub fn path(&self) -> &Path { self.path.as_path() } /// Returns the time the file was last modified. /// /// Returns `None` only on unsupported platforms; see [`std::fs::Metadata::modified()`]. /// Therefore, it is usually safe to unwrap this. #[inline] pub fn modified(&self) -> Option<SystemTime> { self.modified } /// Returns the filesystem metadata associated with this file. #[inline] pub fn metadata(&self) -> &Metadata { &self.md } /// Returns the `Content-Type` header that will be used when serving this file. #[inline] pub fn content_type(&self) -> &Mime { &self.content_type } /// Returns the `Content-Disposition` that will be used when serving this file. #[inline] pub fn content_disposition(&self) -> &ContentDisposition { &self.content_disposition } /// Returns the `Content-Encoding` that will be used when serving this file. /// /// A return value of `None` indicates that the content is not already using a compressed /// representation and may be subject to compression downstream. #[inline] pub fn content_encoding(&self) -> Option<ContentEncoding> { self.encoding } /// Set response status code. #[deprecated(since = "0.7.0", note = "Prefer `Responder::customize()`.")] pub fn set_status_code(mut self, status: StatusCode) -> Self { self.status_code = status; self } /// Sets the `Content-Type` header that will be used when serving this file. By default the /// `Content-Type` is inferred from the filename extension. #[inline] pub fn set_content_type(mut self, mime_type: Mime) -> Self { self.content_type = mime_type; self } /// Set the Content-Disposition for serving this file. This allows changing the /// `inline/attachment` disposition as well as the filename sent to the peer. /// /// By default the disposition is `inline` for `text/*`, `image/*`, `video/*` and /// `application/{javascript, json, wasm}` mime types, and `attachment` otherwise, and the /// filename is taken from the path provided in the `open` method after converting it to UTF-8 /// (using `to_string_lossy`). #[inline] pub fn set_content_disposition(mut self, cd: ContentDisposition) -> Self { self.content_disposition = cd; self.flags.insert(Flags::CONTENT_DISPOSITION); self } /// Disables `Content-Disposition` header. /// /// By default, the `Content-Disposition` header is sent. #[inline] pub fn disable_content_disposition(mut self) -> Self { self.flags.remove(Flags::CONTENT_DISPOSITION); self } /// Sets content encoding for this file. /// /// This prevents the `Compress` middleware from modifying the file contents and signals to /// browsers/clients how to decode it. For example, if serving a compressed HTML file (e.g., /// `index.html.gz`) then use `.set_content_encoding(ContentEncoding::Gzip)`. #[inline] pub fn set_content_encoding(mut self, enc: ContentEncoding) -> Self { self.encoding = Some(enc); self } /// Sets the size threshold that determines file read mode (sync/async). /// /// When a file is smaller than the threshold (bytes), the reader will switch from synchronous /// (blocking) file-reads to async reads to avoid blocking the main-thread when processing large /// files. /// /// Tweaking this value according to your expected usage may lead to signifiant performance /// gains (or losses in other handlers, if `size` is too high). /// /// When the `experimental-io-uring` crate feature is enabled, file reads are always async. /// /// Default is 0, meaning all files are read asynchronously. pub fn read_mode_threshold(mut self, size: u64) -> Self { self.read_mode_threshold = size; self } /// Specifies whether to return `ETag` header in response. /// /// Default is true. #[inline] pub fn use_etag(mut self, value: bool) -> Self { self.flags.set(Flags::ETAG, value); self } /// Specifies whether to return `Last-Modified` header in response. /// /// Default is true. #[inline] pub fn use_last_modified(mut self, value: bool) -> Self { self.flags.set(Flags::LAST_MD, value); self } /// Specifies whether text responses should signal a UTF-8 encoding. /// /// Default is false (but will default to true in a future version). #[inline] pub fn prefer_utf8(mut self, value: bool) -> Self { self.flags.set(Flags::PREFER_UTF8, value); self } /// Creates an `ETag` in a format is similar to Apache's. pub(crate) fn etag(&self) -> Option<header::EntityTag> { self.modified.as_ref().map(|mtime| { let ino = { #[cfg(unix)] { #[cfg(unix)] use std::os::unix::fs::MetadataExt as _; self.md.ino() } #[cfg(not(unix))] { 0 } }; let dur = mtime .duration_since(UNIX_EPOCH) .expect("modification time must be after epoch"); header::EntityTag::new_strong(format!( "{:x}:{:x}:{:x}:{:x}", ino, self.md.len(), dur.as_secs(), dur.subsec_nanos() )) }) } pub(crate) fn last_modified(&self) -> Option<header::HttpDate> { self.modified.map(|mtime| mtime.into()) } /// Creates an `HttpResponse` with file as a streaming body. pub fn into_response(self, req: &HttpRequest) -> HttpResponse<BoxBody> { if self.status_code != StatusCode::OK { let mut res = HttpResponse::build(self.status_code); let ct = if self.flags.contains(Flags::PREFER_UTF8) { equiv_utf8_text(self.content_type.clone()) } else { self.content_type }; res.insert_header((header::CONTENT_TYPE, ct.to_string())); if self.flags.contains(Flags::CONTENT_DISPOSITION) { res.insert_header(( header::CONTENT_DISPOSITION, self.content_disposition.to_string(), )); } if let Some(current_encoding) = self.encoding { res.insert_header((header::CONTENT_ENCODING, current_encoding.as_str())); } let reader = chunked::new_chunked_read(self.md.len(), 0, self.file, self.read_mode_threshold); return res.streaming(reader); } let etag = if self.flags.contains(Flags::ETAG) { self.etag() } else { None }; let last_modified = if self.flags.contains(Flags::LAST_MD) { self.last_modified() } else { None }; // check preconditions let precondition_failed = if !any_match(etag.as_ref(), req) { true } else if let (Some(ref m), Some(header::IfUnmodifiedSince(ref since))) = (last_modified, req.get_header()) { let t1: SystemTime = (*m).into(); let t2: SystemTime = (*since).into(); match (t1.duration_since(UNIX_EPOCH), t2.duration_since(UNIX_EPOCH)) { (Ok(t1), Ok(t2)) => t1.as_secs() > t2.as_secs(), _ => false, } } else { false }; // check last modified let not_modified = if !none_match(etag.as_ref(), req) { true } else if req.headers().contains_key(header::IF_NONE_MATCH) { false } else if let (Some(ref m), Some(header::IfModifiedSince(ref since))) = (last_modified, req.get_header()) { let t1: SystemTime = (*m).into(); let t2: SystemTime = (*since).into(); match (t1.duration_since(UNIX_EPOCH), t2.duration_since(UNIX_EPOCH)) { (Ok(t1), Ok(t2)) => t1.as_secs() <= t2.as_secs(), _ => false, } } else { false }; let mut res = HttpResponse::build(self.status_code); let ct = if self.flags.contains(Flags::PREFER_UTF8) { equiv_utf8_text(self.content_type.clone()) } else { self.content_type }; res.insert_header((header::CONTENT_TYPE, ct.to_string())); if self.flags.contains(Flags::CONTENT_DISPOSITION) { res.insert_header(( header::CONTENT_DISPOSITION, self.content_disposition.to_string(), )); } if let Some(current_encoding) = self.encoding { res.insert_header((header::CONTENT_ENCODING, current_encoding.as_str())); } if let Some(lm) = last_modified { res.insert_header((header::LAST_MODIFIED, lm.to_string())); } if let Some(etag) = etag { res.insert_header((header::ETAG, etag.to_string())); } res.insert_header((header::ACCEPT_RANGES, "bytes")); let mut length = self.md.len(); let mut offset = 0; // check for range header if let Some(ranges) = req.headers().get(header::RANGE) { if let Ok(ranges_header) = ranges.to_str() { if let Ok(ranges) = HttpRange::parse(ranges_header, length) { length = ranges[0].length; offset = ranges[0].start; // When a Content-Encoding header is present in a 206 partial content response // for video content, it prevents browser video players from starting playback // before loading the whole video and also prevents seeking. // // See: https://github.com/actix/actix-web/issues/2815 // // The assumption of this fix is that the video player knows to not send an // Accept-Encoding header for this request and that downstream middleware will // not attempt compression for requests without it. // // TODO: Solve question around what to do if self.encoding is set and partial // range is requested. Reject request? Ignoring self.encoding seems wrong, too. // In practice, it should not come up. if req.headers().contains_key(&header::ACCEPT_ENCODING) { // don't allow compression middleware to modify partial content res.insert_header(( header::CONTENT_ENCODING, HeaderValue::from_static("identity"), )); } res.insert_header(( header::CONTENT_RANGE, format!("bytes {}-{}/{}", offset, offset + length - 1, self.md.len()), )); } else { res.insert_header((header::CONTENT_RANGE, format!("bytes */{}", length))); return res.status(StatusCode::RANGE_NOT_SATISFIABLE).finish(); }; } else { return res.status(StatusCode::BAD_REQUEST).finish(); }; }; if precondition_failed { return res.status(StatusCode::PRECONDITION_FAILED).finish(); } else if not_modified { return res .status(StatusCode::NOT_MODIFIED) .body(body::None::new()) .map_into_boxed_body(); } let reader = chunked::new_chunked_read(length, offset, self.file, self.read_mode_threshold); if offset != 0 || length != self.md.len() { res.status(StatusCode::PARTIAL_CONTENT); } res.body(SizedStream::new(length, reader)) } } /// Returns true if `req` has no `If-Match` header or one which matches `etag`. fn any_match(etag: Option<&header::EntityTag>, req: &HttpRequest) -> bool { match req.get_header::<header::IfMatch>() { None | Some(header::IfMatch::Any) => true, Some(header::IfMatch::Items(ref items)) => { if let Some(some_etag) = etag { for item in items { if item.strong_eq(some_etag) { return true; } } } false } } } /// Returns true if `req` doesn't have an `If-None-Match` header matching `req`. fn none_match(etag: Option<&header::EntityTag>, req: &HttpRequest) -> bool { match req.get_header::<header::IfNoneMatch>() { Some(header::IfNoneMatch::Any) => false, Some(header::IfNoneMatch::Items(ref items)) => { if let Some(some_etag) = etag { for item in items { if item.weak_eq(some_etag) { return false; } } } true } None => true, } } impl Responder for NamedFile { type Body = BoxBody; fn respond_to(self, req: &HttpRequest) -> HttpResponse<Self::Body> { self.into_response(req) } } impl ServiceFactory<ServiceRequest> for NamedFile { type Response = ServiceResponse; type Error = Error; type Config = (); type Service = NamedFileService; type InitError = (); type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>; fn new_service(&self, _: ()) -> Self::Future { let service = NamedFileService { path: self.path.clone(), }; Box::pin(async move { Ok(service) }) } } #[doc(hidden)] #[derive(Debug)] pub struct NamedFileService { path: PathBuf, } impl Service<ServiceRequest> for NamedFileService { type Response = ServiceResponse; type Error = Error; type Future = LocalBoxFuture<'static, Result<Self::Response, Self::Error>>; dev::always_ready!(); fn call(&self, req: ServiceRequest) -> Self::Future { let (req, _) = req.into_parts(); let path = self.path.clone(); Box::pin(async move { let file = NamedFile::open_async(path).await?; let res = file.into_response(&req); Ok(ServiceResponse::new(req, res)) }) } } impl HttpServiceFactory for NamedFile { fn register(self, config: &mut AppService) { config.register_service( ResourceDef::root_prefix(self.path.to_string_lossy().as_ref()), None, self, None, ) } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-files/src/files.rs
actix-files/src/files.rs
use std::{ cell::RefCell, fmt, io, path::{Path, PathBuf}, rc::Rc, }; use actix_service::{boxed, IntoServiceFactory, ServiceFactory, ServiceFactoryExt}; use actix_web::{ dev::{ AppService, HttpServiceFactory, RequestHead, ResourceDef, ServiceRequest, ServiceResponse, }, error::Error, guard::Guard, http::header::DispositionType, HttpRequest, }; use futures_core::future::LocalBoxFuture; use crate::{ directory_listing, named, service::{FilesService, FilesServiceInner}, Directory, DirectoryRenderer, HttpNewService, MimeOverride, PathFilter, }; /// Static files handling service. /// /// `Files` service must be registered with `App::service()` method. /// /// # Examples /// ``` /// use actix_web::App; /// use actix_files::Files; /// /// let app = App::new() /// .service(Files::new("/static", ".")); /// ``` pub struct Files { mount_path: String, directory: PathBuf, index: Option<String>, show_index: bool, redirect_to_slash: bool, with_permanent_redirect: bool, default: Rc<RefCell<Option<Rc<HttpNewService>>>>, renderer: Rc<DirectoryRenderer>, mime_override: Option<Rc<MimeOverride>>, path_filter: Option<Rc<PathFilter>>, file_flags: named::Flags, use_guards: Option<Rc<dyn Guard>>, guards: Vec<Rc<dyn Guard>>, hidden_files: bool, read_mode_threshold: u64, } impl fmt::Debug for Files { fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { f.write_str("Files") } } impl Clone for Files { fn clone(&self) -> Self { Self { directory: self.directory.clone(), index: self.index.clone(), show_index: self.show_index, redirect_to_slash: self.redirect_to_slash, with_permanent_redirect: self.with_permanent_redirect, default: self.default.clone(), renderer: self.renderer.clone(), file_flags: self.file_flags, mount_path: self.mount_path.clone(), mime_override: self.mime_override.clone(), path_filter: self.path_filter.clone(), use_guards: self.use_guards.clone(), guards: self.guards.clone(), hidden_files: self.hidden_files, read_mode_threshold: self.read_mode_threshold, } } } impl Files { /// Create new `Files` instance for a specified base directory. /// /// # Argument Order /// The first argument (`mount_path`) is the root URL at which the static files are served. /// For example, `/assets` will serve files at `example.com/assets/...`. /// /// The second argument (`serve_from`) is the location on disk at which files are loaded. /// This can be a relative path. For example, `./` would serve files from the current /// working directory. /// /// # Implementation Notes /// If the mount path is set as the root path `/`, services registered after this one will /// be inaccessible. Register more specific handlers and services first. /// /// `Files` utilizes the existing Tokio thread-pool for blocking filesystem operations. /// The number of running threads is adjusted over time as needed, up to a maximum of 512 times /// the number of server [workers](actix_web::HttpServer::workers), by default. pub fn new<T: Into<PathBuf>>(mount_path: &str, serve_from: T) -> Files { let orig_dir = serve_from.into(); let dir = match orig_dir.canonicalize() { Ok(canon_dir) => canon_dir, Err(_) => { log::error!("Specified path is not a directory: {:?}", orig_dir); PathBuf::new() } }; Files { mount_path: mount_path.trim_end_matches('/').to_owned(), directory: dir, index: None, show_index: false, redirect_to_slash: false, with_permanent_redirect: false, default: Rc::new(RefCell::new(None)), renderer: Rc::new(directory_listing), mime_override: None, path_filter: None, file_flags: named::Flags::default(), use_guards: None, guards: Vec::new(), hidden_files: false, read_mode_threshold: 0, } } /// Show files listing for directories. /// /// By default show files listing is disabled. /// /// When used with [`Files::index_file()`], files listing is shown as a fallback /// when the index file is not found. pub fn show_files_listing(mut self) -> Self { self.show_index = true; self } /// Redirects to a slash-ended path when browsing a directory. /// /// By default never redirect. pub fn redirect_to_slash_directory(mut self) -> Self { self.redirect_to_slash = true; self } /// Redirect with permanent redirect status code (308). /// /// By default redirect with temporary redirect status code (307). pub fn with_permanent_redirect(mut self) -> Self { self.with_permanent_redirect = true; self } /// Set custom directory renderer. pub fn files_listing_renderer<F>(mut self, f: F) -> Self where for<'r, 's> F: Fn(&'r Directory, &'s HttpRequest) -> Result<ServiceResponse, io::Error> + 'static, { self.renderer = Rc::new(f); self } /// Specifies MIME override callback. pub fn mime_override<F>(mut self, f: F) -> Self where F: Fn(&mime::Name<'_>) -> DispositionType + 'static, { self.mime_override = Some(Rc::new(f)); self } /// Sets path filtering closure. /// /// The path provided to the closure is relative to `serve_from` path. /// You can safely join this path with the `serve_from` path to get the real path. /// However, the real path may not exist since the filter is called before checking path existence. /// /// When a path doesn't pass the filter, [`Files::default_handler`] is called if set, otherwise, /// `404 Not Found` is returned. /// /// # Examples /// ``` /// use std::path::Path; /// use actix_files::Files; /// /// // prevent searching subdirectories and following symlinks /// let files_service = Files::new("/", "./static").path_filter(|path, _| { /// path.components().count() == 1 /// && Path::new("./static") /// .join(path) /// .symlink_metadata() /// .map(|m| !m.file_type().is_symlink()) /// .unwrap_or(false) /// }); /// ``` pub fn path_filter<F>(mut self, f: F) -> Self where F: Fn(&Path, &RequestHead) -> bool + 'static, { self.path_filter = Some(Rc::new(f)); self } /// Set index file /// /// Shows specific index file for directories instead of /// showing files listing. /// /// If the index file is not found, files listing is shown as a fallback if /// [`Files::show_files_listing()`] is set. pub fn index_file<T: Into<String>>(mut self, index: T) -> Self { self.index = Some(index.into()); self } /// Sets the size threshold that determines file read mode (sync/async). /// /// When a file is smaller than the threshold (bytes), the reader will switch from synchronous /// (blocking) file-reads to async reads to avoid blocking the main-thread when processing large /// files. /// /// Tweaking this value according to your expected usage may lead to signifiant performance /// gains (or losses in other handlers, if `size` is too high). /// /// When the `experimental-io-uring` crate feature is enabled, file reads are always async. /// /// Default is 0, meaning all files are read asynchronously. pub fn read_mode_threshold(mut self, size: u64) -> Self { self.read_mode_threshold = size; self } /// Specifies whether to use ETag or not. /// /// Default is true. pub fn use_etag(mut self, value: bool) -> Self { self.file_flags.set(named::Flags::ETAG, value); self } /// Specifies whether to use Last-Modified or not. /// /// Default is true. pub fn use_last_modified(mut self, value: bool) -> Self { self.file_flags.set(named::Flags::LAST_MD, value); self } /// Specifies whether text responses should signal a UTF-8 encoding. /// /// Default is false (but will default to true in a future version). pub fn prefer_utf8(mut self, value: bool) -> Self { self.file_flags.set(named::Flags::PREFER_UTF8, value); self } /// Adds a routing guard. /// /// Use this to allow multiple chained file services that respond to strictly different /// properties of a request. Due to the way routing works, if a guard check returns true and the /// request starts being handled by the file service, it will not be able to back-out and try /// the next service, you will simply get a 404 (or 405) error response. /// /// To allow `POST` requests to retrieve files, see [`Files::method_guard()`]. /// /// # Examples /// ``` /// use actix_web::{guard::Header, App}; /// use actix_files::Files; /// /// App::new().service( /// Files::new("/","/my/site/files") /// .guard(Header("Host", "example.com")) /// ); /// ``` pub fn guard<G: Guard + 'static>(mut self, guard: G) -> Self { self.guards.push(Rc::new(guard)); self } /// Specifies guard to check before fetching directory listings or files. /// /// Note that this guard has no effect on routing; it's main use is to guard on the request's /// method just before serving the file, only allowing `GET` and `HEAD` requests by default. /// See [`Files::guard`] for routing guards. pub fn method_guard<G: Guard + 'static>(mut self, guard: G) -> Self { self.use_guards = Some(Rc::new(guard)); self } /// See [`Files::method_guard`]. #[doc(hidden)] #[deprecated(since = "0.6.0", note = "Renamed to `method_guard`.")] pub fn use_guards<G: Guard + 'static>(self, guard: G) -> Self { self.method_guard(guard) } /// Disable `Content-Disposition` header. /// /// By default Content-Disposition` header is enabled. pub fn disable_content_disposition(mut self) -> Self { self.file_flags.remove(named::Flags::CONTENT_DISPOSITION); self } /// Sets default handler which is used when no matched file could be found. /// /// # Examples /// Setting a fallback static file handler: /// ``` /// use actix_files::{Files, NamedFile}; /// use actix_web::dev::{ServiceRequest, ServiceResponse, fn_service}; /// /// # fn run() -> Result<(), actix_web::Error> { /// let files = Files::new("/", "./static") /// .index_file("index.html") /// .default_handler(fn_service(|req: ServiceRequest| async { /// let (req, _) = req.into_parts(); /// let file = NamedFile::open_async("./static/404.html").await?; /// let res = file.into_response(&req); /// Ok(ServiceResponse::new(req, res)) /// })); /// # Ok(()) /// # } /// ``` pub fn default_handler<F, U>(mut self, f: F) -> Self where F: IntoServiceFactory<U, ServiceRequest>, U: ServiceFactory<ServiceRequest, Config = (), Response = ServiceResponse, Error = Error> + 'static, { // create and configure default resource self.default = Rc::new(RefCell::new(Some(Rc::new(boxed::factory( f.into_factory().map_init_err(|_| ()), ))))); self } /// Enables serving hidden files and directories, allowing a leading dots in url fragments. pub fn use_hidden_files(mut self) -> Self { self.hidden_files = true; self } } impl HttpServiceFactory for Files { fn register(mut self, config: &mut AppService) { let guards = if self.guards.is_empty() { None } else { let guards = std::mem::take(&mut self.guards); Some( guards .into_iter() .map(|guard| -> Box<dyn Guard> { Box::new(guard) }) .collect::<Vec<_>>(), ) }; if self.default.borrow().is_none() { *self.default.borrow_mut() = Some(config.default_service()); } let rdef = if config.is_root() { ResourceDef::root_prefix(&self.mount_path) } else { ResourceDef::prefix(&self.mount_path) }; config.register_service(rdef, guards, self, None) } } impl ServiceFactory<ServiceRequest> for Files { type Response = ServiceResponse; type Error = Error; type Config = (); type Service = FilesService; type InitError = (); type Future = LocalBoxFuture<'static, Result<Self::Service, Self::InitError>>; fn new_service(&self, _: ()) -> Self::Future { let mut inner = FilesServiceInner { directory: self.directory.clone(), index: self.index.clone(), show_index: self.show_index, redirect_to_slash: self.redirect_to_slash, default: None, renderer: self.renderer.clone(), mime_override: self.mime_override.clone(), path_filter: self.path_filter.clone(), file_flags: self.file_flags, guards: self.use_guards.clone(), hidden_files: self.hidden_files, size_threshold: self.read_mode_threshold, with_permanent_redirect: self.with_permanent_redirect, }; if let Some(ref default) = *self.default.borrow() { let fut = default.new_service(()); Box::pin(async { match fut.await { Ok(default) => { inner.default = Some(default); Ok(FilesService(Rc::new(inner))) } Err(_) => Err(()), } }) } else { Box::pin(async move { Ok(FilesService(Rc::new(inner))) }) } } } #[cfg(test)] mod tests { use actix_web::{ http::StatusCode, test::{self, TestRequest}, App, HttpResponse, }; use super::*; #[actix_web::test] async fn custom_files_listing_renderer() { let srv = test::init_service( App::new().service( Files::new("/", "./tests") .show_files_listing() .files_listing_renderer(|dir, req| { Ok(ServiceResponse::new( req.clone(), HttpResponse::Ok().body(dir.path.to_str().unwrap().to_owned()), )) }), ), ) .await; let req = TestRequest::with_uri("/").to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::OK); let body = test::read_body(res).await; let body_str = std::str::from_utf8(&body).unwrap(); let actual_path = Path::new(&body_str); let expected_path = Path::new("actix-files/tests"); assert!( actual_path.ends_with(expected_path), "body {:?} does not end with {:?}", actual_path, expected_path ); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-files/src/encoding.rs
actix-files/src/encoding.rs
use mime::Mime; /// Transforms MIME `text/*` types into their UTF-8 equivalent, if supported. /// /// MIME types that are converted /// - application/javascript /// - text/html /// - text/css /// - text/plain /// - text/csv /// - text/tab-separated-values pub(crate) fn equiv_utf8_text(ct: Mime) -> Mime { // use (roughly) order of file-type popularity for a web server if ct == mime::APPLICATION_JAVASCRIPT { return mime::APPLICATION_JAVASCRIPT_UTF_8; } if ct == mime::TEXT_HTML { return mime::TEXT_HTML_UTF_8; } if ct == mime::TEXT_CSS { return mime::TEXT_CSS_UTF_8; } if ct == mime::TEXT_PLAIN { return mime::TEXT_PLAIN_UTF_8; } if ct == mime::TEXT_CSV { return mime::TEXT_CSV_UTF_8; } if ct == mime::TEXT_TAB_SEPARATED_VALUES { return mime::TEXT_TAB_SEPARATED_VALUES_UTF_8; } ct } #[cfg(test)] mod tests { use super::*; #[test] fn test_equiv_utf8_text() { assert_eq!(equiv_utf8_text(mime::TEXT_PLAIN), mime::TEXT_PLAIN_UTF_8); assert_eq!(equiv_utf8_text(mime::TEXT_XML), mime::TEXT_XML); assert_eq!(equiv_utf8_text(mime::IMAGE_PNG), mime::IMAGE_PNG); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-files/src/directory.rs
actix-files/src/directory.rs
use std::{ fmt::Write, fs::DirEntry, io, path::{Path, PathBuf}, }; use actix_web::{dev::ServiceResponse, HttpRequest, HttpResponse}; use percent_encoding::{utf8_percent_encode, CONTROLS}; use v_htmlescape::escape as escape_html_entity; /// A directory; responds with the generated directory listing. #[derive(Debug)] pub struct Directory { /// Base directory. pub base: PathBuf, /// Path of subdirectory to generate listing for. pub path: PathBuf, } impl Directory { /// Create a new directory pub fn new(base: PathBuf, path: PathBuf) -> Directory { Directory { base, path } } /// Is this entry visible from this directory? pub fn is_visible(&self, entry: &io::Result<DirEntry>) -> bool { if let Ok(ref entry) = *entry { if let Some(name) = entry.file_name().to_str() { if name.starts_with('.') { return false; } } if let Ok(ref md) = entry.metadata() { let ft = md.file_type(); return ft.is_dir() || ft.is_file() || ft.is_symlink(); } } false } } pub(crate) type DirectoryRenderer = dyn Fn(&Directory, &HttpRequest) -> Result<ServiceResponse, io::Error>; /// Returns percent encoded file URL path. macro_rules! encode_file_url { ($path:ident) => { utf8_percent_encode(&$path, CONTROLS) }; } /// Returns HTML entity encoded formatter. /// /// ```plain /// " => &quot; /// & => &amp; /// ' => &#x27; /// < => &lt; /// > => &gt; /// / => &#x2f; /// ``` macro_rules! encode_file_name { ($entry:ident) => { escape_html_entity(&$entry.file_name().to_string_lossy()) }; } pub(crate) fn directory_listing( dir: &Directory, req: &HttpRequest, ) -> Result<ServiceResponse, io::Error> { let index_of = format!("Index of {}", req.path()); let mut body = String::new(); let base = Path::new(req.path()); for entry in dir.path.read_dir()? { if dir.is_visible(&entry) { let entry = entry.unwrap(); let p = match entry.path().strip_prefix(&dir.path) { Ok(p) if cfg!(windows) => base.join(p).to_string_lossy().replace('\\', "/"), Ok(p) => base.join(p).to_string_lossy().into_owned(), Err(_) => continue, }; // if file is a directory, add '/' to the end of the name if let Ok(metadata) = entry.metadata() { if metadata.is_dir() { let _ = write!( body, "<li><a href=\"{}\">{}/</a></li>", encode_file_url!(p), encode_file_name!(entry), ); } else { let _ = write!( body, "<li><a href=\"{}\">{}</a></li>", encode_file_url!(p), encode_file_name!(entry), ); } } else { continue; } } } let html = format!( "<html>\ <head><title>{}</title></head>\ <body><h1>{}</h1>\ <ul>\ {}\ </ul></body>\n</html>", index_of, index_of, body ); Ok(ServiceResponse::new( req.clone(), HttpResponse::Ok() .content_type("text/html; charset=utf-8") .body(html), )) }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-files/tests/guard.rs
actix-files/tests/guard.rs
use actix_files::Files; use actix_web::{ guard::Host, http::StatusCode, test::{self, TestRequest}, App, }; use bytes::Bytes; #[actix_web::test] async fn test_guard_filter() { let srv = test::init_service( App::new() .service(Files::new("/", "./tests/fixtures/guards/first").guard(Host("first.com"))) .service(Files::new("/", "./tests/fixtures/guards/second").guard(Host("second.com"))), ) .await; let req = TestRequest::with_uri("/index.txt") .append_header(("Host", "first.com")) .to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::OK); assert_eq!(test::read_body(res).await, Bytes::from("first")); let req = TestRequest::with_uri("/index.txt") .append_header(("Host", "second.com")) .to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::OK); assert_eq!(test::read_body(res).await, Bytes::from("second")); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-files/tests/traversal.rs
actix-files/tests/traversal.rs
use actix_files::Files; use actix_web::{ http::StatusCode, test::{self, TestRequest}, App, }; #[actix_rt::test] async fn test_directory_traversal_prevention() { let srv = test::init_service(App::new().service(Files::new("/", "./tests"))).await; let req = TestRequest::with_uri("/../../../../../../../../../../../etc/passwd").to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::NOT_FOUND); let req = TestRequest::with_uri( "/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/%2e%2e/etc/passwd", ) .to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::NOT_FOUND); let req = TestRequest::with_uri("/%00/etc/passwd%00").to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::NOT_FOUND); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-files/tests/encoding.rs
actix-files/tests/encoding.rs
use actix_files::{Files, NamedFile}; use actix_web::{ http::{ header::{self, HeaderValue}, StatusCode, }, test::{self, TestRequest}, web, App, }; #[actix_web::test] async fn test_utf8_file_contents() { // use default ISO-8859-1 encoding let srv = test::init_service(App::new().service(Files::new("/", "./tests"))).await; let req = TestRequest::with_uri("/utf8.txt").to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::OK); assert_eq!( res.headers().get(header::CONTENT_TYPE), Some(&HeaderValue::from_static("text/plain; charset=utf-8")), ); // disable UTF-8 attribute let srv = test::init_service(App::new().service(Files::new("/", "./tests").prefer_utf8(false))).await; let req = TestRequest::with_uri("/utf8.txt").to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::OK); assert_eq!( res.headers().get(header::CONTENT_TYPE), Some(&HeaderValue::from_static("text/plain")), ); } #[actix_web::test] async fn partial_range_response_encoding() { let srv = test::init_service(App::new().default_service(web::to(|| async { NamedFile::open_async("./tests/test.binary").await.unwrap() }))) .await; // range request without accept-encoding returns no content-encoding header let req = TestRequest::with_uri("/") .append_header((header::RANGE, "bytes=10-20")) .to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::PARTIAL_CONTENT); assert!(!res.headers().contains_key(header::CONTENT_ENCODING)); // range request with accept-encoding returns a content-encoding header let req = TestRequest::with_uri("/") .append_header((header::RANGE, "bytes=10-20")) .append_header((header::ACCEPT_ENCODING, "identity")) .to_request(); let res = test::call_service(&srv, req).await; assert_eq!(res.status(), StatusCode::PARTIAL_CONTENT); assert_eq!( res.headers().get(header::CONTENT_ENCODING).unwrap(), "identity" ); }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-files/examples/guarded-listing.rs
actix-files/examples/guarded-listing.rs
use actix_files::Files; use actix_web::{get, guard, middleware, App, HttpServer, Responder}; const EXAMPLES_DIR: &str = concat![env!("CARGO_MANIFEST_DIR"), "/examples"]; #[get("/")] async fn index() -> impl Responder { "Hello world!" } #[actix_web::main] async fn main() -> std::io::Result<()> { env_logger::init_from_env(env_logger::Env::new().default_filter_or("info")); log::info!("starting HTTP server at http://localhost:8080"); HttpServer::new(|| { App::new() .service(index) .service( Files::new("/assets", EXAMPLES_DIR) .show_files_listing() .guard(guard::Header("show-listing", "?1")), ) .service(Files::new("/assets", EXAMPLES_DIR)) .wrap(middleware::Compress::default()) .wrap(middleware::Logger::default()) }) .bind(("127.0.0.1", 8080))? .workers(2) .run() .await }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-actors/src/lib.rs
actix-web-actors/src/lib.rs
//! Actix actors support for Actix Web. //! //! This crate is deprecated. Migrate to [`actix-ws`](https://crates.io/crates/actix-ws). //! //! # Examples //! //! ```no_run //! use actix::{Actor, StreamHandler}; //! use actix_web::{get, web, App, Error, HttpRequest, HttpResponse, HttpServer}; //! use actix_web_actors::ws; //! //! /// Define Websocket actor //! struct MyWs; //! //! impl Actor for MyWs { //! type Context = ws::WebsocketContext<Self>; //! } //! //! /// Handler for ws::Message message //! impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWs { //! fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) { //! match msg { //! Ok(ws::Message::Ping(msg)) => ctx.pong(&msg), //! Ok(ws::Message::Text(text)) => ctx.text(text), //! Ok(ws::Message::Binary(bin)) => ctx.binary(bin), //! _ => (), //! } //! } //! } //! //! #[get("/ws")] //! async fn index(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> { //! ws::start(MyWs, &req, stream) //! } //! //! #[actix_web::main] //! async fn main() -> std::io::Result<()> { //! HttpServer::new(|| App::new().service(index)) //! .bind(("127.0.0.1", 8080))? //! .run() //! .await //! } //! ``` //! //! # Documentation & Community Resources //! In addition to this API documentation, several other resources are available: //! //! * [Website & User Guide](https://actix.rs/) //! * [Documentation for `actix_web`](actix_web) //! * [Examples Repository](https://github.com/actix/examples) //! * [Community Chat on Discord](https://discord.gg/NWpN5mmg3x) //! //! To get started navigating the API docs, you may consider looking at the following pages first: //! //! * [`ws`]: This module provides actor support for WebSockets. //! //! * [`HttpContext`]: This struct provides actor support for streaming HTTP responses. //! #![doc(html_logo_url = "https://actix.rs/img/logo.png")] #![doc(html_favicon_url = "https://actix.rs/favicon.ico")] #![cfg_attr(docsrs, feature(doc_cfg))] mod context; pub mod ws; pub use self::context::HttpContext;
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-actors/src/ws.rs
actix-web-actors/src/ws.rs
//! Websocket integration. //! //! # Examples //! //! ```no_run //! use actix::{Actor, StreamHandler}; //! use actix_web::{get, web, App, Error, HttpRequest, HttpResponse, HttpServer}; //! use actix_web_actors::ws; //! //! /// Define Websocket actor //! struct MyWs; //! //! impl Actor for MyWs { //! type Context = ws::WebsocketContext<Self>; //! } //! //! /// Handler for ws::Message message //! impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWs { //! fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) { //! match msg { //! Ok(ws::Message::Ping(msg)) => ctx.pong(&msg), //! Ok(ws::Message::Text(text)) => ctx.text(text), //! Ok(ws::Message::Binary(bin)) => ctx.binary(bin), //! _ => (), //! } //! } //! } //! //! #[get("/ws")] //! async fn websocket(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> { //! ws::start(MyWs, &req, stream) //! } //! //! const MAX_FRAME_SIZE: usize = 16_384; // 16KiB //! //! #[get("/custom-ws")] //! async fn custom_websocket(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> { //! // Create a Websocket session with a specific max frame size, and protocols. //! ws::WsResponseBuilder::new(MyWs, &req, stream) //! .frame_size(MAX_FRAME_SIZE) //! .protocols(&["A", "B"]) //! .start() //! } //! //! #[actix_web::main] //! async fn main() -> std::io::Result<()> { //! HttpServer::new(|| { //! App::new() //! .service(websocket) //! .service(custom_websocket) //! }) //! .bind(("127.0.0.1", 8080))? //! .run() //! .await //! } //! ``` //! use std::{ collections::VecDeque, future::Future, io, mem, pin::Pin, task::{Context, Poll}, }; use actix::{ dev::{ AsyncContextParts, ContextFut, ContextParts, Envelope, Mailbox, StreamHandler, ToEnvelope, }, fut::ActorFuture, Actor, ActorContext, ActorState, Addr, AsyncContext, Handler, Message as ActixMessage, SpawnHandle, }; use actix_http::ws::{hash_key, Codec}; pub use actix_http::ws::{CloseCode, CloseReason, Frame, HandshakeError, Message, ProtocolError}; use actix_web::{ error::{Error, PayloadError}, http::{ header::{self, HeaderValue}, Method, StatusCode, }, HttpRequest, HttpResponse, HttpResponseBuilder, }; use bytes::{Bytes, BytesMut}; use bytestring::ByteString; use futures_core::Stream; use pin_project_lite::pin_project; use tokio::sync::oneshot; use tokio_util::codec::{Decoder as _, Encoder as _}; /// Builder for Websocket session response. /// /// # Examples /// /// ```no_run /// # use actix::{Actor, StreamHandler}; /// # use actix_web::{get, web, App, Error, HttpRequest, HttpResponse, HttpServer}; /// # use actix_web_actors::ws; /// # /// # struct MyWs; /// # /// # impl Actor for MyWs { /// # type Context = ws::WebsocketContext<Self>; /// # } /// # /// # /// Handler for ws::Message message /// # impl StreamHandler<Result<ws::Message, ws::ProtocolError>> for MyWs { /// # fn handle(&mut self, msg: Result<ws::Message, ws::ProtocolError>, ctx: &mut Self::Context) {} /// # } /// # /// #[get("/ws")] /// async fn websocket(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> { /// ws::WsResponseBuilder::new(MyWs, &req, stream).start() /// } /// /// const MAX_FRAME_SIZE: usize = 16_384; // 16KiB /// /// #[get("/custom-ws")] /// async fn custom_websocket(req: HttpRequest, stream: web::Payload) -> Result<HttpResponse, Error> { /// // Create a Websocket session with a specific max frame size, codec, and protocols. /// ws::WsResponseBuilder::new(MyWs, &req, stream) /// .codec(actix_http::ws::Codec::new()) /// // This will overwrite the codec's max frame-size /// .frame_size(MAX_FRAME_SIZE) /// .protocols(&["A", "B"]) /// .start() /// } /// # /// # #[actix_web::main] /// # async fn main() -> std::io::Result<()> { /// # HttpServer::new(|| { /// # App::new() /// # .service(websocket) /// # .service(custom_websocket) /// # }) /// # .bind(("127.0.0.1", 8080))? /// # .run() /// # .await /// # } /// ``` pub struct WsResponseBuilder<'a, A, T> where A: Actor<Context = WebsocketContext<A>> + StreamHandler<Result<Message, ProtocolError>>, T: Stream<Item = Result<Bytes, PayloadError>> + 'static, { actor: A, req: &'a HttpRequest, stream: T, codec: Option<Codec>, protocols: Option<&'a [&'a str]>, frame_size: Option<usize>, } impl<'a, A, T> WsResponseBuilder<'a, A, T> where A: Actor<Context = WebsocketContext<A>> + StreamHandler<Result<Message, ProtocolError>>, T: Stream<Item = Result<Bytes, PayloadError>> + 'static, { /// Construct a new `WsResponseBuilder` with actor, request, and payload stream. /// /// For usage example, see docs on [`WsResponseBuilder`] struct. pub fn new(actor: A, req: &'a HttpRequest, stream: T) -> Self { WsResponseBuilder { actor, req, stream, codec: None, protocols: None, frame_size: None, } } /// Set the protocols for the session. pub fn protocols(mut self, protocols: &'a [&'a str]) -> Self { self.protocols = Some(protocols); self } /// Set the max frame size for each message (in bytes). /// /// **Note**: This will override any given [`Codec`]'s max frame size. pub fn frame_size(mut self, frame_size: usize) -> Self { self.frame_size = Some(frame_size); self } /// Set the [`Codec`] for the session. If [`Self::frame_size`] is also set, the given /// [`Codec`]'s max frame size will be overridden. pub fn codec(mut self, codec: Codec) -> Self { self.codec = Some(codec); self } fn handshake_resp(&self) -> Result<HttpResponseBuilder, HandshakeError> { match self.protocols { Some(protocols) => handshake_with_protocols(self.req, protocols), None => handshake(self.req), } } fn set_frame_size(&mut self) { if let Some(frame_size) = self.frame_size { match &mut self.codec { Some(codec) => { // modify existing codec's max frame size let orig_codec = mem::take(codec); *codec = orig_codec.max_size(frame_size); } None => { // create a new codec with the given size self.codec = Some(Codec::new().max_size(frame_size)); } } } } /// Create a new Websocket context from an actor, request stream, and codec. /// /// Returns a pair, where the first item is an addr for the created actor, and the second item /// is a stream intended to be set as part of the response /// via [`HttpResponseBuilder::streaming()`]. fn create_with_codec_addr<S>( actor: A, stream: S, codec: Codec, ) -> (Addr<A>, impl Stream<Item = Result<Bytes, Error>>) where A: StreamHandler<Result<Message, ProtocolError>>, S: Stream<Item = Result<Bytes, PayloadError>> + 'static, { let mb = Mailbox::default(); let mut ctx = WebsocketContext { inner: ContextParts::new(mb.sender_producer()), messages: VecDeque::new(), }; ctx.add_stream(WsStream::new(stream, codec.clone())); let addr = ctx.address(); (addr, WebsocketContextFut::new(ctx, actor, mb, codec)) } /// Perform WebSocket handshake and start actor. /// /// `req` is an [`HttpRequest`] that should be requesting a websocket protocol change. /// `stream` should be a [`Bytes`] stream (such as `actix_web::web::Payload`) that contains a /// stream of the body request. /// /// If there is a problem with the handshake, an error is returned. /// /// If successful, consume the [`WsResponseBuilder`] and return a [`HttpResponse`] wrapped in /// a [`Result`]. pub fn start(mut self) -> Result<HttpResponse, Error> { let mut res = self.handshake_resp()?; self.set_frame_size(); match self.codec { Some(codec) => { let out_stream = WebsocketContext::with_codec(self.actor, self.stream, codec); Ok(res.streaming(out_stream)) } None => { let out_stream = WebsocketContext::create(self.actor, self.stream); Ok(res.streaming(out_stream)) } } } /// Perform WebSocket handshake and start actor. /// /// `req` is an [`HttpRequest`] that should be requesting a websocket protocol change. /// `stream` should be a [`Bytes`] stream (such as `actix_web::web::Payload`) that contains a /// stream of the body request. /// /// If there is a problem with the handshake, an error is returned. /// /// If successful, returns a pair where the first item is an address for the created actor and /// the second item is the [`HttpResponse`] that should be returned from the websocket request. pub fn start_with_addr(mut self) -> Result<(Addr<A>, HttpResponse), Error> { let mut res = self.handshake_resp()?; self.set_frame_size(); match self.codec { Some(codec) => { let (addr, out_stream) = Self::create_with_codec_addr(self.actor, self.stream, codec); Ok((addr, res.streaming(out_stream))) } None => { let (addr, out_stream) = WebsocketContext::create_with_addr(self.actor, self.stream); Ok((addr, res.streaming(out_stream))) } } } } /// Perform WebSocket handshake and start actor. /// /// To customize options, see [`WsResponseBuilder`]. pub fn start<A, T>(actor: A, req: &HttpRequest, stream: T) -> Result<HttpResponse, Error> where A: Actor<Context = WebsocketContext<A>> + StreamHandler<Result<Message, ProtocolError>>, T: Stream<Item = Result<Bytes, PayloadError>> + 'static, { let mut res = handshake(req)?; Ok(res.streaming(WebsocketContext::create(actor, stream))) } /// Perform WebSocket handshake and start actor. /// /// `req` is an HTTP Request that should be requesting a websocket protocol change. `stream` should /// be a `Bytes` stream (such as `actix_web::web::Payload`) that contains a stream of the /// body request. /// /// If there is a problem with the handshake, an error is returned. /// /// If successful, returns a pair where the first item is an address for the created actor and the /// second item is the response that should be returned from the WebSocket request. #[deprecated(since = "4.0.0", note = "Prefer `WsResponseBuilder::start_with_addr`.")] pub fn start_with_addr<A, T>( actor: A, req: &HttpRequest, stream: T, ) -> Result<(Addr<A>, HttpResponse), Error> where A: Actor<Context = WebsocketContext<A>> + StreamHandler<Result<Message, ProtocolError>>, T: Stream<Item = Result<Bytes, PayloadError>> + 'static, { let mut res = handshake(req)?; let (addr, out_stream) = WebsocketContext::create_with_addr(actor, stream); Ok((addr, res.streaming(out_stream))) } /// Do WebSocket handshake and start ws actor. /// /// `protocols` is a sequence of known protocols. #[deprecated( since = "4.0.0", note = "Prefer `WsResponseBuilder` for setting protocols." )] pub fn start_with_protocols<A, T>( actor: A, protocols: &[&str], req: &HttpRequest, stream: T, ) -> Result<HttpResponse, Error> where A: Actor<Context = WebsocketContext<A>> + StreamHandler<Result<Message, ProtocolError>>, T: Stream<Item = Result<Bytes, PayloadError>> + 'static, { let mut res = handshake_with_protocols(req, protocols)?; Ok(res.streaming(WebsocketContext::create(actor, stream))) } /// Prepare WebSocket handshake response. /// /// This function returns handshake `HttpResponse`, ready to send to peer. It does not perform /// any IO. pub fn handshake(req: &HttpRequest) -> Result<HttpResponseBuilder, HandshakeError> { handshake_with_protocols(req, &[]) } /// Prepare WebSocket handshake response. /// /// This function returns handshake `HttpResponse`, ready to send to peer. It does not perform /// any IO. /// /// `protocols` is a sequence of known protocols. On successful handshake, the returned response /// headers contain the first protocol in this list which the server also knows. pub fn handshake_with_protocols( req: &HttpRequest, protocols: &[&str], ) -> Result<HttpResponseBuilder, HandshakeError> { // WebSocket accepts only GET if *req.method() != Method::GET { return Err(HandshakeError::GetMethodRequired); } // check for "UPGRADE" to WebSocket header let has_hdr = if let Some(hdr) = req.headers().get(&header::UPGRADE) { if let Ok(s) = hdr.to_str() { s.to_ascii_lowercase().contains("websocket") } else { false } } else { false }; if !has_hdr { return Err(HandshakeError::NoWebsocketUpgrade); } // Upgrade connection if !req.head().upgrade() { return Err(HandshakeError::NoConnectionUpgrade); } // check supported version if !req.headers().contains_key(&header::SEC_WEBSOCKET_VERSION) { return Err(HandshakeError::NoVersionHeader); } let supported_ver = { if let Some(hdr) = req.headers().get(&header::SEC_WEBSOCKET_VERSION) { hdr == "13" || hdr == "8" || hdr == "7" } else { false } }; if !supported_ver { return Err(HandshakeError::UnsupportedVersion); } // check client handshake for validity if !req.headers().contains_key(&header::SEC_WEBSOCKET_KEY) { return Err(HandshakeError::BadWebsocketKey); } let key = { let key = req.headers().get(&header::SEC_WEBSOCKET_KEY).unwrap(); hash_key(key.as_ref()) }; // check requested protocols let protocol = req .headers() .get(&header::SEC_WEBSOCKET_PROTOCOL) .and_then(|req_protocols| { let req_protocols = req_protocols.to_str().ok()?; req_protocols .split(',') .map(|req_p| req_p.trim()) .find(|req_p| protocols.iter().any(|p| p == req_p)) }); let mut response = HttpResponse::build(StatusCode::SWITCHING_PROTOCOLS) .upgrade("websocket") .insert_header(( header::SEC_WEBSOCKET_ACCEPT, // key is known to be header value safe ascii HeaderValue::from_bytes(&key).unwrap(), )) .take(); if let Some(protocol) = protocol { response.insert_header((header::SEC_WEBSOCKET_PROTOCOL, protocol)); } Ok(response) } /// Execution context for `WebSockets` actors pub struct WebsocketContext<A> where A: Actor<Context = WebsocketContext<A>>, { inner: ContextParts<A>, messages: VecDeque<Option<Message>>, } impl<A> ActorContext for WebsocketContext<A> where A: Actor<Context = Self>, { fn stop(&mut self) { self.inner.stop(); } fn terminate(&mut self) { self.inner.terminate() } fn state(&self) -> ActorState { self.inner.state() } } impl<A> AsyncContext<A> for WebsocketContext<A> where A: Actor<Context = Self>, { fn spawn<F>(&mut self, fut: F) -> SpawnHandle where F: ActorFuture<A, Output = ()> + 'static, { self.inner.spawn(fut) } fn wait<F>(&mut self, fut: F) where F: ActorFuture<A, Output = ()> + 'static, { self.inner.wait(fut) } #[doc(hidden)] #[inline] fn waiting(&self) -> bool { self.inner.waiting() || self.inner.state() == ActorState::Stopping || self.inner.state() == ActorState::Stopped } fn cancel_future(&mut self, handle: SpawnHandle) -> bool { self.inner.cancel_future(handle) } #[inline] fn address(&self) -> Addr<A> { self.inner.address() } } impl<A> WebsocketContext<A> where A: Actor<Context = Self>, { /// Create a new Websocket context from a request and an actor. #[inline] pub fn create<S>(actor: A, stream: S) -> impl Stream<Item = Result<Bytes, Error>> where A: StreamHandler<Result<Message, ProtocolError>>, S: Stream<Item = Result<Bytes, PayloadError>> + 'static, { let (_, stream) = WebsocketContext::create_with_addr(actor, stream); stream } /// Create a new Websocket context from a request and an actor. /// /// Returns a pair, where the first item is an addr for the created actor, and the second item /// is a stream intended to be set as part of the response /// via [`HttpResponseBuilder::streaming()`]. pub fn create_with_addr<S>( actor: A, stream: S, ) -> (Addr<A>, impl Stream<Item = Result<Bytes, Error>>) where A: StreamHandler<Result<Message, ProtocolError>>, S: Stream<Item = Result<Bytes, PayloadError>> + 'static, { let mb = Mailbox::default(); let mut ctx = WebsocketContext { inner: ContextParts::new(mb.sender_producer()), messages: VecDeque::new(), }; ctx.add_stream(WsStream::new(stream, Codec::new())); let addr = ctx.address(); (addr, WebsocketContextFut::new(ctx, actor, mb, Codec::new())) } /// Create a new Websocket context from a request, an actor, and a codec pub fn with_codec<S>( actor: A, stream: S, codec: Codec, ) -> impl Stream<Item = Result<Bytes, Error>> where A: StreamHandler<Result<Message, ProtocolError>>, S: Stream<Item = Result<Bytes, PayloadError>> + 'static, { let mb = Mailbox::default(); let mut ctx = WebsocketContext { inner: ContextParts::new(mb.sender_producer()), messages: VecDeque::new(), }; ctx.add_stream(WsStream::new(stream, codec.clone())); WebsocketContextFut::new(ctx, actor, mb, codec) } /// Create a new Websocket context pub fn with_factory<S, F>(stream: S, f: F) -> impl Stream<Item = Result<Bytes, Error>> where F: FnOnce(&mut Self) -> A + 'static, A: StreamHandler<Result<Message, ProtocolError>>, S: Stream<Item = Result<Bytes, PayloadError>> + 'static, { let mb = Mailbox::default(); let mut ctx = WebsocketContext { inner: ContextParts::new(mb.sender_producer()), messages: VecDeque::new(), }; ctx.add_stream(WsStream::new(stream, Codec::new())); let act = f(&mut ctx); WebsocketContextFut::new(ctx, act, mb, Codec::new()) } } impl<A> WebsocketContext<A> where A: Actor<Context = Self>, { /// Write payload /// /// This is a low-level function that accepts framed messages that should /// be created using `Frame::message()`. If you want to send text or binary /// data you should prefer the `text()` or `binary()` convenience functions /// that handle the framing for you. #[inline] pub fn write_raw(&mut self, msg: Message) { self.messages.push_back(Some(msg)); } /// Send text frame #[inline] pub fn text(&mut self, text: impl Into<ByteString>) { self.write_raw(Message::Text(text.into())); } /// Send binary frame #[inline] pub fn binary(&mut self, data: impl Into<Bytes>) { self.write_raw(Message::Binary(data.into())); } /// Send ping frame #[inline] pub fn ping(&mut self, message: &[u8]) { self.write_raw(Message::Ping(Bytes::copy_from_slice(message))); } /// Send pong frame #[inline] pub fn pong(&mut self, message: &[u8]) { self.write_raw(Message::Pong(Bytes::copy_from_slice(message))); } /// Send close frame #[inline] pub fn close(&mut self, reason: Option<CloseReason>) { self.write_raw(Message::Close(reason)); } /// Handle of the running future /// /// SpawnHandle is the handle returned by `AsyncContext::spawn()` method. pub fn handle(&self) -> SpawnHandle { self.inner.curr_handle() } /// Set mailbox capacity /// /// By default mailbox capacity is 16 messages. pub fn set_mailbox_capacity(&mut self, cap: usize) { self.inner.set_mailbox_capacity(cap) } } impl<A> AsyncContextParts<A> for WebsocketContext<A> where A: Actor<Context = Self>, { fn parts(&mut self) -> &mut ContextParts<A> { &mut self.inner } } struct WebsocketContextFut<A> where A: Actor<Context = WebsocketContext<A>>, { fut: ContextFut<A, WebsocketContext<A>>, encoder: Codec, buf: BytesMut, closed: bool, } impl<A> WebsocketContextFut<A> where A: Actor<Context = WebsocketContext<A>>, { fn new(ctx: WebsocketContext<A>, act: A, mailbox: Mailbox<A>, codec: Codec) -> Self { let fut = ContextFut::new(ctx, act, mailbox); WebsocketContextFut { fut, encoder: codec, buf: BytesMut::new(), closed: false, } } } impl<A> Stream for WebsocketContextFut<A> where A: Actor<Context = WebsocketContext<A>>, { type Item = Result<Bytes, Error>; fn poll_next(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let this = self.get_mut(); if this.fut.alive() { let _ = Pin::new(&mut this.fut).poll(cx); } // encode messages while let Some(item) = this.fut.ctx().messages.pop_front() { if let Some(msg) = item { this.encoder.encode(msg, &mut this.buf)?; } else { this.closed = true; break; } } if !this.buf.is_empty() { Poll::Ready(Some(Ok(std::mem::take(&mut this.buf).freeze()))) } else if this.fut.alive() && !this.closed { Poll::Pending } else { Poll::Ready(None) } } } impl<A, M> ToEnvelope<A, M> for WebsocketContext<A> where A: Actor<Context = WebsocketContext<A>> + Handler<M>, M: ActixMessage + Send + 'static, M::Result: Send, { fn pack(msg: M, tx: Option<oneshot::Sender<M::Result>>) -> Envelope<A> { Envelope::new(msg, tx) } } pin_project! { #[derive(Debug)] struct WsStream<S> { #[pin] stream: S, decoder: Codec, buf: BytesMut, closed: bool, } } impl<S> WsStream<S> where S: Stream<Item = Result<Bytes, PayloadError>>, { fn new(stream: S, codec: Codec) -> Self { Self { stream, decoder: codec, buf: BytesMut::new(), closed: false, } } } impl<S> Stream for WsStream<S> where S: Stream<Item = Result<Bytes, PayloadError>>, { type Item = Result<Message, ProtocolError>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { let mut this = self.as_mut().project(); if !*this.closed { loop { match Pin::new(&mut this.stream).poll_next(cx) { Poll::Ready(Some(Ok(chunk))) => { this.buf.extend_from_slice(&chunk[..]); } Poll::Ready(None) => { *this.closed = true; break; } Poll::Pending => break, Poll::Ready(Some(Err(err))) => { return Poll::Ready(Some(Err(ProtocolError::Io(io::Error::other(err))))); } } } } match this.decoder.decode(this.buf)? { None => { if *this.closed { Poll::Ready(None) } else { Poll::Pending } } Some(frm) => { let msg = match frm { Frame::Text(data) => Message::Text( ByteString::try_from(data) .map_err(|err| ProtocolError::Io(io::Error::other(err)))?, ), Frame::Binary(data) => Message::Binary(data), Frame::Ping(s) => Message::Ping(s), Frame::Pong(s) => Message::Pong(s), Frame::Close(reason) => Message::Close(reason), Frame::Continuation(item) => Message::Continuation(item), }; Poll::Ready(Some(Ok(msg))) } } } } #[cfg(test)] mod tests { use actix_web::test::TestRequest; use super::*; #[test] fn test_handshake() { let req = TestRequest::default() .method(Method::POST) .to_http_request(); assert_eq!( HandshakeError::GetMethodRequired, handshake(&req).err().unwrap() ); let req = TestRequest::default().to_http_request(); assert_eq!( HandshakeError::NoWebsocketUpgrade, handshake(&req).err().unwrap() ); let req = TestRequest::default() .insert_header((header::UPGRADE, header::HeaderValue::from_static("test"))) .to_http_request(); assert_eq!( HandshakeError::NoWebsocketUpgrade, handshake(&req).err().unwrap() ); let req = TestRequest::default() .insert_header(( header::UPGRADE, header::HeaderValue::from_static("websocket"), )) .to_http_request(); assert_eq!( HandshakeError::NoConnectionUpgrade, handshake(&req).err().unwrap() ); let req = TestRequest::default() .insert_header(( header::UPGRADE, header::HeaderValue::from_static("websocket"), )) .insert_header(( header::CONNECTION, header::HeaderValue::from_static("upgrade"), )) .to_http_request(); assert_eq!( HandshakeError::NoVersionHeader, handshake(&req).err().unwrap() ); let req = TestRequest::default() .insert_header(( header::UPGRADE, header::HeaderValue::from_static("websocket"), )) .insert_header(( header::CONNECTION, header::HeaderValue::from_static("upgrade"), )) .insert_header(( header::SEC_WEBSOCKET_VERSION, header::HeaderValue::from_static("5"), )) .to_http_request(); assert_eq!( HandshakeError::UnsupportedVersion, handshake(&req).err().unwrap() ); let req = TestRequest::default() .insert_header(( header::UPGRADE, header::HeaderValue::from_static("websocket"), )) .insert_header(( header::CONNECTION, header::HeaderValue::from_static("upgrade"), )) .insert_header(( header::SEC_WEBSOCKET_VERSION, header::HeaderValue::from_static("13"), )) .to_http_request(); assert_eq!( HandshakeError::BadWebsocketKey, handshake(&req).err().unwrap() ); let req = TestRequest::default() .insert_header(( header::UPGRADE, header::HeaderValue::from_static("websocket"), )) .insert_header(( header::CONNECTION, header::HeaderValue::from_static("upgrade"), )) .insert_header(( header::SEC_WEBSOCKET_VERSION, header::HeaderValue::from_static("13"), )) .insert_header(( header::SEC_WEBSOCKET_KEY, header::HeaderValue::from_static("13"), )) .to_http_request(); let resp = handshake(&req).unwrap().finish(); assert_eq!(StatusCode::SWITCHING_PROTOCOLS, resp.status()); assert_eq!(None, resp.headers().get(&header::CONTENT_LENGTH)); assert_eq!(None, resp.headers().get(&header::TRANSFER_ENCODING)); let req = TestRequest::default() .insert_header(( header::UPGRADE, header::HeaderValue::from_static("websocket"), )) .insert_header(( header::CONNECTION, header::HeaderValue::from_static("upgrade"), )) .insert_header(( header::SEC_WEBSOCKET_VERSION, header::HeaderValue::from_static("13"), )) .insert_header(( header::SEC_WEBSOCKET_KEY, header::HeaderValue::from_static("13"), )) .insert_header(( header::SEC_WEBSOCKET_PROTOCOL, header::HeaderValue::from_static("graphql"), )) .to_http_request(); let protocols = ["graphql"]; assert_eq!( StatusCode::SWITCHING_PROTOCOLS, handshake_with_protocols(&req, &protocols) .unwrap() .finish() .status() ); assert_eq!( Some(&header::HeaderValue::from_static("graphql")), handshake_with_protocols(&req, &protocols) .unwrap() .finish() .headers() .get(&header::SEC_WEBSOCKET_PROTOCOL) ); let req = TestRequest::default() .insert_header(( header::UPGRADE, header::HeaderValue::from_static("websocket"), )) .insert_header(( header::CONNECTION, header::HeaderValue::from_static("upgrade"), )) .insert_header(( header::SEC_WEBSOCKET_VERSION, header::HeaderValue::from_static("13"), )) .insert_header(( header::SEC_WEBSOCKET_KEY, header::HeaderValue::from_static("13"), )) .insert_header(( header::SEC_WEBSOCKET_PROTOCOL, header::HeaderValue::from_static("p1, p2, p3"), )) .to_http_request(); let protocols = vec!["p3", "p2"]; assert_eq!( StatusCode::SWITCHING_PROTOCOLS, handshake_with_protocols(&req, &protocols) .unwrap() .finish() .status() ); assert_eq!( Some(&header::HeaderValue::from_static("p2")), handshake_with_protocols(&req, &protocols) .unwrap() .finish() .headers() .get(&header::SEC_WEBSOCKET_PROTOCOL) ); let req = TestRequest::default() .insert_header(( header::UPGRADE, header::HeaderValue::from_static("websocket"), )) .insert_header(( header::CONNECTION, header::HeaderValue::from_static("upgrade"), )) .insert_header(( header::SEC_WEBSOCKET_VERSION, header::HeaderValue::from_static("13"), )) .insert_header(( header::SEC_WEBSOCKET_KEY, header::HeaderValue::from_static("13"), )) .insert_header(( header::SEC_WEBSOCKET_PROTOCOL, header::HeaderValue::from_static("p1,p2,p3"), )) .to_http_request(); let protocols = vec!["p3", "p2"]; assert_eq!( StatusCode::SWITCHING_PROTOCOLS, handshake_with_protocols(&req, &protocols) .unwrap() .finish() .status() ); assert_eq!( Some(&header::HeaderValue::from_static("p2")), handshake_with_protocols(&req, &protocols) .unwrap() .finish()
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
true
actix/actix-web
https://github.com/actix/actix-web/blob/024addfc4063814ba9ddd5e0ac06992e74b98e5b/actix-web-actors/src/context.rs
actix-web-actors/src/context.rs
use std::{ collections::VecDeque, future::Future, pin::Pin, task::{Context, Poll}, }; use actix::{ dev::{AsyncContextParts, ContextFut, ContextParts, Envelope, Mailbox, ToEnvelope}, fut::ActorFuture, Actor, ActorContext, ActorState, Addr, AsyncContext, Handler, Message, SpawnHandle, }; use actix_web::error::Error; use bytes::Bytes; use futures_core::Stream; use tokio::sync::oneshot::Sender; /// Execution context for HTTP actors /// /// # Example /// /// A demonstration of [server-sent events](https://developer.mozilla.org/docs/Web/API/Server-sent_events) using actors: /// /// ```no_run /// use std::time::Duration; /// /// use actix::{Actor, AsyncContext}; /// use actix_web::{get, http::header, App, HttpResponse, HttpServer}; /// use actix_web_actors::HttpContext; /// use bytes::Bytes; /// /// struct MyActor { /// count: usize, /// } /// /// impl Actor for MyActor { /// type Context = HttpContext<Self>; /// /// fn started(&mut self, ctx: &mut Self::Context) { /// ctx.run_later(Duration::from_millis(100), Self::write); /// } /// } /// /// impl MyActor { /// fn write(&mut self, ctx: &mut HttpContext<Self>) { /// self.count += 1; /// if self.count > 3 { /// ctx.write_eof() /// } else { /// ctx.write(Bytes::from(format!("event: count\ndata: {}\n\n", self.count))); /// ctx.run_later(Duration::from_millis(100), Self::write); /// } /// } /// } /// /// #[get("/")] /// async fn index() -> HttpResponse { /// HttpResponse::Ok() /// .insert_header(header::ContentType(mime::TEXT_EVENT_STREAM)) /// .streaming(HttpContext::create(MyActor { count: 0 })) /// } /// /// #[actix_web::main] /// async fn main() -> std::io::Result<()> { /// HttpServer::new(|| App::new().service(index)) /// .bind(("127.0.0.1", 8080))? /// .run() /// .await /// } /// ``` pub struct HttpContext<A> where A: Actor<Context = HttpContext<A>>, { inner: ContextParts<A>, stream: VecDeque<Option<Bytes>>, } impl<A> ActorContext for HttpContext<A> where A: Actor<Context = Self>, { fn stop(&mut self) { self.inner.stop(); } fn terminate(&mut self) { self.inner.terminate() } fn state(&self) -> ActorState { self.inner.state() } } impl<A> AsyncContext<A> for HttpContext<A> where A: Actor<Context = Self>, { #[inline] fn spawn<F>(&mut self, fut: F) -> SpawnHandle where F: ActorFuture<A, Output = ()> + 'static, { self.inner.spawn(fut) } #[inline] fn wait<F>(&mut self, fut: F) where F: ActorFuture<A, Output = ()> + 'static, { self.inner.wait(fut) } #[doc(hidden)] #[inline] fn waiting(&self) -> bool { self.inner.waiting() || self.inner.state() == ActorState::Stopping || self.inner.state() == ActorState::Stopped } #[inline] fn cancel_future(&mut self, handle: SpawnHandle) -> bool { self.inner.cancel_future(handle) } #[inline] fn address(&self) -> Addr<A> { self.inner.address() } } impl<A> HttpContext<A> where A: Actor<Context = Self>, { #[inline] /// Create a new HTTP Context from a request and an actor pub fn create(actor: A) -> impl Stream<Item = Result<Bytes, Error>> { let mb = Mailbox::default(); let ctx = HttpContext { inner: ContextParts::new(mb.sender_producer()), stream: VecDeque::new(), }; HttpContextFut::new(ctx, actor, mb) } /// Create a new HTTP Context pub fn with_factory<F>(f: F) -> impl Stream<Item = Result<Bytes, Error>> where F: FnOnce(&mut Self) -> A + 'static, { let mb = Mailbox::default(); let mut ctx = HttpContext { inner: ContextParts::new(mb.sender_producer()), stream: VecDeque::new(), }; let act = f(&mut ctx); HttpContextFut::new(ctx, act, mb) } } impl<A> HttpContext<A> where A: Actor<Context = Self>, { /// Write payload #[inline] pub fn write(&mut self, data: Bytes) { self.stream.push_back(Some(data)); } /// Indicate end of streaming payload. Also this method calls `Self::close`. #[inline] pub fn write_eof(&mut self) { self.stream.push_back(None); } /// Handle of the running future /// /// SpawnHandle is the handle returned by `AsyncContext::spawn()` method. pub fn handle(&self) -> SpawnHandle { self.inner.curr_handle() } } impl<A> AsyncContextParts<A> for HttpContext<A> where A: Actor<Context = Self>, { fn parts(&mut self) -> &mut ContextParts<A> { &mut self.inner } } struct HttpContextFut<A> where A: Actor<Context = HttpContext<A>>, { fut: ContextFut<A, HttpContext<A>>, } impl<A> HttpContextFut<A> where A: Actor<Context = HttpContext<A>>, { fn new(ctx: HttpContext<A>, act: A, mailbox: Mailbox<A>) -> Self { let fut = ContextFut::new(ctx, act, mailbox); HttpContextFut { fut } } } impl<A> Stream for HttpContextFut<A> where A: Actor<Context = HttpContext<A>>, { type Item = Result<Bytes, Error>; fn poll_next(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll<Option<Self::Item>> { if self.fut.alive() { let _ = Pin::new(&mut self.fut).poll(cx); } // frames if let Some(data) = self.fut.ctx().stream.pop_front() { Poll::Ready(data.map(Ok)) } else if self.fut.alive() { Poll::Pending } else { Poll::Ready(None) } } } impl<A, M> ToEnvelope<A, M> for HttpContext<A> where A: Actor<Context = HttpContext<A>> + Handler<M>, M: Message + Send + 'static, M::Result: Send, { fn pack(msg: M, tx: Option<Sender<M::Result>>) -> Envelope<A> { Envelope::new(msg, tx) } } #[cfg(test)] mod tests { use std::time::Duration; use actix_web::{ http::StatusCode, test::{call_service, init_service, read_body, TestRequest}, web, App, HttpResponse, }; use super::*; struct MyActor { count: usize, } impl Actor for MyActor { type Context = HttpContext<Self>; fn started(&mut self, ctx: &mut Self::Context) { ctx.run_later(Duration::from_millis(100), Self::write); } } impl MyActor { fn write(&mut self, ctx: &mut HttpContext<Self>) { self.count += 1; if self.count > 3 { ctx.write_eof() } else { ctx.write(Bytes::from(format!("LINE-{}", self.count))); ctx.run_later(Duration::from_millis(100), Self::write); } } } #[actix_rt::test] async fn test_default_resource() { let srv = init_service(App::new().service(web::resource("/test").to(|| async { HttpResponse::Ok().streaming(HttpContext::create(MyActor { count: 0 })) }))) .await; let req = TestRequest::with_uri("/test").to_request(); let resp = call_service(&srv, req).await; assert_eq!(resp.status(), StatusCode::OK); let body = read_body(resp).await; assert_eq!(body, Bytes::from_static(b"LINE-1LINE-2LINE-3")); } }
rust
Apache-2.0
024addfc4063814ba9ddd5e0ac06992e74b98e5b
2026-01-04T15:37:59.021020Z
false