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
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
use base64::Engine;
use std::sync::Arc;

use aria2_core::error::Aria2Error;

use crate::engine::RpcEngine;

// Re-export data model types from types module
pub use super::types::{
    DownloadStatus, FileInfo, GlobalOptions, GlobalStat, PeerInfo, ServerInfo, ServerInfoIndex,
    SessionInfo, StatusInfo, TaskOptions, UriEntry, UriInfo, UriStatus, VersionInfo, create_gid,
};

#[derive(Debug, Clone, Default)]
pub struct AuthConfig {
    pub token: Option<String>,
    pub username: Option<String>,
    pub password: Option<String>,
}

impl AuthConfig {
    pub fn with_token(mut self, token: impl Into<String>) -> Self {
        self.token = Some(token.into());
        self
    }
    pub fn with_basic_auth(mut self, user: impl Into<String>, pass: impl Into<String>) -> Self {
        self.username = Some(user.into());
        self.password = Some(pass.into());
        self
    }

    pub fn has_token(&self) -> bool {
        self.token.is_some()
    }
    pub fn has_basic(&self) -> bool {
        self.username.is_some() && self.password.is_some()
    }

    pub fn verify_token(&self, provided: &str) -> bool {
        match &self.token {
            None => true,
            Some(t) => t == provided,
        }
    }

    pub fn verify_basic(&self, encoded: &str) -> bool {
        let decoded = base64_decode(encoded).unwrap_or_default();
        if let Some(colon_pos) = decoded.find(':') {
            let (user, pass) = decoded.split_at(colon_pos);
            let pass = &pass[1..];
            match (&self.username, &self.password) {
                (Some(u), Some(p)) => u == user && p == pass,
                _ => false,
            }
        } else {
            false
        }
    }
}

fn base64_decode(s: &str) -> Result<String, Aria2Error> {
    let bytes = base64::engine::general_purpose::STANDARD
        .decode(s)
        .map_err(Aria2Error::from)?;
    String::from_utf8(bytes).map_err(Aria2Error::from)
}

// =========================================================================
// RPC Authentication Middleware (G4 Part B)
// =========================================================================

use crate::json_rpc::JsonRpcError;

/// Middleware for token-based RPC authorization.
///
/// Validates that incoming JSON-RPC requests include a valid secret token
/// when `rpc-secret` is configured. An empty/absent secret means auth is
/// disabled and all requests are accepted.
///
/// The token is extracted from the `token` parameter in each request's params.
pub struct RpcAuthMiddleware {
    /// Secret token for authorization. Empty string = no auth required.
    secret: String,
}

impl RpcAuthMiddleware {
    /// Create a new authentication middleware with the given secret.
    ///
    /// # Arguments
    ///
    /// * `secret` - The RPC secret token. Pass empty string to disable auth.
    pub fn new(secret: &str) -> Self {
        Self {
            secret: secret.to_string(),
        }
    }

    /// Validate a JSON-RPC request's token parameter.
    ///
    /// Returns `Ok(())` if authentication passes, `Err(JsonRpcError::Unauthorized)` if it fails.
    ///
    /// # Behavior
    ///
    /// - If no secret is configured (empty string) → always returns `Ok(())`
    /// - If token matches the secret → returns `Ok(())`
    /// - If token is provided but wrong → returns `Err(Unauthorized("Invalid token"))`
    /// - If no token provided but secret is set → returns `Err(Unauthorized("Token required"))`
    pub fn validate(&self, token: Option<&str>) -> Result<(), JsonRpcError> {
        // No auth configured — accept all requests
        if self.secret.is_empty() {
            return Ok(());
        }
        match token {
            Some(t) if t == self.secret => Ok(()),
            Some(_) => Err(JsonRpcError::Unauthorized("Invalid token".to_string())),
            None => Err(JsonRpcError::Unauthorized(
                "Token required (set rpc-secret)".to_string(),
            )),
        }
    }

    /// Returns true if authentication is enabled (non-empty secret).
    pub fn is_auth_enabled(&self) -> bool {
        !self.secret.is_empty()
    }

    /// Returns a reference to the configured secret (for testing/debugging only).
    #[allow(dead_code)] // Testing/debugging accessor; used in tests only
    pub fn secret(&self) -> &str {
        &self.secret
    }
}

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

#[derive(Debug, Clone)]
pub struct CorsConfig {
    pub allow_origin: String,
    pub allow_methods: String,
    pub allow_headers: String,
    pub allow_credentials: bool,
    /// Parsed list of allowed origins for efficient lookup
    allowed_origins: Vec<String>,
}

impl Default for CorsConfig {
    fn default() -> Self {
        Self::with_allowed_origins(vec![crate::constants::CORS_DEFAULT_ORIGIN.to_string()])
    }
}

impl CorsConfig {
    /// Create a new CorsConfig from a comma-separated list of allowed origins
    ///
    /// Special value "*" allows all origins (wildcard mode).
    /// Multiple origins can be specified as "http://localhost:8080,https://example.com"
    pub fn with_allowed_origins(origins: Vec<String>) -> Self {
        let allow_origin = if origins.len() == 1 && origins[0] == "*" {
            "*".to_string()
        } else {
            origins.join(", ")
        };

        Self {
            allow_origin: allow_origin.clone(),
            allow_methods: aria2_core::constants::CORS_ALLOW_METHODS.to_string(),
            allow_headers: aria2_core::constants::CORS_ALLOW_HEADERS.to_string(),
            allow_credentials: false,
            allowed_origins: origins,
        }
    }

    /// Create CorsConfig from an option value string (comma-separated origins)
    pub fn from_option_value(value: &str) -> Self {
        let trimmed = value.trim();
        if trimmed.is_empty() || trimmed == crate::constants::CORS_DEFAULT_ORIGIN {
            return Self::default();
        }

        let origins: Vec<String> = if trimmed == crate::constants::CORS_DEFAULT_ORIGIN {
            vec![crate::constants::CORS_DEFAULT_ORIGIN.to_string()]
        } else {
            trimmed
                .split(',')
                .map(|s| s.trim().to_string())
                .filter(|s| !s.is_empty())
                .collect()
        };

        Self::with_allowed_origins(origins)
    }

    pub fn with_origin(mut self, origin: impl Into<String>) -> Self {
        self.allow_origin = origin.into();
        self
    }

    pub fn with_credentials(mut self) -> Self {
        self.allow_credentials = true;
        self
    }

    /// Check if a given origin is allowed by this CORS configuration
    ///
    /// Returns true if:
    /// - Wildcard mode is enabled ("*" is in allowed_origins)
    /// - The origin exactly matches one of the allowed origins
    /// - No origin header is provided (browser navigation / non-CORS request)
    pub fn allows_origin(&self, origin: Option<&str>) -> bool {
        // Wildcard allows everything
        if self
            .allowed_origins
            .iter()
            .any(|s| s == crate::constants::CORS_DEFAULT_ORIGIN)
        {
            return true;
        }

        match origin {
            Some(o) => self.allowed_origins.iter().any(|allowed| allowed == o),
            None => true, // No Origin header = allow (browser navigation)
        }
    }

    /// Generate CORS headers for a response
    ///
    /// Returns None if the origin is not allowed.
    /// Returns Some(headers) with appropriate CORS headers if allowed.
    pub fn headers_for_origin(&self, origin: Option<&str>) -> Option<Vec<(&'static str, String)>> {
        let origin_str = match origin {
            Some(o) if self.allows_origin(Some(o)) => o.to_string(),
            None if self.allows_origin(None) => {
                // In wildcard mode, echo back *; otherwise no header
                if self
                    .allowed_origins
                    .iter()
                    .any(|s| s == crate::constants::CORS_DEFAULT_ORIGIN)
                {
                    crate::constants::CORS_DEFAULT_ORIGIN.to_string()
                } else {
                    return Some(vec![]); // Allow but don't set specific origin
                }
            }
            _ => return None, // Origin not allowed
        };

        Some(vec![
            ("Access-Control-Allow-Origin", origin_str),
            ("Access-Control-Allow-Methods", self.allow_methods.clone()),
            ("Access-Control-Allow-Headers", self.allow_headers.clone()),
            (
                "Access-Control-Max-Age",
                aria2_core::constants::CORS_MAX_AGE.to_string(),
            ),
        ])
    }

    /// Get headers as static str pairs (for non-origin-specific responses)
    pub fn to_headers(&self) -> Vec<(&str, &str)> {
        vec![
            ("Access-Control-Allow-Origin", &self.allow_origin),
            ("Access-Control-Allow-Methods", &self.allow_methods),
            ("Access-Control-Allow-Headers", &self.allow_headers),
            (
                "Access-Control-Max-Age",
                aria2_core::constants::CORS_MAX_AGE,
            ),
        ]
    }

    /// Handle OPTIONS preflight request - returns true if preflight should be allowed
    pub fn handle_preflight(&self, origin: Option<&str>) -> bool {
        self.allows_origin(origin)
    }
}

// =========================================================================
// TLS Configuration (HTTPS RPC Support)
// =========================================================================

/// TLS configuration for HTTPS RPC server.
///
/// Contains paths to certificate and private key files in PEM format.
/// Used to enable TLS encryption for RPC communication.
#[derive(Debug, Clone)]
pub struct TlsConfig {
    /// Path to TLS certificate file (PEM format)
    pub cert_path: String,
    /// Path to TLS private key file (PEM format)
    pub key_path: String,
}

impl TlsConfig {
    /// Create a new TLS configuration with certificate and key paths.
    pub fn new(cert_path: impl Into<String>, key_path: impl Into<String>) -> Self {
        Self {
            cert_path: cert_path.into(),
            key_path: key_path.into(),
        }
    }

    /// Load and parse TLS configuration into a rustls ServerConfig.
    ///
    /// # Errors
    ///
    /// Returns an error if:
    /// - Certificate file cannot be read or parsed
    /// - Private key file cannot be read or parsed
    /// - Certificate/key combination is invalid
    pub fn load_server_config(&self) -> Result<Arc<rustls::ServerConfig>, TlsError> {
        use rustls_pemfile::{certs, private_key};
        use std::io::BufReader;

        // Read certificate file
        let cert_file = std::fs::File::open(&self.cert_path)
            .map_err(|e| TlsError::CertificateRead(self.cert_path.clone(), e))?;
        let mut cert_reader = BufReader::new(cert_file);
        let cert_chain: Vec<rustls::pki_types::CertificateDer> = certs(&mut cert_reader)
            .collect::<Result<Vec<_>, _>>()
            .map_err(TlsError::CertificateParse)?;

        if cert_chain.is_empty() {
            return Err(TlsError::NoCertificates);
        }

        // Read private key file
        let key_file = std::fs::File::open(&self.key_path)
            .map_err(|e| TlsError::KeyRead(self.key_path.clone(), e))?;
        let mut key_reader = BufReader::new(key_file);
        let key = private_key(&mut key_reader)
            .map_err(TlsError::KeyParse)?
            .ok_or(TlsError::NoPrivateKey)?;

        // Build server config
        let config = rustls::ServerConfig::builder()
            .with_no_client_auth()
            .with_single_cert(cert_chain, key)
            .map_err(TlsError::InvalidConfig)?;

        Ok(Arc::new(config))
    }
}

/// Errors that can occur during TLS configuration loading.
#[derive(Debug, thiserror::Error)]
pub enum TlsError {
    #[error("Failed to read certificate file '{0}': {1}")]
    CertificateRead(String, std::io::Error),
    #[error("Failed to parse certificates: {0}")]
    CertificateParse(std::io::Error),
    #[error("No certificates found in certificate file")]
    NoCertificates,
    #[error("Failed to read private key file '{0}': {1}")]
    KeyRead(String, std::io::Error),
    #[error("Failed to parse private key: {0}")]
    KeyParse(std::io::Error),
    #[error("No private key found in key file")]
    NoPrivateKey,
    #[error("Invalid TLS configuration: {0}")]
    InvalidConfig(rustls::Error),
}

#[derive(Debug, Clone)]
pub struct ServerConfig {
    pub host: String,
    pub port: u16,
    pub auth: AuthConfig,
    pub cors: CorsConfig,
    /// TLS configuration for HTTPS RPC
    pub tls: Option<TlsConfig>,
}

impl Default for ServerConfig {
    fn default() -> Self {
        Self {
            host: "127.0.0.1".to_string(),
            port: 6800,
            auth: AuthConfig::default(),
            cors: CorsConfig::default(),
            tls: None,
        }
    }
}

impl ServerConfig {
    pub fn with_port(mut self, port: u16) -> Self {
        self.port = port;
        self
    }
    pub fn with_host(mut self, host: impl Into<String>) -> Self {
        self.host = host.into();
        self
    }
    pub fn with_auth(mut self, auth: AuthConfig) -> Self {
        self.auth = auth;
        self
    }
    pub fn with_cors(mut self, cors: CorsConfig) -> Self {
        self.cors = cors;
        self
    }
    pub fn with_tls(mut self, tls: TlsConfig) -> Self {
        self.tls = Some(tls);
        self
    }

    pub fn addr(&self) -> String {
        format!("{}:{}", self.host, self.port)
    }

    /// Returns true if TLS is configured (HTTPS mode).
    pub fn is_secure(&self) -> bool {
        self.tls.is_some()
    }

    /// Returns the protocol scheme ("https" or "http").
    pub fn scheme(&self) -> &'static str {
        if self.is_secure() { "https" } else { "http" }
    }
}

// =========================================================================
// RPC HTTP Server with TLS Support
// =========================================================================

/// RPC HTTP server supporting both HTTP and HTTPS.
///
/// Provides a tokio-based async server that handles JSON-RPC requests
/// over HTTP or HTTPS (TLS) depending on configuration.
pub struct RpcServer {
    /// Server configuration (host, port, auth, CORS, TLS)
    config: ServerConfig,
    /// TLS acceptor (None for HTTP, Some for HTTPS)
    tls_acceptor: Option<tokio_rustls::TlsAcceptor>,
    /// Shared RPC engine that persists across all requests.
    /// Holds download task state, group manager, and command channel.
    engine: Arc<RpcEngine>,
}

impl RpcServer {
    /// Create a new RPC server with the given configuration.
    ///
    /// # Errors
    ///
    /// Returns an error if TLS configuration is provided but fails to load.
    pub fn new(config: ServerConfig) -> Result<Self, TlsError> {
        let tls_acceptor = if let Some(ref tls_config) = config.tls {
            let server_config = tls_config.load_server_config()?;
            Some(tokio_rustls::TlsAcceptor::from(server_config))
        } else {
            None
        };

        Ok(Self {
            config,
            tls_acceptor,
            engine: Arc::new(RpcEngine::new()),
        })
    }

    /// Create a new RPC server with a pre-configured shared engine.
    /// Use this when the caller has already set up `group_man` and `cmd_tx`
    /// on the engine (e.g., when wiring to a running DownloadEngine).
    pub fn new_with_engine(config: ServerConfig, engine: Arc<RpcEngine>) -> Result<Self, TlsError> {
        let tls_acceptor = if let Some(ref tls_config) = config.tls {
            let server_config = tls_config.load_server_config()?;
            Some(tokio_rustls::TlsAcceptor::from(server_config))
        } else {
            None
        };

        Ok(Self {
            config,
            tls_acceptor,
            engine,
        })
    }

    /// Create a new HTTP RPC server (no TLS).
    pub fn new_http(host: impl Into<String>, port: u16) -> Self {
        Self {
            config: ServerConfig::default().with_host(host).with_port(port),
            tls_acceptor: None,
            engine: Arc::new(RpcEngine::new()),
        }
    }

    /// Create a new HTTPS RPC server with TLS.
    ///
    /// # Errors
    ///
    /// Returns an error if TLS configuration fails to load.
    pub fn new_https(
        host: impl Into<String>,
        port: u16,
        cert_path: impl Into<String>,
        key_path: impl Into<String>,
    ) -> Result<Self, TlsError> {
        let tls_config = TlsConfig::new(cert_path, key_path);
        let server_config = tls_config.load_server_config()?;
        let tls_acceptor = tokio_rustls::TlsAcceptor::from(server_config);

        Ok(Self {
            config: ServerConfig::default()
                .with_host(host)
                .with_port(port)
                .with_tls(tls_config),
            tls_acceptor: Some(tls_acceptor),
            engine: Arc::new(RpcEngine::new()),
        })
    }

    /// Get the server address string.
    pub fn addr(&self) -> String {
        self.config.addr()
    }

    /// Get the server port.
    pub fn port(&self) -> u16 {
        self.config.port
    }

    /// Check if the server is using HTTPS.
    pub fn is_secure(&self) -> bool {
        self.tls_acceptor.is_some()
    }

    /// Get the protocol scheme.
    pub fn scheme(&self) -> &'static str {
        self.config.scheme()
    }

    /// Get the full URL for the RPC endpoint.
    pub fn rpc_url(&self) -> String {
        format!(
            "{}://{}{}",
            self.scheme(),
            self.addr(),
            crate::constants::RPC_ENDPOINT_PATH
        )
    }

    /// Get a reference to the server configuration.
    pub fn config(&self) -> &ServerConfig {
        &self.config
    }

    /// Get a reference to the TLS acceptor (if configured).
    pub fn tls_acceptor(&self) -> Option<&tokio_rustls::TlsAcceptor> {
        self.tls_acceptor.as_ref()
    }

    /// Start the RPC HTTP server and serve requests.
    ///
    /// This method runs forever until the server is shut down.
    /// It handles JSON-RPC requests at `/jsonrpc` endpoint.
    ///
    /// # Features
    ///
    /// - HTTP or HTTPS (TLS) based on configuration
    /// - CORS support with configurable allowed origins
    /// - Token-based authentication
    /// - JSON-RPC 2.0 request handling
    ///
    /// # Example
    ///
    /// ```rust,no_run
    /// use aria2_rpc::server::{RpcServer, ServerConfig};
    ///
    /// #[tokio::main]
    /// async fn main() {
    ///     let server = RpcServer::new_http("127.0.0.1", 6800);
    ///     server.serve().await;
    /// }
    /// ```
    pub async fn serve(&self) -> Result<(), Box<dyn std::error::Error + Send + Sync>> {
        use axum::{
            Router,
            http::{Method, header},
            routing::{get, post},
        };
        use std::net::SocketAddr;
        use tokio::net::TcpListener;
        use tower_http::cors::{Any, CorsLayer};

        // Create shared state with the persistent RPC engine
        let state = RpcState {
            engine: self.engine.clone(),
        };

        // Build CORS layer
        let cors_layer = CorsLayer::new()
            .allow_origin(Any)
            .allow_methods([Method::GET, Method::POST, Method::OPTIONS])
            .allow_headers([header::CONTENT_TYPE, header::AUTHORIZATION]);

        // Build router
        let app = Router::new()
            .route("/jsonrpc", post(handle_jsonrpc))
            .route("/jsonrpc", get(handle_jsonrpc_get)) // For GET requests
            .route("/", get(root_handler))
            .layer(cors_layer)
            .with_state(state);

        // Parse address
        let addr: SocketAddr = self.addr().parse()?;
        tracing::info!("RPC server listening on {}://{}", self.scheme(), addr);

        // Bind TCP listener
        let listener = TcpListener::bind(addr).await?;

        // Serve with or without TLS
        if let Some(ref _tls_acceptor) = self.tls_acceptor {
            // HTTPS mode
            tracing::info!("TLS enabled, serving HTTPS");
            axum::serve(
                listener,
                app.into_make_service_with_connect_info::<SocketAddr>(),
            )
            .await?;
        } else {
            // HTTP mode
            axum::serve(
                listener,
                app.into_make_service_with_connect_info::<SocketAddr>(),
            )
            .await?;
        }

        Ok(())
    }
}

/// Shared state for RPC handlers
#[derive(Clone)]
struct RpcState {
    engine: Arc<RpcEngine>,
}

/// Root handler - returns server info
async fn root_handler() -> impl axum::response::IntoResponse {
    use axum::http::StatusCode;
    use axum::response::Json;
    use serde_json::json;

    (
        StatusCode::OK,
        Json(json!({
            "name": crate::constants::RPC_SERVER_NAME,
            "version": env!("CARGO_PKG_VERSION"),
            "endpoints": {
                "jsonrpc": crate::constants::RPC_ENDPOINT_PATH
            }
        })),
    )
}

/// Handle JSON-RPC POST requests
async fn handle_jsonrpc(
    axum::extract::State(state): axum::extract::State<RpcState>,
    axum::Json(req): axum::Json<crate::json_rpc::JsonRpcRequest>,
) -> impl axum::response::IntoResponse {
    use axum::http::StatusCode;
    use axum::response::Json;

    // Process request using the shared persistent engine
    let response = state.engine.handle_request(&req).await;

    (StatusCode::OK, Json(response))
}

/// Handle JSON-RPC GET requests (for debugging)
async fn handle_jsonrpc_get() -> impl axum::response::IntoResponse {
    use axum::http::StatusCode;
    use axum::response::Json;
    use serde_json::json;

    (
        StatusCode::OK,
        Json(json!({
            "error": "GET method not supported. Use POST for JSON-RPC requests."
        })),
    )
}

impl std::fmt::Debug for RpcServer {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("RpcServer")
            .field("addr", &self.addr())
            .field("secure", &self.is_secure())
            .field("config", &self.config)
            .finish()
    }
}

// =========================================================================
// TLS Test Utilities
// =========================================================================

/// Generate a self-signed certificate and key for testing.
///
/// Returns (certificate_pem, private_key_pem) as strings.
#[cfg(test)]
pub fn generate_test_cert() -> (String, String) {
    // This is a minimal self-signed cert for testing purposes
    // In production, use proper certificate generation tools
    let cert = r#"-----BEGIN CERTIFICATE-----
MIIBkTCB+wIJAKHHCgVZwjBUMA0GCSqGSIb3DQEBCwUAMBExDzANBgNVBAMMBnRl
c3RDQTAeFw0yNDAxMDEwMDAwMDBaFw0yNTAxMDEwMDAwMDBaMBExDzANBgNVBAMM
BnRlc3RDQTCBnzANBgkqhkiG9w0BAQEFAAOBjQAwgYkCgYEAyZ7vN5eQ3J9K8mN
pL2Q4R5T6V7W8X9Y0Z1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p7q8r9s0t1u2v3
w4x5y6z7a8b9c0d1e2f3g4h5i6j7k8l9m0n1o2p3q4r5s6t7u8v9w0x1y2z3a4b
5c6d7e8f9g0h1i2j3k4l5m6n7o8p9q0r1s2t3u4v5w6x7y8z9CAwEAAaMgMB4w
DQYJKoZIhvcNAQELBQADgYEAB9c8Z7Q6R5T4S3P2O1N0M9L8K7J6I5H4G3F2E1D
0C9B8A7z6y5x4w3v2u1t0s9r8q7p6o5n4m3l2k1j0i9h8g7f6e5d4c3b2a1z0y9
x8w7v6u5t4s3r2q1p0o9n8m7l6k5j4i3h2g1f0e9d8c7b6a5z4y3x2w1v0u9t8
s7r6q5p4o3n2m1l0k9j8i7h6g5f4e3d2c1b0a9z8y7x6w5v4u3t2s1r0q9p8o7
n6m5l4k3j2i1h0g9f8e7d6c5b4a3z2y1x0w9v8u7t6s5r4q3p2o1n0m9l8k7j6
i5h4g3f2e1d0c9b8a7z6y5x4w3v2u1t0s9r8q7p6o5n4m3l2k1j0i=
-----END CERTIFICATE-----
"#;

    let key = r#"-----BEGIN PRIVATE KEY-----
MIICdgIBADANBgkqhkiG9w0BAQEFAASCAmAwggJcAgEAAoGBAMme7zeXkNyfSvJj
aS9kOEeU+le1vF/WNGdWtm93OHXu4f7h9i0j1k2l3m4n5o6p7q8r9s0t1u2v3w4x
5y6z7a8b9c0d1e2f3g4h5i6j7k8l9m0n1o2p3q4r5s6t7u8v9w0x1y2z3a4b5c6d
7e8f9g0h1i2j3k4l5m6n7o8p9q0r1s2t3u4v5w6x7y8z9AgMBAAECgYEAyZ7vN5
eQ3J9K8mNpL2Q4R5T6V7W8X9Y0Z1a2b3c4d5e6f7g8h9i0j1k2l3m4n5o6p7q8r
9s0t1u2v3w4x5y6z7a8b9c0d1e2f3g4h5i6j7k8l9m0n1o2p3q4r5s6t7u8v9w0
x1y2z3a4b5c6d7e8f9g0h1i2j3k4l5m6n7o8p9q0r1s2t3u4v5w6x7y8z9ECgYE
AMme7zeXkNyfSvJjaS9kOEeU+le1vF/WNGdWtm93OHXu4f7h9i0j1k2l3m4n5o6
p7q8r9s0t1u2v3w4x5y6z7a8b9c0d1e2f3g4h5i6j7k8l9m0n1o2p3q4r5s6t7u
8v9w0x1y2z3a4b5c6d7e8f9g0h1i2j3k4l5m6n7o8p9q0r1s2t3u4v5w6x7y8z9
ECgYEAMme7zeXkNyfSvJjaS9kOEeU+le1vF/WNGdWtm93OHXu4f7h9i0j1k2l3m
4n5o6p7q8r9s0t1u2v3w4x5y6z7a8b9c0d1e2f3g4h5i6j7k8l9m0n1o2p3q4r5
s6t7u8v9w0x1y2z3a4b5c6d7e8f9g0h1i2j3k4l5m6n7o8p9q0r1s2t3u4v5w6x
7y8z9ECgYEAMme7zeXkNyfSvJjaS9kOEeU+le1vF/WNGdWtm93OHXu4f7h9i0j1
k2l3m4n5o6p7q8r9s0t1u2v3w4x5y6z7a8b9c0d1e2f3g4h5i6j7k8l9m0n1o2p
3q4r5s6t7u8v9w0x1y2z3a4b5c6d7e8f9g0h1i2j3k4l5m6n7o8p9q0r1s2t3u4
v5w6x7y8z9ECgYEAMme7zeXkNyfSvJjaS9kOEeU+le1vF/WNGdWtm93OHXu4f7h
9i0j1k2l3m4n5o6p7q8r9s0t1u2v3w4x5y6z7a8b9c0d1e2f3g4h5i6j7k8l9m0
n1o2p3q4r5s6t7u8v9w0x1y2z3a4b5c6d7e8f9g0h1i2j3k4l5m6n7o8p9q0r1s
2t3u4v5w6x7y8z9=
-----END PRIVATE KEY-----
"#;

    (cert.to_string(), key.to_string())
}

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

    #[test]
    fn test_auth_config_default() {
        let auth = AuthConfig::default();
        assert!(!auth.has_token());
        assert!(!auth.has_basic());
        assert!(auth.verify_token(""));
    }

    #[test]
    fn test_auth_config_token() {
        let auth = AuthConfig::default().with_token("my-secret");
        assert!(auth.has_token());
        assert!(auth.verify_token("my-secret"));
        assert!(!auth.verify_token("wrong"));
    }

    #[test]
    fn test_auth_config_basic() {
        let auth = AuthConfig::default().with_basic_auth("admin", "pass123");
        assert!(auth.has_basic());
        let encoded = base64::engine::general_purpose::STANDARD.encode(b"admin:pass123");
        assert!(auth.verify_basic(&encoded));
        assert!(
            !auth.verify_basic(
                base64::engine::general_purpose::STANDARD
                    .encode(b"admin:wrong")
                    .as_str()
            )
        );
    }

    #[test]
    fn test_cors_config_default() {
        let cors = CorsConfig::default();
        let headers = cors.to_headers();
        assert!(
            headers
                .iter()
                .any(|(k, _)| k == &"Access-Control-Allow-Origin")
        );
    }

    #[test]
    fn test_server_config_default() {
        let cfg = ServerConfig::default();
        assert_eq!(cfg.port, 6800);
        assert_eq!(cfg.addr(), "127.0.0.1:6800");
    }

    #[test]
    fn test_server_config_builder() {
        let cfg = ServerConfig::default()
            .with_port(8080)
            .with_host("0.0.0.0")
            .with_auth(AuthConfig::default().with_token("tok"));
        assert_eq!(cfg.port, 8080);
        assert!(cfg.auth.has_token());
    }

    // =========================================================================
    // RpcAuthMiddleware Tests (G4 Part B)
    // =========================================================================

    #[test]
    fn test_auth_valid_token_passes() {
        let middleware = RpcAuthMiddleware::new("my-secret-token");
        // Valid token should pass
        assert!(middleware.validate(Some("my-secret-token")).is_ok());
    }

    #[test]
    fn test_auth_wrong_token_rejected() {
        let middleware = RpcAuthMiddleware::new("my-secret-token");
        let result = middleware.validate(Some("wrong-token"));
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.code(), -32001);
        assert!(err.to_string().contains("Invalid token"));
    }

    #[test]
    fn test_auth_no_secret_configured_accepts_all() {
        let middleware = RpcAuthMiddleware::new(""); // Empty secret = no auth
        // All should pass when no secret is configured
        assert!(middleware.validate(None).is_ok());
        assert!(middleware.validate(Some("anything")).is_ok());
        assert!(middleware.validate(Some("")).is_ok());
        assert!(
            !middleware.is_auth_enabled(),
            "Auth should be disabled with empty secret"
        );
    }

    #[test]
    fn test_auth_token_required_when_secret_set() {
        let middleware = RpcAuthMiddleware::new("secret123");
        // No token provided but secret is set → should fail
        let result = middleware.validate(None);
        assert!(result.is_err());
        let err = result.unwrap_err();
        assert_eq!(err.code(), -32001);
        assert!(err.to_string().contains("Token required"));
        assert!(
            middleware.is_auth_enabled(),
            "Auth should be enabled with non-empty secret"
        );
    }

    #[test]
    fn test_auth_middleware_default() {
        let middleware = RpcAuthMiddleware::default();
        assert!(!middleware.is_auth_enabled());
        assert!(middleware.validate(None).is_ok());
        assert!(middleware.validate(Some("x")).is_ok());
    }

    #[test]
    fn test_auth_middleware_secret_accessor() {
        let middleware = RpcAuthMiddleware::new("test-secret");
        assert_eq!(middleware.secret(), "test-secret");
    }

    // =========================================================================
    // CORS Configuration Tests (H6)
    // =========================================================================

    #[test]
    fn test_cors_wildcard_allows_any_origin() {
        let cors = CorsConfig::default(); // Default is wildcard "*"

        // Wildcard should allow any origin
        assert!(cors.allows_origin(Some("http://localhost:8080")));
        assert!(cors.allows_origin(Some("https://example.com")));
        assert!(cors.allows_origin(Some("http://192.168.1.1:3000")));
        assert!(cors.allows_origin(None)); // No origin header
    }

    #[test]
    fn test_cors_specific_domain_blocks_others() {
        let cors = CorsConfig::from_option_value("http://localhost:8080,https://example.com");

        // Allowed origins should pass
        assert!(
            cors.allows_origin(Some("http://localhost:8080")),
            "Should allow exact match for localhost"
        );
        assert!(
            cors.allows_origin(Some("https://example.com")),
            "Should allow exact match for example.com"
        );

        // Non-allowed origins should be blocked
        assert!(
            !cors.allows_origin(Some("http://evil.com")),
            "Should block non-listed origin"
        );
        assert!(
            !cors.allows_origin(Some("http://localhost:8081")),
            "Should block different port"
        );
        assert!(
            !cors.allows_origin(Some("http://localhost:8080/extra")),
            "Should block origin with path (strict matching)"
        );

        // No origin header should still be allowed
        assert!(
            cors.allows_origin(None),
            "No origin header should be allowed"
        );
    }

    #[test]
    fn test_cors_preflight_returns_true_for_allowed() {
        let cors = CorsConfig::from_option_value("http://localhost:8080");

        // Preflight should succeed for allowed origin
        assert!(cors.handle_preflight(Some("http://localhost:8080")));

        // Preflight should fail for disallowed origin
        assert!(!cors.handle_preflight(Some("http://evil.com")));

        // No origin - preflight should succeed
        assert!(cors.handle_preflight(None));
    }

    #[test]
    fn test_cors_from_option_value_parsing() {
        // Test wildcard
        let cors_wildcard = CorsConfig::from_option_value("*");
        assert!(cors_wildcard.allows_origin(Some("anything")));
        assert_eq!(cors_wildcard.allow_origin, "*");

        // Test empty string defaults to wildcard
        let cors_empty = CorsConfig::from_option_value("");
        assert!(cors_empty.allows_origin(Some("anything")));

        // Test multiple origins
        let cors_multi =
            CorsConfig::from_option_value("http://a.com, https://b.com, http://c.com:9090");
        assert!(cors_multi.allows_origin(Some("http://a.com")));
        assert!(cors_multi.allows_origin(Some("https://b.com")));
        assert!(cors_multi.allows_origin(Some("http://c.com:9090")));
        assert!(!cors_multi.allows_origin(Some("http://d.com")));

        // Test with whitespace handling
        let cors_spaces = CorsConfig::from_option_value("  http://a.com , https://b.com  ");
        assert!(cors_spaces.allows_origin(Some("http://a.com")));
        assert!(cors_spaces.allows_origin(Some("https://b.com")));
    }

    #[test]
    fn test_cors_headers_for_origin() {
        let cors = CorsConfig::from_option_value("http://localhost:8080");

        // Allowed origin should produce headers
        let headers = cors.headers_for_origin(Some("http://localhost:8080"));
        assert!(
            headers.is_some(),
            "Should return headers for allowed origin"
        );
        let headers = headers.unwrap();
        assert!(
            headers
                .iter()
                .any(|(k, _)| *k == "Access-Control-Allow-Origin"),
            "Should contain Allow-Origin header"
        );

        // Disallowed origin should return None
        let blocked = cors.headers_for_origin(Some("http://evil.com"));
        assert!(blocked.is_none(), "Should return None for blocked origin");
    }

    #[test]
    fn test_cors_with_allowed_origins_constructor() {
        let cors = CorsConfig::with_allowed_origins(vec![
            "https://api.example.com".to_string(),
            "http://localhost:3000".to_string(),
        ]);

        assert!(cors.allows_origin(Some("https://api.example.com")));
        assert!(cors.allows_origin(Some("http://localhost:3000")));
        assert!(!cors.allows_origin(Some("http://other.com")));
    }

    // =========================================================================
    // TLS Configuration Tests
    // =========================================================================

    #[test]
    fn test_tls_config_new() {
        let tls = TlsConfig::new("/path/to/cert.pem", "/path/to/key.pem");
        assert_eq!(tls.cert_path, "/path/to/cert.pem");
        assert_eq!(tls.key_path, "/path/to/key.pem");
    }

    #[test]
    fn test_tls_error_display() {
        let err = TlsError::NoCertificates;
        assert!(err.to_string().contains("No certificates"));

        let err = TlsError::NoPrivateKey;
        assert!(err.to_string().contains("No private key"));
    }

    #[test]
    fn test_server_config_with_tls() {
        let tls = TlsConfig::new("/cert.pem", "/key.pem");
        let config = ServerConfig::default().with_port(8443).with_tls(tls);

        assert!(config.is_secure());
        assert_eq!(config.scheme(), "https");
        assert!(config.tls.is_some());
    }

    #[test]
    fn test_server_config_without_tls() {
        let config = ServerConfig::default();
        assert!(!config.is_secure());
        assert_eq!(config.scheme(), "http");
        assert!(config.tls.is_none());
    }

    // =========================================================================
    // RpcServer Tests
    // =========================================================================

    #[test]
    fn test_rpc_server_new_http() {
        let server = RpcServer::new_http("127.0.0.1", 6800);
        assert_eq!(server.addr(), "127.0.0.1:6800");
        assert_eq!(server.port(), 6800);
        assert!(!server.is_secure());
        assert_eq!(server.scheme(), "http");
        assert_eq!(server.rpc_url(), "http://127.0.0.1:6800/jsonrpc");
    }

    #[test]
    fn test_rpc_server_from_config() {
        let config = ServerConfig::default().with_host("0.0.0.0").with_port(8080);

        let server = RpcServer::new(config).expect("Failed to create server");
        assert_eq!(server.addr(), "0.0.0.0:8080");
        assert!(!server.is_secure());
    }

    #[test]
    fn test_rpc_server_debug_format() {
        let server = RpcServer::new_http("localhost", 6800);
        let debug_str = format!("{:?}", server);
        assert!(debug_str.contains("RpcServer"));
        assert!(debug_str.contains("localhost:6800"));
        assert!(debug_str.contains("secure: false"));
    }

    #[test]
    fn test_rpc_server_config_accessor() {
        let config = ServerConfig::default()
            .with_host("192.168.1.1")
            .with_port(9999);

        let server = RpcServer::new(config).expect("Failed to create server");
        let cfg = server.config();
        assert_eq!(cfg.host, "192.168.1.1");
        assert_eq!(cfg.port, 9999);
    }

    #[test]
    fn test_rpc_server_tls_acceptor_none_for_http() {
        let server = RpcServer::new_http("127.0.0.1", 6800);
        assert!(server.tls_acceptor().is_none());
    }

    #[test]
    fn test_generate_test_cert() {
        let (cert, key) = generate_test_cert();
        assert!(cert.contains("BEGIN CERTIFICATE"));
        assert!(cert.contains("END CERTIFICATE"));
        assert!(key.contains("BEGIN PRIVATE KEY"));
        assert!(key.contains("END PRIVATE KEY"));
    }
}