a3s-gateway 1.0.7

A3S Gateway - AI-native API gateway with reverse proxy, routing, and agent orchestration
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
use clap::{Args, Parser, Subcommand};
use std::sync::Arc;
use tracing_subscriber::EnvFilter;

/// A3S Gateway — AI-native API gateway
#[derive(Parser)]
#[command(name = "a3s-gateway", version, about)]
struct Cli {
    /// Path to configuration file (.acl)
    #[arg(short, long, default_value = "gateway.acl")]
    config: String,

    /// Override listen address (e.g., 0.0.0.0:8080)
    #[arg(short, long)]
    listen: Option<String>,

    /// Log level (trace, debug, info, warn, error)
    #[arg(long, default_value = "info")]
    log_level: String,

    #[command(subcommand)]
    command: Option<Commands>,
}

#[derive(Subcommand)]
enum Commands {
    /// Update a3s-gateway to the latest version
    Update,
    /// Validate a configuration file without starting the gateway
    Validate {
        /// Path to configuration file to validate
        #[arg(short, long, default_value = "gateway.acl")]
        config: String,
    },
    /// Inspect ACL configuration from the CLI
    Config {
        /// Path to configuration file to inspect
        #[arg(short, long, default_value = "gateway.acl")]
        config: String,
        #[command(subcommand)]
        command: ConfigCommands,
    },
    /// Inspect a running management listener
    Management {
        #[command(subcommand)]
        command: ManagementCommands,
    },
}

#[derive(Subcommand)]
enum ConfigCommands {
    /// Print a compact configuration summary
    Summary,
    /// List configured entrypoints
    Entrypoints,
    /// List configured routers
    Routes,
    /// List configured services and backend counts
    Services,
    /// List configured middleware names
    Middlewares,
    /// List enabled providers
    Providers,
    /// Print the parsed configuration as JSON
    Json,
}

#[derive(Subcommand)]
enum ManagementCommands {
    /// Fetch recent management security audit events
    Events {
        #[command(flatten)]
        api: ManagementApiArgs,

        /// Maximum number of events to fetch.
        #[arg(long, default_value_t = 100)]
        limit: usize,

        /// Print raw JSON instead of tab-separated rows.
        #[arg(long)]
        json: bool,
    },
    /// Validate an ACL file through the management API
    Validate {
        /// ACL configuration file to validate.
        #[arg(short, long)]
        file: String,

        #[command(flatten)]
        api: ManagementApiArgs,

        /// Print raw JSON response.
        #[arg(long)]
        json: bool,
    },
    /// Reload the gateway with an ACL file through the management API
    Reload {
        /// ACL configuration file to apply.
        #[arg(short, long)]
        file: String,

        #[command(flatten)]
        api: ManagementApiArgs,

        /// Print raw JSON response.
        #[arg(long)]
        json: bool,
    },
}

#[derive(Args, Clone)]
struct ManagementApiArgs {
    /// Base management API URL, without endpoint suffix.
    #[arg(long, default_value = "http://127.0.0.1:9090/api/gateway")]
    url: String,

    /// Bearer token value. If omitted, A3S_GATEWAY_ADMIN_TOKEN is used when present.
    #[arg(long)]
    token: Option<String>,

    /// Environment variable containing the bearer token.
    #[arg(long)]
    token_env: Option<String>,

    /// PEM CA certificate used to verify the management listener.
    #[arg(long)]
    ca_cert: Option<String>,

    /// PEM client certificate for mTLS.
    #[arg(long)]
    client_cert: Option<String>,

    /// PEM client private key for mTLS.
    #[arg(long)]
    client_key: Option<String>,

    /// Disable TLS certificate verification. Use only for local diagnostics.
    #[arg(long)]
    insecure: bool,
}

#[tokio::main]
async fn main() -> a3s_gateway::Result<()> {
    // rustls 0.23 with both `aws-lc-rs` and `ring` in the dep graph refuses to
    // auto-pick a CryptoProvider; install `ring` explicitly so kube-rs/reqwest
    // TLS clients don't panic on first use.
    let _ = rustls::crypto::ring::default_provider().install_default();

    let cli = Cli::parse();

    // Handle update subcommand early
    if matches!(cli.command, Some(Commands::Update)) {
        return a3s_updater::run_update(&a3s_updater::UpdateConfig {
            binary_name: "a3s-gateway",
            crate_name: "a3s-gateway",
            current_version: env!("CARGO_PKG_VERSION"),
            github_owner: "A3S-Lab",
            github_repo: "Gateway",
        })
        .await
        .map_err(|e| a3s_gateway::GatewayError::Other(e.to_string()));
    }

    // Handle validate subcommand
    if let Some(Commands::Validate {
        config: config_path,
    }) = &cli.command
    {
        return validate_config(config_path).await;
    }

    if let Some(Commands::Config {
        config: config_path,
        command,
    }) = &cli.command
    {
        return inspect_config(config_path, command).await;
    }

    if let Some(Commands::Management { command }) = &cli.command {
        return inspect_management(command).await;
    }

    // Initialize tracing
    tracing_subscriber::fmt()
        .with_env_filter(
            EnvFilter::try_from_default_env().unwrap_or_else(|_| EnvFilter::new(&cli.log_level)),
        )
        .init();

    tracing::info!("A3S Gateway v{}", env!("CARGO_PKG_VERSION"));

    // Load configuration
    let mut config = if std::path::Path::new(&cli.config).exists() {
        tracing::info!(config = cli.config, "Loading configuration");
        a3s_gateway::config::GatewayConfig::from_file(&cli.config).await?
    } else {
        tracing::warn!("Config file not found, using defaults");
        a3s_gateway::config::GatewayConfig::default()
    };

    // Override listen address if provided
    if let Some(listen) = &cli.listen {
        config.entrypoints.insert(
            "web".to_string(),
            a3s_gateway::config::EntrypointConfig::new(listen),
        );
    }

    // Create and start the gateway
    let gateway = Arc::new(a3s_gateway::Gateway::new(config.clone())?);
    gateway.start().await?;

    tracing::info!("Gateway ready — press Ctrl+C to stop");

    // Start hot reload watcher if configured
    if let Some(ref file_config) = config.providers.file {
        if file_config.watch {
            let watcher = a3s_gateway::provider::FileWatcher::new(&cli.config);
            let watcher = if let Some(ref dir) = file_config.directory {
                watcher.with_directory(dir)
            } else {
                watcher
            };

            match watcher.watch() {
                Ok(rx) => {
                    let gw = gateway.clone();
                    tokio::spawn(async move {
                        while let Ok(event) = rx.recv() {
                            match event.config {
                                Ok(new_config) => {
                                    tracing::info!(
                                        path = %event.trigger_path.display(),
                                        "Config change detected, reloading"
                                    );
                                    if let Err(e) = gw.reload(new_config).await {
                                        tracing::error!(error = %e, "Hot reload failed");
                                    }
                                }
                                Err(e) => {
                                    tracing::error!(
                                        error = %e,
                                        path = %event.trigger_path.display(),
                                        "Config reload failed, keeping current config"
                                    );
                                }
                            }
                        }
                    });
                    tracing::info!("Hot reload enabled");
                }
                Err(e) => {
                    tracing::warn!(error = %e, "Failed to start file watcher, hot reload disabled");
                }
            }
        }
    }

    // Wait for shutdown signal
    gateway.wait_for_shutdown().await;

    Ok(())
}

async fn inspect_config(path: &str, command: &ConfigCommands) -> a3s_gateway::Result<()> {
    let config = load_validated_config(path).await?;

    match command {
        ConfigCommands::Summary => print!("{}", render_config_summary(&config)),
        ConfigCommands::Entrypoints => print!("{}", render_entrypoints(&config)),
        ConfigCommands::Routes => print!("{}", render_routes(&config)),
        ConfigCommands::Services => print!("{}", render_services(&config)),
        ConfigCommands::Middlewares => print!("{}", render_middlewares(&config)),
        ConfigCommands::Providers => print!("{}", render_providers(&config)),
        ConfigCommands::Json => {
            let json = serde_json::to_string_pretty(&config)
                .map_err(|e| a3s_gateway::GatewayError::Other(e.to_string()))?;
            println!("{}", json);
        }
    }

    Ok(())
}

async fn inspect_management(command: &ManagementCommands) -> a3s_gateway::Result<()> {
    match command {
        ManagementCommands::Events { api, limit, json } => {
            let events =
                fetch_management_events(ManagementEventsRequest { api, limit: *limit }).await?;

            if *json {
                let body = serde_json::to_string_pretty(&events)
                    .map_err(|e| a3s_gateway::GatewayError::Other(e.to_string()))?;
                println!("{}", body);
            } else {
                print!("{}", render_management_events(&events));
            }
        }
        ManagementCommands::Validate { file, api, json } => {
            let acl = std::fs::read_to_string(file).map_err(|e| {
                a3s_gateway::GatewayError::Other(format!(
                    "Failed to read management validation file {}: {}",
                    file, e
                ))
            })?;
            let response =
                post_management_config(api, "config/validate", acl, "validation").await?;
            print_management_mutation_response(&response, *json)?;
        }
        ManagementCommands::Reload { file, api, json } => {
            let acl = std::fs::read_to_string(file).map_err(|e| {
                a3s_gateway::GatewayError::Other(format!(
                    "Failed to read management reload file {}: {}",
                    file, e
                ))
            })?;
            let response = post_management_config(api, "config/reload", acl, "reload").await?;
            print_management_mutation_response(&response, *json)?;
        }
    }

    Ok(())
}

struct ManagementEventsRequest<'a> {
    api: &'a ManagementApiArgs,
    limit: usize,
}

async fn fetch_management_events(
    request: ManagementEventsRequest<'_>,
) -> a3s_gateway::Result<Vec<a3s_gateway::dashboard::ManagementAuditEvent>> {
    let client = build_management_http_client(request.api)?;
    let endpoint =
        management_endpoint_url(&request.api.url, &format!("events?limit={}", request.limit));
    let response = send_management_request(client.get(endpoint), request.api)
        .await?
        .json::<Vec<a3s_gateway::dashboard::ManagementAuditEvent>>()
        .await
        .map_err(|e| a3s_gateway::GatewayError::Other(e.to_string()))?;

    Ok(response)
}

async fn post_management_config(
    api: &ManagementApiArgs,
    endpoint: &str,
    acl: String,
    action: &str,
) -> a3s_gateway::Result<serde_json::Value> {
    let client = build_management_http_client(api)?;
    let url = management_endpoint_url(&api.url, endpoint);
    send_management_request(
        client
            .post(url)
            .body(acl)
            .header("Content-Type", "text/plain"),
        api,
    )
    .await?
    .json::<serde_json::Value>()
    .await
    .map_err(|e| {
        a3s_gateway::GatewayError::Other(format!(
            "Failed to parse management {} response: {}",
            action, e
        ))
    })
}

fn build_management_http_client(api: &ManagementApiArgs) -> a3s_gateway::Result<reqwest::Client> {
    let mut builder = reqwest::Client::builder();
    if api.insecure {
        builder = builder.danger_accept_invalid_certs(true);
    }
    if let Some(path) = api.ca_cert.as_deref() {
        let pem = std::fs::read(path).map_err(|e| {
            a3s_gateway::GatewayError::Other(format!(
                "Failed to read management CA certificate {}: {}",
                path, e
            ))
        })?;
        let cert = reqwest::Certificate::from_pem(&pem)
            .map_err(|e| a3s_gateway::GatewayError::Other(e.to_string()))?;
        builder = builder.add_root_certificate(cert);
    }
    match (api.client_cert.as_deref(), api.client_key.as_deref()) {
        (Some(cert_path), Some(key_path)) => {
            let mut pem = std::fs::read(cert_path).map_err(|e| {
                a3s_gateway::GatewayError::Other(format!(
                    "Failed to read management client certificate {}: {}",
                    cert_path, e
                ))
            })?;
            let key = std::fs::read(key_path).map_err(|e| {
                a3s_gateway::GatewayError::Other(format!(
                    "Failed to read management client key {}: {}",
                    key_path, e
                ))
            })?;
            pem.extend_from_slice(&key);
            let identity = reqwest::Identity::from_pem(&pem)
                .map_err(|e| a3s_gateway::GatewayError::Other(e.to_string()))?;
            builder = builder.identity(identity);
        }
        (Some(_), None) | (None, Some(_)) => {
            return Err(a3s_gateway::GatewayError::Other(
                "Both --client-cert and --client-key are required for mTLS".to_string(),
            ));
        }
        (None, None) => {}
    }

    builder
        .build()
        .map_err(|e| a3s_gateway::GatewayError::Other(e.to_string()))
}

async fn send_management_request(
    request: reqwest::RequestBuilder,
    api: &ManagementApiArgs,
) -> a3s_gateway::Result<reqwest::Response> {
    let mut request = request;
    if let Some(token) = management_bearer_token(api.token.as_deref(), api.token_env.as_deref()) {
        request = request.bearer_auth(token);
    }

    let response = request
        .send()
        .await
        .map_err(|e| a3s_gateway::GatewayError::Other(e.to_string()))?;
    let status = response.status();
    if !status.is_success() {
        let body = response.text().await.unwrap_or_default();
        return Err(a3s_gateway::GatewayError::Other(format!(
            "Management events request failed with {}: {}",
            status, body
        )));
    }

    Ok(response)
}

fn management_endpoint_url(base_url: &str, endpoint: &str) -> String {
    format!("{}/{}", base_url.trim_end_matches('/'), endpoint)
}

fn print_management_mutation_response(
    response: &serde_json::Value,
    json: bool,
) -> a3s_gateway::Result<()> {
    if json {
        let body = serde_json::to_string_pretty(response)
            .map_err(|e| a3s_gateway::GatewayError::Other(e.to_string()))?;
        println!("{}", body);
    } else if let Some(message) = response.get("message").and_then(|value| value.as_str()) {
        println!("{}", message);
    } else {
        println!("Success");
    }
    Ok(())
}

fn management_bearer_token(token: Option<&str>, token_env: Option<&str>) -> Option<String> {
    match (token, token_env) {
        (Some(token), _) => Some(token.to_string()),
        (None, Some(env)) => std::env::var(env).ok(),
        (None, None) => std::env::var("A3S_GATEWAY_ADMIN_TOKEN").ok(),
    }
}

fn render_management_events(events: &[a3s_gateway::dashboard::ManagementAuditEvent]) -> String {
    use std::fmt::Write;

    let mut out = String::new();
    for event in events {
        writeln!(
            &mut out,
            "{}\t{}\t{}\t{}\t{}\t{}\t{}",
            event.sequence,
            event.timestamp,
            event.kind,
            event
                .status
                .map(|status| status.to_string())
                .unwrap_or_else(|| "-".to_string()),
            event.remote_addr.as_deref().unwrap_or("-"),
            event.path.as_deref().unwrap_or("-"),
            event.reason
        )
        .unwrap();
    }
    out
}

async fn load_validated_config(
    path: &str,
) -> a3s_gateway::Result<a3s_gateway::config::GatewayConfig> {
    let config = a3s_gateway::config::GatewayConfig::from_file(path).await?;
    config.validate()?;
    Ok(config)
}

fn render_config_summary(config: &a3s_gateway::config::GatewayConfig) -> String {
    use std::fmt::Write;

    let mut out = String::new();
    writeln!(&mut out, "Configuration summary").unwrap();
    writeln!(&mut out, "  Entrypoints: {}", config.entrypoints.len()).unwrap();
    writeln!(&mut out, "  Routers:     {}", config.routers.len()).unwrap();
    writeln!(&mut out, "  Services:    {}", config.services.len()).unwrap();
    writeln!(&mut out, "  Middlewares: {}", config.middlewares.len()).unwrap();
    writeln!(
        &mut out,
        "  Providers:   {}",
        provider_names(config).join(", ")
    )
    .unwrap();
    writeln!(
        &mut out,
        "  Management:  {}",
        if config.management.enabled {
            config.management.address.as_str()
        } else {
            "disabled"
        }
    )
    .unwrap();
    out
}

fn render_entrypoints(config: &a3s_gateway::config::GatewayConfig) -> String {
    use std::fmt::Write;

    let mut out = String::new();
    let mut entrypoints: Vec<_> = config.entrypoints.iter().collect();
    entrypoints.sort_by_key(|(k, _)| (*k).clone());
    for (name, entrypoint) in entrypoints {
        writeln!(
            &mut out,
            "{}\t{}\t{:?}",
            name, entrypoint.address, entrypoint.protocol
        )
        .unwrap();
    }
    out
}

fn render_routes(config: &a3s_gateway::config::GatewayConfig) -> String {
    use std::fmt::Write;

    let mut out = String::new();
    let mut routers: Vec<_> = config.routers.iter().collect();
    routers.sort_by_key(|(k, _)| (*k).clone());
    for (name, router) in routers {
        writeln!(
            &mut out,
            "{}\tservice={}\trule={}\tentrypoints={}",
            name,
            router.service,
            router.rule,
            router.entrypoints.join(",")
        )
        .unwrap();
    }
    out
}

fn render_services(config: &a3s_gateway::config::GatewayConfig) -> String {
    use std::fmt::Write;

    let mut out = String::new();
    let mut services: Vec<_> = config.services.iter().collect();
    services.sort_by_key(|(k, _)| (*k).clone());
    for (name, service) in services {
        let base_backends = service.load_balancer.servers.len();
        let revision_backends: usize = service
            .revisions
            .iter()
            .map(|revision| revision.servers.len())
            .sum();
        writeln!(
            &mut out,
            "{}\tbase_backends={}\trevision_backends={}\tstrategy={:?}",
            name, base_backends, revision_backends, service.load_balancer.strategy
        )
        .unwrap();
    }
    out
}

fn render_middlewares(config: &a3s_gateway::config::GatewayConfig) -> String {
    use std::fmt::Write;

    let mut out = String::new();
    let mut middlewares: Vec<_> = config.middlewares.keys().collect();
    middlewares.sort();
    for name in middlewares {
        writeln!(&mut out, "{}", name).unwrap();
    }
    out
}

fn render_providers(config: &a3s_gateway::config::GatewayConfig) -> String {
    use std::fmt::Write;

    let mut out = String::new();
    for name in provider_names(config) {
        writeln!(&mut out, "{}", name).unwrap();
    }
    out
}

fn provider_names(config: &a3s_gateway::config::GatewayConfig) -> Vec<&'static str> {
    let mut providers = Vec::new();
    if config.providers.file.is_some() {
        providers.push("file");
    }
    if config.providers.discovery.is_some() {
        providers.push("discovery");
    }
    if config.providers.kubernetes.is_some() {
        providers.push("kubernetes");
    }
    if config.providers.docker.is_some() {
        providers.push("docker");
    }
    if providers.is_empty() {
        providers.push("none");
    }
    providers
}

/// Validate a configuration file and print diagnostics
async fn validate_config(path: &str) -> a3s_gateway::Result<()> {
    use std::path::Path;

    let config_path = Path::new(path);
    if !config_path.exists() {
        eprintln!("✗ Config file not found: {}", path);
        std::process::exit(1);
    }

    // Parse
    let config = match a3s_gateway::config::GatewayConfig::from_file(path).await {
        Ok(c) => {
            println!("✓ Config parsed successfully ({})", path);
            c
        }
        Err(e) => {
            eprintln!("✗ Parse error: {}", e);
            std::process::exit(1);
        }
    };

    // Validate
    if let Err(e) = config.validate() {
        eprintln!("✗ Validation error: {}", e);
        std::process::exit(1);
    }

    // Print summary
    println!("✓ Configuration is valid");
    println!();
    println!("  Entrypoints: {}", config.entrypoints.len());
    let mut entrypoints: Vec<_> = config.entrypoints.iter().collect();
    entrypoints.sort_by_key(|(k, _)| (*k).clone());
    for (name, ep) in entrypoints {
        println!("    - {}{} ({:?})", name, ep.address, ep.protocol);
    }
    println!("  Routers:     {}", config.routers.len());
    let mut routers: Vec<_> = config.routers.iter().collect();
    routers.sort_by_key(|(k, _)| (*k).clone());
    for (name, router) in routers {
        println!(
            "    - {} → service:{} rule:{}",
            name, router.service, router.rule
        );
    }
    println!("  Services:    {}", config.services.len());
    let mut services: Vec<_> = config.services.iter().collect();
    services.sort_by_key(|(k, _)| (*k).clone());
    for (name, svc) in services {
        println!(
            "    - {} ({} backends, strategy: {:?})",
            name,
            svc.load_balancer.servers.len(),
            svc.load_balancer.strategy
        );
    }
    println!("  Middlewares:  {}", config.middlewares.len());
    let mut middlewares: Vec<_> = config.middlewares.keys().collect();
    middlewares.sort();
    for name in middlewares {
        println!("    - {}", name);
    }

    // Provider info
    if config.providers.file.is_some() {
        println!("  Provider:    file (hot reload)");
    }
    if config.providers.discovery.is_some() {
        println!("  Provider:    discovery (health-based)");
    }
    if config.providers.kubernetes.is_some() {
        println!("  Provider:    kubernetes");
    }
    if config.providers.docker.is_some() {
        println!("  Provider:    docker");
    }
    if config.management.enabled {
        println!(
            "  Management:  {}{}",
            config.management.address, config.management.path_prefix
        );
    }

    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use a3s_gateway::config::{
        EntrypointConfig, GatewayConfig, LoadBalancerConfig, Protocol, RouterConfig, ServerConfig,
        ServiceConfig, Strategy,
    };
    use std::collections::HashMap;

    fn config_fixture() -> GatewayConfig {
        let mut config = GatewayConfig::default();
        config.entrypoints.insert(
            "admin".to_string(),
            EntrypointConfig {
                address: "127.0.0.1:9000".to_string(),
                protocol: Protocol::Http,
                tls: None,
                max_connections: None,
                tcp_allowed_ips: vec![],
                udp_session_timeout_secs: None,
                udp_max_sessions: None,
            },
        );
        config.routers.insert(
            "api".to_string(),
            RouterConfig {
                rule: "PathPrefix(`/api`)".to_string(),
                service: "backend".to_string(),
                entrypoints: vec!["web".to_string()],
                middlewares: vec![],
                priority: 0,
            },
        );
        config.services.insert(
            "backend".to_string(),
            ServiceConfig {
                load_balancer: LoadBalancerConfig {
                    strategy: Strategy::RoundRobin,
                    request_timeout: "30s".to_string(),
                    servers: vec![ServerConfig {
                        url: "http://127.0.0.1:8001".to_string(),
                        weight: 1,
                    }],
                    health_check: None,
                    sticky: None,
                },
                scaling: None,
                revisions: vec![],
                rollout: None,
                mirror: None,
                failover: None,
            },
        );
        config.middlewares = HashMap::new();
        config
    }

    #[test]
    fn test_render_config_summary() {
        let config = config_fixture();
        let summary = render_config_summary(&config);
        assert!(summary.contains("Entrypoints: 2"));
        assert!(summary.contains("Routers:     1"));
        assert!(summary.contains("Services:    1"));
    }

    #[test]
    fn test_render_routes_and_services() {
        let config = config_fixture();
        assert!(render_routes(&config).contains("service=backend"));
        assert!(render_services(&config).contains("base_backends=1"));
    }

    #[test]
    fn test_provider_names_none() {
        let config = config_fixture();
        assert_eq!(provider_names(&config), vec!["none"]);
    }

    #[test]
    fn test_render_management_events() {
        let event = a3s_gateway::dashboard::ManagementAuditEvent {
            sequence: 1,
            timestamp: "2026-05-09T00:00:00Z".to_string(),
            kind: a3s_gateway::dashboard::ManagementAuditEventKind::AuthRejected,
            remote_addr: Some("127.0.0.1:50000".to_string()),
            path: Some("/api/gateway/health".to_string()),
            status: Some(401),
            reason: "Bearer token is missing or invalid".to_string(),
        };

        let output = render_management_events(&[event]);
        assert!(output.contains("auth-rejected"));
        assert!(output.contains("401"));
    }
}