forked from torrust/torrust-tracker
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathscrape.rs
357 lines (283 loc) · 14.7 KB
/
scrape.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
//! Axum [`handlers`](axum#handlers) for the `announce` requests.
//!
//! The handlers perform the authentication and authorization of the request,
//! and resolve the client IP address.
use std::net::SocketAddr;
use std::sync::Arc;
use axum::extract::State;
use axum::response::{IntoResponse, Response};
use bittorrent_http_tracker_core::services::scrape::ScrapeService;
use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape;
use bittorrent_http_tracker_protocol::v1::responses;
use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources;
use bittorrent_tracker_core::authentication::Key;
use hyper::StatusCode;
use torrust_tracker_primitives::core::ScrapeData;
use crate::v1::extractors::authentication_key::Extract as ExtractKey;
use crate::v1::extractors::client_ip_sources::Extract as ExtractClientIpSources;
use crate::v1::extractors::scrape_request::ExtractRequest;
/// It handles the `scrape` request when the HTTP tracker is configured
/// to run in `public` mode.
#[allow(clippy::unused_async)]
pub async fn handle_without_key(
State(state): State<(Arc<ScrapeService>, SocketAddr)>,
ExtractRequest(scrape_request): ExtractRequest,
ExtractClientIpSources(client_ip_sources): ExtractClientIpSources,
) -> Response {
tracing::debug!("http scrape request: {:#?}", &scrape_request);
handle(&state.0, &scrape_request, &client_ip_sources, &state.1, None).await
}
/// It handles the `scrape` request when the HTTP tracker is configured
/// to run in `private` or `private_listed` mode.
///
/// In this case, the authentication `key` parameter is required.
#[allow(clippy::unused_async)]
pub async fn handle_with_key(
State(state): State<(Arc<ScrapeService>, SocketAddr)>,
ExtractRequest(scrape_request): ExtractRequest,
ExtractClientIpSources(client_ip_sources): ExtractClientIpSources,
ExtractKey(key): ExtractKey,
) -> Response {
tracing::debug!("http scrape request: {:#?}", &scrape_request);
handle(&state.0, &scrape_request, &client_ip_sources, &state.1, Some(key)).await
}
async fn handle(
scrape_service: &Arc<ScrapeService>,
scrape_request: &Scrape,
client_ip_sources: &ClientIpSources,
server_socket_addr: &SocketAddr,
maybe_key: Option<Key>,
) -> Response {
let scrape_data = match scrape_service
.handle_scrape(scrape_request, client_ip_sources, server_socket_addr, maybe_key)
.await
{
Ok(scrape_data) => scrape_data,
Err(error) => {
let error_response = responses::error::Error {
failure_reason: error.to_string(),
};
return (StatusCode::OK, error_response.write()).into_response();
}
};
build_response(scrape_data)
}
fn build_response(scrape_data: ScrapeData) -> Response {
let response = responses::scrape::Bencoded::from(scrape_data);
(StatusCode::OK, response.body()).into_response()
}
#[cfg(test)]
mod tests {
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::str::FromStr;
use std::sync::Arc;
use bittorrent_http_tracker_protocol::v1::requests::scrape::Scrape;
use bittorrent_http_tracker_protocol::v1::responses;
use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources;
use bittorrent_primitives::info_hash::InfoHash;
use bittorrent_tracker_core::authentication::key::repository::in_memory::InMemoryKeyRepository;
use bittorrent_tracker_core::authentication::service::AuthenticationService;
use bittorrent_tracker_core::scrape_handler::ScrapeHandler;
use bittorrent_tracker_core::torrent::repository::in_memory::InMemoryTorrentRepository;
use bittorrent_tracker_core::whitelist::authorization::WhitelistAuthorization;
use bittorrent_tracker_core::whitelist::repository::in_memory::InMemoryWhitelist;
use torrust_tracker_configuration::{Configuration, Core};
use torrust_tracker_test_helpers::configuration;
struct CoreTrackerServices {
pub core_config: Arc<Core>,
pub scrape_handler: Arc<ScrapeHandler>,
pub authentication_service: Arc<AuthenticationService>,
}
struct CoreHttpTrackerServices {
pub http_stats_event_sender: Arc<Option<Box<dyn bittorrent_http_tracker_core::event::sender::Sender>>>,
}
fn initialize_private_tracker() -> (CoreTrackerServices, CoreHttpTrackerServices) {
initialize_core_tracker_services(&configuration::ephemeral_private())
}
fn initialize_listed_tracker() -> (CoreTrackerServices, CoreHttpTrackerServices) {
initialize_core_tracker_services(&configuration::ephemeral_listed())
}
fn initialize_tracker_on_reverse_proxy() -> (CoreTrackerServices, CoreHttpTrackerServices) {
initialize_core_tracker_services(&configuration::ephemeral_with_reverse_proxy())
}
fn initialize_tracker_not_on_reverse_proxy() -> (CoreTrackerServices, CoreHttpTrackerServices) {
initialize_core_tracker_services(&configuration::ephemeral_without_reverse_proxy())
}
fn initialize_core_tracker_services(config: &Configuration) -> (CoreTrackerServices, CoreHttpTrackerServices) {
let core_config = Arc::new(config.core.clone());
let in_memory_whitelist = Arc::new(InMemoryWhitelist::default());
let whitelist_authorization = Arc::new(WhitelistAuthorization::new(&config.core, &in_memory_whitelist.clone()));
let in_memory_key_repository = Arc::new(InMemoryKeyRepository::default());
let authentication_service = Arc::new(AuthenticationService::new(&config.core, &in_memory_key_repository));
let in_memory_torrent_repository = Arc::new(InMemoryTorrentRepository::default());
let scrape_handler = Arc::new(ScrapeHandler::new(&whitelist_authorization, &in_memory_torrent_repository));
// HTTP stats
let (http_stats_event_sender, _http_stats_repository) =
bittorrent_http_tracker_core::statistics::setup::factory(config.core.tracker_usage_statistics);
let http_stats_event_sender = Arc::new(http_stats_event_sender);
(
CoreTrackerServices {
core_config,
scrape_handler,
authentication_service,
},
CoreHttpTrackerServices { http_stats_event_sender },
)
}
fn sample_scrape_request() -> Scrape {
Scrape {
info_hashes: vec!["3b245504cf5f11bbdbe1201cea6a6bf45aee1bc0".parse::<InfoHash>().unwrap()], // DevSkim: ignore DS173237
}
}
fn sample_client_ip_sources() -> ClientIpSources {
ClientIpSources {
right_most_x_forwarded_for: Some(IpAddr::from_str("203.0.113.195").unwrap()),
connection_info_socket_address: Some(SocketAddr::new(IpAddr::V4(Ipv4Addr::new(203, 0, 113, 196)), 8080)),
}
}
fn assert_error_response(error: &responses::error::Error, error_message: &str) {
assert!(
error.failure_reason.contains(error_message),
"Error response does not contain message: '{error_message}'. Error: {error:?}"
);
}
mod with_tracker_in_private_mode {
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use std::str::FromStr;
use bittorrent_http_tracker_core::services::scrape::ScrapeService;
use bittorrent_tracker_core::authentication;
use torrust_tracker_primitives::core::ScrapeData;
use super::{initialize_private_tracker, sample_client_ip_sources, sample_scrape_request};
#[tokio::test]
async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_missing() {
let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070);
let (core_tracker_services, core_http_tracker_services) = initialize_private_tracker();
let scrape_request = sample_scrape_request();
let maybe_key = None;
let scrape_service = ScrapeService::new(
core_tracker_services.core_config.clone(),
core_tracker_services.scrape_handler.clone(),
core_tracker_services.authentication_service.clone(),
core_http_tracker_services.http_stats_event_sender.clone(),
);
let scrape_data = scrape_service
.handle_scrape(&scrape_request, &sample_client_ip_sources(), &server_socket_addr, maybe_key)
.await
.unwrap();
let expected_scrape_data = ScrapeData::zeroed(&scrape_request.info_hashes);
assert_eq!(scrape_data, expected_scrape_data);
}
#[tokio::test]
async fn it_should_return_zeroed_swarm_metadata_when_the_authentication_key_is_invalid() {
let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070);
let (core_tracker_services, core_http_tracker_services) = initialize_private_tracker();
let scrape_request = sample_scrape_request();
let unregistered_key = authentication::Key::from_str("YZSl4lMZupRuOpSRC3krIKR5BPB14nrJ").unwrap();
let maybe_key = Some(unregistered_key);
let scrape_service = ScrapeService::new(
core_tracker_services.core_config.clone(),
core_tracker_services.scrape_handler.clone(),
core_tracker_services.authentication_service.clone(),
core_http_tracker_services.http_stats_event_sender.clone(),
);
let scrape_data = scrape_service
.handle_scrape(&scrape_request, &sample_client_ip_sources(), &server_socket_addr, maybe_key)
.await
.unwrap();
let expected_scrape_data = ScrapeData::zeroed(&scrape_request.info_hashes);
assert_eq!(scrape_data, expected_scrape_data);
}
}
mod with_tracker_in_listed_mode {
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use bittorrent_http_tracker_core::services::scrape::ScrapeService;
use torrust_tracker_primitives::core::ScrapeData;
use super::{initialize_listed_tracker, sample_client_ip_sources, sample_scrape_request};
#[tokio::test]
async fn it_should_return_zeroed_swarm_metadata_when_the_torrent_is_not_whitelisted() {
let (core_tracker_services, core_http_tracker_services) = initialize_listed_tracker();
let scrape_request = sample_scrape_request();
let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070);
let scrape_service = ScrapeService::new(
core_tracker_services.core_config.clone(),
core_tracker_services.scrape_handler.clone(),
core_tracker_services.authentication_service.clone(),
core_http_tracker_services.http_stats_event_sender.clone(),
);
let scrape_data = scrape_service
.handle_scrape(&scrape_request, &sample_client_ip_sources(), &server_socket_addr, None)
.await
.unwrap();
let expected_scrape_data = ScrapeData::zeroed(&scrape_request.info_hashes);
assert_eq!(scrape_data, expected_scrape_data);
}
}
mod with_tracker_on_reverse_proxy {
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use bittorrent_http_tracker_core::services::scrape::ScrapeService;
use bittorrent_http_tracker_protocol::v1::responses;
use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources;
use super::{initialize_tracker_on_reverse_proxy, sample_scrape_request};
use crate::v1::handlers::scrape::tests::assert_error_response;
#[tokio::test]
async fn it_should_fail_when_the_right_most_x_forwarded_for_header_ip_is_not_available() {
let (core_tracker_services, core_http_tracker_services) = initialize_tracker_on_reverse_proxy();
let client_ip_sources = ClientIpSources {
right_most_x_forwarded_for: None,
connection_info_socket_address: None,
};
let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070);
let scrape_service = ScrapeService::new(
core_tracker_services.core_config.clone(),
core_tracker_services.scrape_handler.clone(),
core_tracker_services.authentication_service.clone(),
core_http_tracker_services.http_stats_event_sender.clone(),
);
let response = scrape_service
.handle_scrape(&sample_scrape_request(), &client_ip_sources, &server_socket_addr, None)
.await
.unwrap_err();
let error_response = responses::error::Error {
failure_reason: response.to_string(),
};
assert_error_response(
&error_response,
"Error resolving peer IP: missing or invalid the right most X-Forwarded-For IP",
);
}
}
mod with_tracker_not_on_reverse_proxy {
use std::net::{IpAddr, Ipv4Addr, SocketAddr};
use bittorrent_http_tracker_core::services::scrape::ScrapeService;
use bittorrent_http_tracker_protocol::v1::responses;
use bittorrent_http_tracker_protocol::v1::services::peer_ip_resolver::ClientIpSources;
use super::{initialize_tracker_not_on_reverse_proxy, sample_scrape_request};
use crate::v1::handlers::scrape::tests::assert_error_response;
#[tokio::test]
async fn it_should_fail_when_the_client_ip_from_the_connection_info_is_not_available() {
let (core_tracker_services, core_http_tracker_services) = initialize_tracker_not_on_reverse_proxy();
let client_ip_sources = ClientIpSources {
right_most_x_forwarded_for: None,
connection_info_socket_address: None,
};
let server_socket_addr = SocketAddr::new(IpAddr::V4(Ipv4Addr::new(127, 0, 0, 1)), 7070);
let scrape_service = ScrapeService::new(
core_tracker_services.core_config.clone(),
core_tracker_services.scrape_handler.clone(),
core_tracker_services.authentication_service.clone(),
core_http_tracker_services.http_stats_event_sender.clone(),
);
let response = scrape_service
.handle_scrape(&sample_scrape_request(), &client_ip_sources, &server_socket_addr, None)
.await
.unwrap_err();
let error_response = responses::error::Error {
failure_reason: response.to_string(),
};
assert_error_response(
&error_response,
"Error resolving peer IP: cannot get the client IP from the connection info",
);
}
}
}