aria2-rpc 0.2.2

Remote control server for aria2-rust: JSON-RPC 2.0, XML-RPC, and WebSocket download management with 34+ methods and 7 event types
Documentation
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
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
use std::collections::HashMap;
use std::sync::Arc;
use tokio::sync::{RwLock, mpsc};
use tokio_util::sync::CancellationToken;

use super::json_rpc::{JsonRpcRequest, JsonRpcResponse};
use super::server::{AuthConfig, CorsConfig, RpcAuthMiddleware};
use super::types::{GlobalOptions, PeerInfo, StatusInfo, TaskOptions};
use super::websocket::EventPublisher;
use aria2_core::TorrentFileEntry;
use aria2_core::config::OptionRegistry;
use aria2_core::engine::command::Command;
use aria2_core::request::request_group_man::RequestGroupMan;

/// Core RPC engine that manages download tasks and handles aria2 protocol requests.
///
/// This is the main orchestrator that:
/// - Maintains task state (active downloads, stopped tasks)
/// - Routes incoming RPC requests to appropriate handlers
/// - Provides progress tracking and status queries
/// - Publishes events via WebSocket for real-time notifications
///
/// Handler implementations are in the [`handlers`](crate::handlers) module.
pub struct RpcEngine {
    /// Active download tasks keyed by GID
    pub(crate) tasks: Arc<RwLock<HashMap<String, TaskState>>>,
    /// Global configuration options
    pub(crate) global_opts: GlobalOptions,
    /// Per-task configuration options
    pub(crate) task_opts: TaskOptions,
    /// Completed/stopped task results
    pub(crate) stopped_tasks: Arc<RwLock<Vec<StatusInfo>>>,
    /// Event publisher for WebSocket notifications
    pub(crate) event_publisher: Arc<EventPublisher>,
    /// Authentication middleware for token-based RPC auth
    pub(crate) auth_middleware: RpcAuthMiddleware,
    /// Shared download group manager (for live progress queries and task tracking).
    /// When set, RPC handlers read progress directly from RequestGroupMan
    /// instead of the placeholder `tasks` map.
    pub(crate) group_man: Option<Arc<RwLock<RequestGroupMan>>>,
    /// Channel sender to submit download commands to the DownloadEngine loop.
    /// When set, `aria2.addUri` starts real downloads by sending a
    /// `DownloadCommand` through this channel.
    pub(crate) cmd_tx: Option<mpsc::UnboundedSender<Box<dyn Command>>>,
}

/// Internal state for an active download task.
///
/// Contains both static metadata (GID, URIs, options) and dynamic
/// progress fields (speeds, lengths, connections) that are updated
/// by the download engine during execution.
pub(crate) struct TaskState {
    /// Current status information with metadata
    pub(crate) status: StatusInfo,
    /// Configuration options specific to this task
    #[allow(dead_code)] // Stored for future RPC tellActive/tellStopped option reporting
    pub(crate) options: HashMap<String, serde_json::Value>,
    /// URI list for this download
    #[allow(dead_code)] // Stored for future RPC getUris option reporting
    pub(crate) uris: Vec<String>,
    /// Torrent file entries (for BitTorrent downloads)
    pub(crate) torrent_files: Option<Vec<TorrentFileEntry>>,
    // === Dynamic progress fields (updated by download engine) ===
    pub(crate) total_length: u64,
    pub(crate) completed_length: u64,
    pub(crate) upload_length: u64,
    pub(crate) download_speed: u64,
    pub(crate) upload_speed: u64,
    pub(crate) connections: u16,
    /// Peer list for BitTorrent downloads
    pub(crate) peers: Vec<PeerInfo>,
    /// Cancellation token for forceful interruption of active downloads
    pub(crate) cancel_token: Option<CancellationToken>,
}

impl TaskState {
    pub(crate) fn new(
        status: StatusInfo,
        options: HashMap<String, serde_json::Value>,
        uris: Vec<String>,
    ) -> Self {
        Self {
            status,
            options,
            uris,
            torrent_files: None,
            total_length: 0,
            completed_length: 0,
            upload_length: 0,
            download_speed: 0,
            upload_speed: 0,
            connections: 0,
            peers: vec![],
            cancel_token: Some(CancellationToken::new()),
        }
    }

    /// Update the StatusInfo snapshot from current internal state.
    ///
    /// Called before returning status to ensure all progress fields
    /// are reflected in the response.
    pub(crate) fn update_status_info(&mut self) {
        let mut status = StatusInfo::new(&self.status.gid)
            .with_status(self.status.status.clone())
            .with_total_length(self.total_length)
            .with_completed_length(self.completed_length)
            .with_upload_length(self.upload_length)
            .with_download_speed(self.download_speed)
            .with_upload_speed(self.upload_speed)
            .with_connections(self.connections)
            .with_dir(self.status.dir.clone().unwrap_or_default())
            .with_files(self.status.files.clone().unwrap_or_default());
        if let Some(ref tf) = self.torrent_files {
            status = status.with_torrent_files(tf.clone());
        }
        self.status = status;
    }

    /// Update progress fields (typically called by download engine).
    pub fn update_progress(
        &mut self,
        total: u64,
        completed: u64,
        uploaded: u64,
        dl_speed: u64,
        ul_speed: u64,
        connections: u16,
    ) {
        self.total_length = total;
        self.completed_length = completed;
        self.upload_length = uploaded;
        self.download_speed = dl_speed;
        self.upload_speed = ul_speed;
        self.connections = connections;
    }
}

impl RpcEngine {
    /// Create a new RpcEngine instance with default global options seeded
    /// from the `OptionRegistry`.
    ///
    /// The `global_opts` map is pre-populated with all registered option
    /// defaults (e.g. `file-allocation=falloc`, `secure-falloc=false`,
    /// `mmap-threshold=268435456`) so that `aria2.getGlobalOption` returns
    /// meaningful values immediately, without requiring the client to first
    /// call `aria2.changeGlobalOption`.
    pub fn new() -> Self {
        let registry = OptionRegistry::new();
        let mut defaults = HashMap::new();
        for (name, def) in registry.all() {
            // Skip deprecated and hidden options so RPC clients don't see
            // internal/legacy options via aria2.getGlobalOption.
            if def.deprecated || def.hidden {
                continue;
            }
            let json_val: serde_json::Value = serde_json::Value::from(def.default_value());
            // Skip None/Null defaults to keep the map compact
            if !json_val.is_null() {
                defaults.insert(name.clone(), json_val);
            }
        }

        Self {
            tasks: Arc::new(RwLock::new(HashMap::new())),
            global_opts: Arc::new(RwLock::new(defaults)),
            task_opts: Arc::new(RwLock::new(HashMap::new())),
            stopped_tasks: Arc::new(RwLock::new(Vec::new())),
            event_publisher: Arc::new(EventPublisher::default()),
            auth_middleware: RpcAuthMiddleware::default(),
            group_man: None,
            cmd_tx: None,
        }
    }

    /// Chainable builder method to set authentication config.
    pub fn with_auth(mut self, auth: AuthConfig) -> Self {
        if let Some(token) = &auth.token {
            self.auth_middleware = RpcAuthMiddleware::new(token);
        }
        self
    }

    /// Chainable builder method to set auth middleware directly.
    pub fn with_auth_middleware(mut self, middleware: RpcAuthMiddleware) -> Self {
        self.auth_middleware = middleware;
        self
    }

    /// Chainable builder method to set CORS config.
    pub fn with_cors(self, cors: CorsConfig) -> Self {
        let _ = cors;
        self
    }

    /// Chainable builder method to set the shared RequestGroupMan.
    /// When set, RPC handlers read live progress from the group manager
    /// and `aria2.addUri` registers downloads there.
    pub fn with_group_man(mut self, man: Arc<RwLock<RequestGroupMan>>) -> Self {
        self.group_man = Some(man);
        self
    }

    /// Chainable builder method to set the command channel sender.
    /// When set, `aria2.addUri` sends real `DownloadCommand`s to the engine.
    pub fn with_cmd_tx(mut self, tx: mpsc::UnboundedSender<Box<dyn Command>>) -> Self {
        self.cmd_tx = Some(tx);
        self
    }

    /// Chainable builder method to merge user-specified global options
    /// over the OptionRegistry defaults. User values take precedence.
    ///
    /// Null values in `user_opts` are skipped so that the corresponding
    /// default (if any) is preserved.
    ///
    /// Uses `try_write()` because the engine is freshly constructed and
    /// not yet shared across tasks, so lock contention is impossible.
    pub fn with_global_opts(self, user_opts: HashMap<String, serde_json::Value>) -> Self {
        // Scope the write guard so it is dropped before `self` is returned.
        {
            let mut defaults = self
                .global_opts
                .try_write()
                .expect("no contention on fresh engine");
            for (k, v) in user_opts {
                // Only insert non-null values; null means "use default"
                if !v.is_null() {
                    defaults.insert(k, v);
                }
            }
        }
        self
    }

    /// Get reference to the event publisher for subscribing to events.
    pub fn publisher(&self) -> &EventPublisher {
        &self.event_publisher
    }

    /// Get current number of active tasks.
    pub async fn task_count(&self) -> usize {
        self.tasks.read().await.len()
    }

    /// Update progress for a specific task (called by download engine).
    ///
    /// Returns `true` if the task was found and updated, `false` otherwise.
    #[allow(clippy::too_many_arguments)]
    pub async fn update_task_progress(
        &self,
        gid: &str,
        total: u64,
        completed: u64,
        uploaded: u64,
        dl_speed: u64,
        ul_speed: u64,
        connections: u16,
    ) -> bool {
        let mut tasks = self.tasks.write().await;
        if let Some(state) = tasks.get_mut(gid) {
            state.update_progress(total, completed, uploaded, dl_speed, ul_speed, connections);
            true
        } else {
            false
        }
    }

    /// Set torrent file entries for a BitTorrent download task.
    pub async fn set_task_torrent_files(&self, gid: &str, files: Vec<TorrentFileEntry>) -> bool {
        let mut tasks = self.tasks.write().await;
        if let Some(state) = tasks.get_mut(gid) {
            state.torrent_files = Some(files);
            true
        } else {
            false
        }
    }

    /// Set peer list for a BitTorrent download task.
    pub async fn set_task_peers(&self, gid: &str, peers: Vec<PeerInfo>) -> bool {
        let mut tasks = self.tasks.write().await;
        if let Some(state) = tasks.get_mut(gid) {
            state.peers = peers;
            true
        } else {
            false
        }
    }

    /// Main request dispatcher - routes RPC methods to their handlers.
    ///
    /// This is the central entry point for all JSON-RPC requests.
    /// It matches on the method name and delegates to the appropriate
    /// handler implementation in [rpc_handlers].
    ///
    /// Before dispatching, validates the request token against the
    /// configured `rpc-secret` (if any) via [`RpcAuthMiddleware`].
    pub async fn handle_request(&self, req: &JsonRpcRequest) -> JsonRpcResponse {
        let id = req.id.clone().unwrap_or(serde_json::Value::Null);

        // Authenticate: extract token from params and validate
        let token = req.params.get("token").and_then(|v| v.as_str());
        if let Err(auth_err) = self.auth_middleware.validate(token) {
            return auth_err.into_response(req.id.clone());
        }

        match req.method.as_str() {
            "aria2.addUri" => self
                .handle_add_uri(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.addTorrent" => self
                .handle_add_torrent(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.addMetalink" => self
                .handle_add_metalink(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.remove" => self
                .handle_remove(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.pause" => self
                .handle_pause(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.forcePause" => self
                .handle_force_pause(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.unpause" | "aria2.forceUnpause" => self
                .handle_unpause(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.tellStatus" => self
                .handle_tell_status(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.tellActive" => self
                .handle_tell_active(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.tellWaiting" => self
                .handle_tell_waiting(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.tellStopped" => self
                .handle_tell_stopped(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.getGlobalStat" => self.handle_global_stat().await,
            "aria2.getUris" => self
                .handle_get_uris(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.getFiles" => self
                .handle_get_files(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.getServers" => self
                .handle_get_servers(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.purgeDownloadResult" => self
                .handle_purge_download_result(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.removeDownloadResult" => self
                .handle_remove_download_result(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.getGlobalOption" => self.handle_get_global_option().await,
            "aria2.changeGlobalOption" => self
                .handle_change_global_option(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.getOption" => self
                .handle_get_option(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.changeOption" => self
                .handle_change_option(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.getPeers" => self
                .handle_get_peers(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.pauseAll" => self.handle_pause_all().await,
            "aria2.forcePauseAll" => self.handle_force_pause_all().await,
            "aria2.unpauseAll" => self.handle_unpause_all().await,
            "aria2.changeUri" => self
                .handle_change_uri(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.saveSession" => self
                .handle_save_session(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.changePosition" => self
                .handle_change_position(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.forceRemove" => self
                .handle_force_remove(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.shutdown" => self
                .handle_shutdown(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.forceShutdown" => self
                .handle_force_shutdown(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "aria2.getVersion" => self.handle_version(req),
            "aria2.getSessionInfo" => self.handle_session_info(req),
            "system.multicall" => self
                .handle_multicall(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "system.listMethods" => self
                .handle_list_methods(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            "system.listNotifications" => self
                .handle_list_notifications(req)
                .await
                .unwrap_or_else(|e| e.into_response(req.id.clone())),
            _ => JsonRpcResponse::error(id, -32601, format!("Method not found: {}", req.method)),
        }
    }
}

impl Default for RpcEngine {
    fn default() -> Self {
        Self::new()
    }
}

// =========================================================================
// Integration / Routing Tests
// =========================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[tokio::test]
    async fn test_engine_creation() {
        let engine = RpcEngine::new();
        assert_eq!(engine.task_count().await, 0);
    }

    #[tokio::test]
    async fn test_handle_unknown_method() {
        let engine = RpcEngine::new();
        let req = JsonRpcRequest::new("aria2.nonExistent", serde_json::json!([])).with_id(1);
        let resp = engine.handle_request(&req).await;
        assert!(resp.is_error());
        assert_eq!(resp.error.unwrap().code, -32601);
    }

    #[tokio::test]
    async fn test_handle_version() {
        let engine = RpcEngine::new();
        let req = JsonRpcRequest::new("aria2.getVersion", serde_json::json!([])).with_id(1);
        let resp = engine.handle_request(&req).await;
        assert!(resp.is_success());
    }

    #[tokio::test]
    async fn test_handle_session_info() {
        let engine = RpcEngine::new();
        let req = JsonRpcRequest::new("aria2.getSessionInfo", serde_json::json!([])).with_id(1);
        let resp = engine.handle_request(&req).await;
        assert!(resp.is_success());
    }

    #[tokio::test]
    async fn test_handle_add_uri() {
        let engine = RpcEngine::new();
        let req = JsonRpcRequest::new(
            "aria2.addUri",
            serde_json::json!(["http://example.com/file.iso"]),
        )
        .with_id(1);
        let resp = engine.handle_request(&req).await;
        assert!(resp.is_success());
        let gid: String = serde_json::from_value(resp.result.unwrap()).unwrap();
        assert_eq!(gid.len(), 16);
    }

    #[tokio::test]
    async fn test_handle_remove_nonexistent() {
        let engine = RpcEngine::new();
        let req =
            JsonRpcRequest::new("aria2.remove", serde_json::json!(["nonexistent-gid"])).with_id(1);
        let resp = engine.handle_request(&req).await;
        assert!(resp.is_error());
    }

    #[tokio::test]
    async fn test_handle_pause_and_unpause() {
        let engine = RpcEngine::new();
        let add_req =
            JsonRpcRequest::new("aria2.addUri", serde_json::json!(["http://x.com/f"])).with_id(1);
        let add_resp = engine.handle_request(&add_req).await;
        let gid: String = serde_json::from_value(add_resp.result.unwrap()).unwrap();

        let pause_req = JsonRpcRequest::new("aria2.pause", serde_json::json!([gid])).with_id(2);
        let pause_resp = engine.handle_request(&pause_req).await;
        assert!(pause_resp.is_success());

        let unpause_req = JsonRpcRequest::new("aria2.unpause", serde_json::json!([gid])).with_id(3);
        let unpause_resp = engine.handle_request(&unpause_req).await;
        assert!(unpause_resp.is_success());
    }

    #[tokio::test]
    async fn test_handle_tell_status() {
        let engine = RpcEngine::new();
        let add_req =
            JsonRpcRequest::new("aria2.addUri", serde_json::json!(["http://x.com/f"])).with_id(1);
        let add_resp = engine.handle_request(&add_req).await;
        let gid: String = serde_json::from_value(add_resp.result.unwrap()).unwrap();

        let tell_req = JsonRpcRequest::new("aria2.tellStatus", serde_json::json!([gid])).with_id(2);
        let tell_resp = engine.handle_request(&tell_req).await;
        assert!(tell_resp.is_success());
    }

    #[tokio::test]
    async fn test_handle_tell_active() {
        let engine = RpcEngine::new();
        let req = JsonRpcRequest::new("aria2.tellActive", serde_json::json!([])).with_id(1);
        let resp = engine.handle_request(&req).await;
        assert!(resp.is_success());
    }

    #[tokio::test]
    async fn test_handle_global_stat() {
        let engine = RpcEngine::new();
        let req = JsonRpcRequest::new("aria2.getGlobalStat", serde_json::json!([])).with_id(1);
        let resp = engine.handle_request(&req).await;
        assert!(resp.is_success());
    }

    #[tokio::test]
    async fn test_handle_purge_download_result() {
        let engine = RpcEngine::new();
        let req =
            JsonRpcRequest::new("aria2.purgeDownloadResult", serde_json::json!([])).with_id(1);
        let resp = engine.handle_request(&req).await;
        assert!(resp.is_success());
    }

    #[tokio::test]
    async fn test_handle_get_set_global_option() {
        let engine = RpcEngine::new();
        let get_req =
            JsonRpcRequest::new("aria2.getGlobalOption", serde_json::json!([])).with_id(1);
        let get_resp = engine.handle_request(&get_req).await;
        assert!(get_resp.is_success());

        let set_req = JsonRpcRequest::new(
            "aria2.changeGlobalOption",
            serde_json::json!([{"max-concurrent-downloads": 5}]),
        )
        .with_id(2);
        let set_resp = engine.handle_request(&set_req).await;
        assert!(set_resp.is_success());
    }

    // =========================================================================
    // Auth Integration Tests (G4 Part B)
    // =========================================================================

    #[tokio::test]
    async fn test_engine_auth_default_accepts_all() {
        // Default engine has no auth configured — all requests pass
        let engine = RpcEngine::new();
        let req = JsonRpcRequest::new("aria2.getVersion", serde_json::json!([])).with_id(1);
        let resp = engine.handle_request(&req).await;
        assert!(
            resp.is_success(),
            "Default engine should accept requests without token"
        );
    }

    #[tokio::test]
    async fn test_engine_auth_valid_token_passes() {
        let engine = RpcEngine::new().with_auth_middleware(RpcAuthMiddleware::new("my-secret"));

        // Request with correct token in params
        let req = JsonRpcRequest::new(
            "aria2.getVersion",
            serde_json::json!({"token": "my-secret"}),
        )
        .with_id(1);
        let resp = engine.handle_request(&req).await;
        assert!(resp.is_success(), "Valid token should be accepted");
    }

    #[tokio::test]
    async fn test_engine_auth_wrong_token_rejected() {
        let engine = RpcEngine::new().with_auth_middleware(RpcAuthMiddleware::new("my-secret"));

        // Request with wrong token
        let req = JsonRpcRequest::new(
            "aria2.getVersion",
            serde_json::json!({"token": "wrong-token"}),
        )
        .with_id(1);
        let resp = engine.handle_request(&req).await;
        assert!(resp.is_error(), "Wrong token should be rejected");
        assert_eq!(
            resp.error.unwrap().code,
            -32001,
            "Should return Unauthorized error code"
        );
    }

    #[tokio::test]
    async fn test_engine_auth_missing_token_rejected() {
        let engine = RpcEngine::new().with_auth_middleware(RpcAuthMiddleware::new("my-secret"));

        // Request without any token parameter
        let req = JsonRpcRequest::new("aria2.getVersion", serde_json::json!([])).with_id(1);
        let resp = engine.handle_request(&req).await;
        assert!(
            resp.is_error(),
            "Missing token should be rejected when auth is enabled"
        );
        assert_eq!(resp.error.unwrap().code, -32001);
    }

    #[tokio::test]
    async fn test_engine_auth_via_config_token() {
        // Test that AuthConfig.token flows through correctly
        let engine = RpcEngine::new().with_auth(AuthConfig::default().with_token("config-secret"));

        // Use object-style params where token is a named field
        let req = JsonRpcRequest::new(
            "aria2.getVersion",
            serde_json::json!({"token": "config-secret"}),
        )
        .with_id(1);
        let resp = engine.handle_request(&req).await;
        assert!(resp.is_success(), "Token from AuthConfig should work");
    }
}