torrust-actix 4.2.15

A rich, fast and efficient Bittorrent Tracker.
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
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
use crate::api::api_blacklists::{
    api_service_blacklist_clear,
    api_service_blacklist_delete,
    api_service_blacklist_get,
    api_service_blacklist_post,
    api_service_blacklists_delete,
    api_service_blacklists_get,
    api_service_blacklists_post
};
use crate::api::api_certificate::{
    api_service_certificate_reload,
    api_service_certificate_status
};
use crate::api::api_keys::{
    api_service_key_delete,
    api_service_key_get,
    api_service_key_post,
    api_service_keys_clear,
    api_service_keys_delete,
    api_service_keys_get,
    api_service_keys_post
};
use crate::api::api_stats::{
    api_service_prom_get,
    api_service_stats_get
};
use crate::api::api_torrents::{
    api_service_torrent_delete,
    api_service_torrent_get,
    api_service_torrent_post,
    api_service_torrents_delete,
    api_service_torrents_get,
    api_service_torrents_post
};
use crate::api::api_users::{
    api_service_user_delete,
    api_service_user_get,
    api_service_user_post,
    api_service_users_clear,
    api_service_users_delete,
    api_service_users_get,
    api_service_users_post
};
use crate::api::api_whitelists::{
    api_service_whitelist_clear,
    api_service_whitelist_delete,
    api_service_whitelist_get,
    api_service_whitelist_post,
    api_service_whitelists_delete,
    api_service_whitelists_get,
    api_service_whitelists_post
};
use crate::api::structs::api_service_data::ApiServiceData;
use crate::api::structs::query_token::QueryToken;
use crate::common::common::hex2bin;
use crate::common::structs::custom_error::CustomError;
use crate::config::structs::api_trackers_config::ApiTrackersConfig;
use crate::config::structs::configuration::Configuration;
use crate::security::security::{
    constant_time_eq,
    validate_remote_ip
};
use crate::ssl::enums::server_identifier::ServerIdentifier;
use crate::ssl::structs::dynamic_certificate_resolver::DynamicCertificateResolver;
use crate::stats::enums::stats_event::StatsEvent;
use crate::tracker::structs::info_hash::InfoHash;
use crate::tracker::structs::torrent_tracker::TorrentTracker;
use actix_cors::Cors;
use actix_web::dev::ServerHandle;
use actix_web::http::header::ContentType;
use actix_web::web::{
    BytesMut,
    Data,
    ServiceConfig
};
use actix_web::{
    http,
    web,
    App,
    HttpRequest,
    HttpResponse,
    HttpServer
};
use futures_util::StreamExt;
use log::{
    error,
    info
};
use serde_json::json;
use std::future::Future;
use std::net::{
    IpAddr,
    SocketAddr
};
use std::process::exit;
use std::str::FromStr;
use std::sync::Arc;
use std::time::Duration;
use utoipa_swagger_ui::{
    Config,
    SwaggerUi
};

/// Builds the CORS policy for the management API (any origin, common methods, `Authorization`
/// and `Content-Type` headers allowed).
pub fn api_service_cors() -> Cors
{
    Cors::default()
        .send_wildcard()
        .allowed_methods(vec!["GET", "POST", "PUT", "DELETE"])
        .allowed_headers(vec![http::header::X_FORWARDED_FOR, http::header::ACCEPT])
        .allowed_header(http::header::CONTENT_TYPE)
        .allowed_header(http::header::AUTHORIZATION)
        .max_age(1)
}

/// Returns the Actix route configuration for the management API: `/stats`, `/metrics`,
/// the `api/torrent(s)`, `api/whitelist(s)`, `api/blacklist(s)`, `api/key(s)`, `api/user(s)`
/// and `api/certificate/*` resources, plus optional Swagger UI.
pub fn api_service_routes(data: Arc<ApiServiceData>) -> Box<dyn Fn(&mut ServiceConfig) + Send + Sync>
{
    Box::new(move |cfg: &mut ServiceConfig| {
        cfg.app_data(Data::new(Arc::clone(&data)));
        cfg.default_service(web::route().to(api_service_not_found));
        cfg.service(web::resource("stats")
            .route(web::get().to(api_service_stats_get)));
        cfg.service(web::resource("metrics")
            .route(web::get().to(api_service_prom_get)));
        cfg.service(web::resource("api/torrent/{info_hash}")
            .route(web::get().to(api_service_torrent_get))
            .route(web::delete().to(api_service_torrent_delete))
        );
        cfg.service(web::resource("api/torrent/{info_hash}/{completed}")
            .route(web::post().to(api_service_torrent_post)));
        cfg.service(web::resource("api/torrents")
            .route(web::get().to(api_service_torrents_get))
            .route(web::post().to(api_service_torrents_post))
            .route(web::delete().to(api_service_torrents_delete))
        );
        cfg.service(web::resource("api/whitelist/clear")
            .route(web::delete().to(api_service_whitelist_clear))
        );
        cfg.service(web::resource("api/whitelist/{info_hash}")
            .route(web::get().to(api_service_whitelist_get))
            .route(web::post().to(api_service_whitelist_post))
            .route(web::delete().to(api_service_whitelist_delete))
        );
        cfg.service(web::resource("api/whitelists")
            .route(web::get().to(api_service_whitelists_get))
            .route(web::post().to(api_service_whitelists_post))
            .route(web::delete().to(api_service_whitelists_delete))
        );
        cfg.service(web::resource("api/blacklist/clear")
            .route(web::delete().to(api_service_blacklist_clear))
        );
        cfg.service(web::resource("api/blacklist/{info_hash}")
            .route(web::get().to(api_service_blacklist_get))
            .route(web::post().to(api_service_blacklist_post))
            .route(web::delete().to(api_service_blacklist_delete))
        );
        cfg.service(web::resource("api/blacklists")
            .route(web::get().to(api_service_blacklists_get))
            .route(web::post().to(api_service_blacklists_post))
            .route(web::delete().to(api_service_blacklists_delete))
        );
        cfg.service(web::resource("api/key/{key_hash}")
            .route(web::get().to(api_service_key_get))
            .route(web::delete().to(api_service_key_delete))
        );
        cfg.service(web::resource("api/key/{key_hash}/{timeout}")
            .route(web::post().to(api_service_key_post))
        );
        cfg.service(web::resource("api/keys")
            .route(web::get().to(api_service_keys_get))
            .route(web::post().to(api_service_keys_post))
            .route(web::delete().to(api_service_keys_delete))
        );
        cfg.service(web::resource("api/keys/clear")
            .route(web::delete().to(api_service_keys_clear))
        );
        cfg.service(web::resource("api/user/{id}")
            .route(web::get().to(api_service_user_get))
            .route(web::delete().to(api_service_user_delete))
        );
        cfg.service(web::resource("api/user/{id}/{key}/{uploaded}/{downloaded}/{completed}/{updated}/{active}")
            .route(web::post().to(api_service_user_post))
        );
        cfg.service(web::resource("api/users")
            .route(web::get().to(api_service_users_get))
            .route(web::post().to(api_service_users_post))
            .route(web::delete().to(api_service_users_delete))
        );
        cfg.service(web::resource("api/users/clear")
            .route(web::delete().to(api_service_users_clear))
        );
        cfg.service(web::resource("api/certificate/reload")
            .route(web::post().to(api_service_certificate_reload))
        );
        cfg.service(web::resource("api/certificate/status")
            .route(web::get().to(api_service_certificate_status))
        );
        if data.torrent_tracker.config.tracker_config.swagger {
            cfg.service(SwaggerUi::new("/swagger-ui/{_:.*}")
                .config(Config::new(["/api/openapi.json"])));
            cfg.service(web::resource("/api/openapi.json")
                .route(web::get().to(api_service_openapi_json))
            );
        }
    })
}

/// Starts an API listener (HTTP, or HTTPS when `ssl` is set) on `addr`.
///
/// Returns the Actix [`ServerHandle`] for shutdown plus the server future to await.
///
/// # Panics / exit
///
/// Exits the process when the address cannot be bound or the TLS material is missing.
pub async fn api_service(
    addr: SocketAddr,
    data: Arc<TorrentTracker>,
    api_server_object: ApiTrackersConfig
) -> (ServerHandle, impl Future<Output=Result<(), std::io::Error>>)
{
    let keep_alive = api_server_object.keep_alive;
    let request_timeout = api_server_object.request_timeout;
    let disconnect_timeout = api_server_object.disconnect_timeout;
    let worker_threads = api_server_object.threads as usize;
    let api_service_data = Arc::new(ApiServiceData {
        torrent_tracker: Arc::clone(&data),
        api_trackers_config: Arc::new(api_server_object.clone()),
    });
    let app_factory = move || {
        let cors = api_service_cors();
        let sentry_wrap = sentry_actix::Sentry::new();
        App::new()
            .wrap(cors)
            .wrap(sentry_wrap)
            .configure(api_service_routes(Arc::clone(&api_service_data)))
    };
    if api_server_object.ssl {
        info!("[APIS] Starting server listener with SSL on {addr}");
        if api_server_object.ssl_key.is_empty() || api_server_object.ssl_cert.is_empty() {
            error!("[APIS] No SSL key or SSL certificate given, exiting...");
            exit(1);
        }
        let server_id = ServerIdentifier::ApiServer(addr.to_string());
        if let Err(e) = data.certificate_store.load_certificate(
            server_id.clone(),
            &api_server_object.ssl_cert,
            &api_server_object.ssl_key,
        ) {
            panic!("[APIS] Failed to load SSL certificate: {e}");
        }
        let resolver = match DynamicCertificateResolver::new(
            Arc::clone(&data.certificate_store),
            server_id,
        ) {
            Ok(resolver) => Arc::new(resolver),
            Err(e) => panic!("[APIS] Failed to create certificate resolver: {e}"),
        };
        let tls_config = rustls::ServerConfig::builder()
            .with_no_client_auth()
            .with_cert_resolver(resolver);
        let server = HttpServer::new(app_factory)
            .keep_alive(Duration::from_secs(keep_alive))
            .client_request_timeout(Duration::from_secs(request_timeout))
            .client_disconnect_timeout(Duration::from_secs(disconnect_timeout))
            .workers(worker_threads)
            .bind_rustls_0_23((addr.ip(), addr.port()), tls_config)
            .unwrap_or_else(|e| {
                error!("[APIS] Unable to bind to {addr}: {e}");
                exit(1);
            })
            .disable_signals()
            .run();
        return (server.handle(), server);
    }
    info!("[API] Starting server listener on {addr}");
    let server = HttpServer::new(app_factory)
        .keep_alive(Duration::from_secs(keep_alive))
        .client_request_timeout(Duration::from_secs(request_timeout))
        .client_disconnect_timeout(Duration::from_secs(disconnect_timeout))
        .workers(worker_threads)
        .bind((addr.ip(), addr.port()))
        .unwrap_or_else(|e| {
            error!("[API] Unable to bind to {addr}: {e}");
            exit(1);
        })
        .disable_signals()
        .run();
    (server.handle(), server)
}

/// Increments the API connections-handled statistic for the request's IP family.
pub async fn api_service_stats_log(ip: IpAddr, tracker: Arc<TorrentTracker>)
{
    let event = if ip.is_ipv4() {
        StatsEvent::Tcp4ConnectionsHandled
    } else {
        StatsEvent::Tcp6ConnectionsHandled
    };
    tracker.update_stats(event, 1);
}

/// Extracts the API token from the `Authorization` header (with or without a `Bearer` prefix),
/// falling back to the legacy `?token=` query parameter.
pub fn api_extract_token(request: &HttpRequest) -> Option<String>
{
    if let Some(value) = request.headers().get(http::header::AUTHORIZATION).and_then(|h| h.to_str().ok()) {
        let token = value
            .strip_prefix("Bearer ")
            .or_else(|| value.strip_prefix("bearer "))
            .unwrap_or(value)
            .trim();
        if !token.is_empty() {
            return Some(token.to_string());
        }
    }
    web::Query::<QueryToken>::from_query(request.query_string())
        .ok()
        .and_then(|params| params.token.clone())
}

/// Validates the request's API token against the configured key using a constant-time comparison.
///
/// Returns `None` when the token is valid, or `Some(response)` with the JSON error to send.
pub async fn api_service_token(request: &HttpRequest, config: Arc<Configuration>) -> Option<HttpResponse>
{
    let token_code = match api_extract_token(request) {
        Some(token) => token,
        None => {
            return Some(HttpResponse::BadRequest().content_type(ContentType::json()).json(json!({
                "status": "missing token"
            })));
        }
    };
    if !constant_time_eq(&token_code, &config.tracker_config.api_key) {
        return Some(HttpResponse::BadRequest().content_type(ContentType::json()).json(json!({
            "status": "invalid token"
        })));
    }
    None
}

/// Determines the client IP, honouring the configured `real_ip` header when trusted proxies
/// are enabled; falls back to the socket peer address.
///
/// # Errors
///
/// Returns `Err(())` when no peer address is available.
pub async fn api_service_retrieve_remote_ip(request: &HttpRequest, data: Arc<ApiTrackersConfig>) -> Result<IpAddr, ()>
{
    let origin_ip = request.peer_addr().map(|addr| addr.ip()).ok_or(())?;
    if !data.trusted_proxies {
        return Ok(origin_ip);
    }
    request.headers()
        .get(&data.real_ip)
        .and_then(|header| header.to_str().ok())
        .and_then(|ip_str| {
            validate_remote_ip(ip_str, data.trusted_proxies).ok()?;
            IpAddr::from_str(ip_str).ok()
        })
        .map_or(Ok(origin_ip), Ok)
}

/// Resolves and validates the client IP and logs the connection statistic.
///
/// # Errors
///
/// Returns a JSON `invalid ip` response when the IP cannot be determined.
pub async fn api_validate_ip(request: &HttpRequest, data: Data<Arc<ApiServiceData>>) -> Result<IpAddr, HttpResponse>
{
    match api_service_retrieve_remote_ip(request, Arc::clone(&data.api_trackers_config)).await {
        Ok(ip) => {
            api_service_stats_log(ip, Arc::clone(&data.torrent_tracker)).await;
            Ok(ip)
        }
        Err(()) => {
            Err(HttpResponse::Ok().content_type(ContentType::json()).json(json!({
                "status": "invalid ip"
            })))
        }
    }
}

/// Catch-all handler returning a JSON `unknown request` error with HTTP 404.
pub async fn api_service_not_found(request: HttpRequest, data: Data<Arc<ApiServiceData>>) -> HttpResponse
{
    if let Some(error_return) = api_validation(&request, &data).await {
        return error_return;
    }
    HttpResponse::NotFound().content_type(ContentType::json()).json(json!({
        "status": "not found"
    }))
}

/// Increments the IPv4 or IPv6 variant of a statistics event depending on the client IP.
pub fn api_stat_update(ip: IpAddr, data: Arc<TorrentTracker>, stats_ipv4: StatsEvent, stat_ipv6: StatsEvent, count: i64)
{
    let event = if ip.is_ipv4() {
        stats_ipv4
    } else {
        stat_ipv6
    };
    data.update_stats(event, count);
}

/// Per-request guard: resolves and validates the client IP and records the API-handled
/// statistic. Token validation is done separately by [`api_service_token`].
///
/// Returns `Some(response)` with the error to send, or `None` when the request may proceed.
pub async fn api_validation(request: &HttpRequest, data: &Data<Arc<ApiServiceData>>) -> Option<HttpResponse>
{
    match api_validate_ip(request, data.clone()).await {
        Ok(ip) => {
            api_stat_update(
                ip,
                Arc::clone(&data.torrent_tracker),
                StatsEvent::Tcp4ApiHandled,
                StatsEvent::Tcp6ApiHandled,
                1
            );
            None
        }
        Err(result) => Some(result),
    }
}

/// `GET /api/openapi.json` — serves the generated OpenAPI specification for Swagger UI.
pub async fn api_service_openapi_json() -> HttpResponse
{
    let openapi_file = include_str!("../openapi.json");
    HttpResponse::Ok().content_type(ContentType::json()).body(openapi_file)
}

/// Collects a request body into memory, capped at 1 MiB.
///
/// # Errors
///
/// Returns a [`CustomError`] when the body overflows the cap or a chunk cannot be read.
pub async fn api_parse_body(mut payload: web::Payload) -> Result<BytesMut, CustomError>
{
    let mut body = BytesMut::new();
    while let Some(chunk) = payload.next().await {
        let chunk = chunk.map_err(|_| CustomError::new("chunk error"))?;

        if body.len() + chunk.len() > 1_048_576 {
            return Err(CustomError::new("chunk size exceeded"));
        }
        body.extend_from_slice(&chunk);
    }
    Ok(body)
}

/// Parses a 40-character hex string into an [`InfoHash`].
///
/// # Errors
///
/// Returns a JSON error response describing the malformed value.
pub fn parse_info_hash(info: &str) -> Result<InfoHash, HttpResponse>
{
    if info.len() != 40 {
        return Err(HttpResponse::BadRequest()
            .content_type(ContentType::json())
            .json(json!({"status": "bad info_hash"})));
    }
    match hex2bin(info.to_string()) {
        Ok(hash) => Ok(InfoHash(hash)),
        Err(_) => Err(HttpResponse::BadRequest()
            .content_type(ContentType::json())
            .json(json!({"status": "invalid info_hash"}))),
    }
}