koi-net 0.4.1

Local network toolkit: service discovery, DNS, health monitoring, TLS proxy, and certificate mesh
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
//! HTTP adapter - builds and serves the axum router.
//!
//! Mounts domain routes, health check, unified status, CORS, and OpenAPI docs.
//! Called by `daemon_mode()` in `main.rs` and `run_service()` in `platform/windows.rs`.

use std::sync::Arc;

use axum::body::Body;
use axum::extract::Extension;
use axum::http::{header, HeaderName, Request, StatusCode};
use axum::middleware::{self, Next};
use axum::response::{IntoResponse, Json, Response};
use axum::routing::{get, post};
use axum::Router;
use serde::Serialize;
use subtle::ConstantTimeEq;
use tokio_util::sync::CancellationToken;
use tower_http::cors::CorsLayer;
use utoipa::OpenApi;
use utoipa::ToSchema;
use utoipa_scalar::{Scalar, Servable};

use crate::DaemonCores;
use koi_dashboard::browser::BrowserState;
use koi_dashboard::dashboard::DashboardState;
use koi_dashboard::meta_browse::LazyMetaBrowse;

/// Header name for Daemon Access Token authentication.
const DAT_HEADER: &str = "x-koi-token";

// ── System-level route path constants ───────────────────────────────

/// Route path constants for system endpoints not owned by any domain crate.
pub mod paths {
    pub const HEALTHZ: &str = "/healthz";
    pub const UNIFIED_STATUS: &str = "/v1/status";
    pub const SHUTDOWN: &str = "/v1/admin/shutdown";
    pub const HOST: &str = "/v1/host";
}

// ── App state ───────────────────────────────────────────────────────

#[derive(Clone)]
struct AppState {
    mdns: Option<Arc<koi_mdns::MdnsCore>>,
    certmesh: Option<Arc<koi_certmesh::CertmeshCore>>,
    dns: Option<Arc<koi_dns::DnsRuntime>>,
    health: Option<Arc<koi_health::HealthRuntime>>,
    proxy: Option<Arc<koi_proxy::ProxyRuntime>>,
    udp: Option<Arc<koi_udp::UdpRuntime>>,
    runtime: Option<Arc<koi_runtime::RuntimeCore>>,
    started_at: std::time::Instant,
    cancel: CancellationToken,
    http_bind: String,
    /// Lazy mDNS meta-browse controller (when mDNS is enabled), so `/v1/status` can
    /// report whether LAN-wide browsing is currently active.
    mdns_browse: Option<Arc<LazyMetaBrowse>>,
}

// ── Entrypoint ──────────────────────────────────────────────────────

// Wiring entrypoint: it threads every daemon component through to the HTTP
// adapter. Pre-existing signature (P03); clippy 0.1.95 (> repo MSRV 1.92) newly
// flags the arg count. Behaviour-neutral allow to keep the gate green.
#[allow(clippy::too_many_arguments)]
pub async fn start(
    cores: DaemonCores,
    bind_ip: std::net::IpAddr,
    port: u16,
    cancel: CancellationToken,
    started_at: std::time::Instant,
    dashboard_state: DashboardState,
    browser_state: Option<BrowserState>,
    dat_token: String,
) -> anyhow::Result<()> {
    let app_state = AppState {
        mdns: cores.mdns.clone(),
        certmesh: cores.certmesh.clone(),
        dns: cores.dns.clone(),
        health: cores.health.clone(),
        proxy: cores.proxy.clone(),
        udp: cores.udp.clone(),
        runtime: cores.runtime.clone(),
        started_at,
        cancel: cancel.clone(),
        http_bind: bind_ip.to_string(),
        mdns_browse: browser_state.as_ref().map(|b| b.meta.clone()),
    };

    // ── Dashboard (always mounted) ──
    let mut app = Router::new()
        .route(paths::HEALTHZ, get(health))
        .route(paths::UNIFIED_STATUS, get(unified_status_handler))
        .route(paths::SHUTDOWN, post(shutdown_handler))
        .route(paths::HOST, get(host_handler))
        .route("/", get(koi_dashboard::dashboard::get_dashboard))
        .route(
            "/v1/dashboard/snapshot",
            get(koi_dashboard::dashboard::get_snapshot),
        )
        .route(
            "/v1/dashboard/events",
            get(koi_dashboard::dashboard::get_events),
        );

    // ── mDNS browser (conditional on mDNS being enabled) ──
    if let Some(bs) = browser_state {
        app = app
            .route("/mdns-browser", get(koi_dashboard::browser::get_page))
            .nest("/v1/mdns/browser", koi_dashboard::browser::routes(bs));
    } else {
        app = app.nest("/v1/mdns/browser", disabled_fallback_router("mdns-browser"));
    }

    // Mount domain routes or fallback routers
    if let Some(ref mdns_core) = cores.mdns {
        app = app.nest(
            koi_mdns::http::paths::PREFIX,
            koi_mdns::http::routes(mdns_core.clone()),
        );
    } else {
        app = app.nest(
            koi_mdns::http::paths::PREFIX,
            disabled_fallback_router("mdns"),
        );
    }

    if let Some(ref certmesh_core) = cores.certmesh {
        app = app.nest(koi_certmesh::http::paths::PREFIX, certmesh_core.routes());
    } else {
        app = app.nest(
            koi_certmesh::http::paths::PREFIX,
            disabled_fallback_router("certmesh"),
        );
    }

    if let Some(ref dns_runtime) = cores.dns {
        app = app.nest(
            koi_dns::http::paths::PREFIX,
            koi_dns::http::routes(dns_runtime.clone()),
        );
    } else {
        app = app.nest(
            koi_dns::http::paths::PREFIX,
            disabled_fallback_router("dns"),
        );
    }

    if let Some(ref health_runtime) = cores.health {
        app = app.nest(
            koi_health::http::paths::PREFIX,
            koi_health::http::routes(health_runtime.core()),
        );
    } else {
        app = app.nest(
            koi_health::http::paths::PREFIX,
            disabled_fallback_router("health"),
        );
    }

    if let Some(ref proxy_runtime) = cores.proxy {
        app = app.nest(
            koi_proxy::http::paths::PREFIX,
            koi_proxy::http::routes(proxy_runtime.clone()),
        );
    } else {
        app = app.nest(
            koi_proxy::http::paths::PREFIX,
            disabled_fallback_router("proxy"),
        );
    }

    if let Some(ref udp_runtime) = cores.udp {
        app = app.nest(
            koi_udp::http::paths::PREFIX,
            koi_udp::http::routes(udp_runtime.clone()),
        );
    } else {
        app = app.nest(
            koi_udp::http::paths::PREFIX,
            disabled_fallback_router("udp"),
        );
    }

    if let Some(ref runtime_core) = cores.runtime {
        app = app.nest(koi_runtime::http::paths::PREFIX, runtime_core.routes());
    } else {
        app = app.nest(
            koi_runtime::http::paths::PREFIX,
            disabled_fallback_router("runtime"),
        );
    }

    // OpenAPI spec - composed from domain-owned specs via nest()
    let openapi = build_openapi();

    // Serve interactive API docs at /docs and raw spec at /openapi.json
    app = app.merge(Scalar::with_url("/docs", openapi.clone()));
    let spec_json = match openapi.to_pretty_json() {
        Ok(json) => json,
        Err(e) => {
            tracing::error!(error = %e, "OpenAPI JSON serialization failed");
            String::from(r#"{"error":"OpenAPI serialization failed"}"#)
        }
    };
    app = app.route(
        "/openapi.json",
        get(move || {
            let json = spec_json.clone();
            async move {
                (
                    [(axum::http::header::CONTENT_TYPE, "application/json")],
                    json,
                )
            }
        }),
    );

    app = app.layer(Extension(app_state));
    app = app.layer(Extension(dashboard_state));

    // DAT auth middleware: mutation requests (non-GET/OPTIONS) require X-Koi-Token header.
    // Applied BEFORE CORS so it only sees real requests (CORS handles OPTIONS preflight).
    let shared_token = Arc::new(dat_token);
    app = app.layer(middleware::from_fn(move |req, next| {
        let token = Arc::clone(&shared_token);
        dat_auth_middleware(req, next, token)
    }));

    // CORS must be the LAST .layer() call (outermost) so OPTIONS preflight
    // is handled before auth middleware strips unauthenticated requests.
    let cors = CorsLayer::new()
        .allow_methods([
            axum::http::Method::GET,
            axum::http::Method::POST,
            axum::http::Method::PUT,
            axum::http::Method::DELETE,
            axum::http::Method::OPTIONS,
        ])
        .allow_headers([header::CONTENT_TYPE, HeaderName::from_static("x-koi-token")])
        .allow_origin(tower_http::cors::AllowOrigin::predicate(|origin, _| {
            let s = origin.to_str().unwrap_or("");
            s.starts_with("http://localhost") || s.starts_with("http://127.0.0.1")
        }));
    app = app.layer(cors);

    // Bind to the resolved address (loopback by default; see --http-bind).
    // Exposure does not relax auth — mutations still require the DAT token.
    let listener = tokio::net::TcpListener::bind((bind_ip, port)).await?;
    tracing::info!("HTTP adapter listening on {}:{}", bind_ip, port);

    axum::serve(listener, app)
        .with_graceful_shutdown(async move {
            cancel.cancelled().await;
        })
        .await?;

    tracing::debug!("HTTP adapter stopped");
    Ok(())
}

// ── Response types for top-level endpoints ──────────────────────────

#[derive(Debug, Serialize, ToSchema)]
struct UnifiedStatusResponse {
    version: String,
    platform: String,
    uptime_secs: u64,
    daemon: bool,
    /// The HTTP adapter's bind address (e.g. "127.0.0.1" or "0.0.0.0").
    http_bind: String,
    capabilities: Vec<koi_common::capability::CapabilityStatus>,
}

#[derive(Debug, Serialize, ToSchema)]
struct ShutdownResponse {
    status: String,
}

/// Host identity and network interfaces.
#[derive(Debug, Serialize, ToSchema)]
struct HostInfoResponse {
    /// Raw hostname (e.g. "stone-azure-pool").
    hostname: String,
    /// Fully-qualified mDNS name (e.g. "stone-azure-pool.local").
    hostname_fqdn: String,
    /// Operating system (e.g. "linux", "windows").
    os: String,
    /// CPU architecture (e.g. "x86_64", "aarch64").
    arch: String,
    /// Network interfaces grouped by category.
    interfaces: HostInterfaces,
}

/// Grouped network interfaces. Extensible — future categories (e.g. vpn)
/// can be added without breaking the schema.
#[derive(Debug, Serialize, ToSchema)]
struct HostInterfaces {
    /// LAN-routable interfaces (loopback and link-local excluded).
    lan: Vec<NetworkInterface>,
}

/// A single network interface.
#[derive(Debug, Serialize, ToSchema)]
struct NetworkInterface {
    /// Platform-specific interface name (e.g. "eth0", "Ethernet", "en0").
    name: String,
    /// IPv4 or IPv6 address.
    ip: String,
}

// ── System-level OpenAPI doc ─────────────────────────────────────────

/// System-level OpenAPI doc with paths for top-level endpoints and schemas.
#[derive(OpenApi)]
#[openapi(
    paths(health, unified_status_handler, shutdown_handler, host_handler),
    components(schemas(
        UnifiedStatusResponse,
        ShutdownResponse,
        HostInfoResponse,
        HostInterfaces,
        NetworkInterface,
        koi_common::capability::CapabilityStatus,
        koi_common::error::ErrorCode,
        koi_common::api::ErrorBody,
    ))
)]
struct KoiSchemas;

/// Build the full OpenAPI spec by composing domain-owned specs via `nest()`.
///
/// System-level paths (healthz, status, shutdown, host) come from `KoiSchemas`.
/// Each domain crate self-describes its API surface via `#[utoipa::path]` on
/// handlers and `paths(...)` in its `ApiDoc`. The `nest()` call prepends the
/// domain prefix to all paths.
pub fn build_openapi() -> utoipa::openapi::OpenApi {
    use utoipa::openapi::external_docs::ExternalDocs;
    use utoipa::openapi::tag::TagBuilder;
    use utoipa::openapi::{InfoBuilder, LicenseBuilder};

    let openapi = KoiSchemas::openapi()
        .nest(
            koi_mdns::http::paths::PREFIX,
            koi_mdns::http::MdnsApiDoc::openapi(),
        )
        .nest(
            koi_certmesh::http::paths::PREFIX,
            koi_certmesh::http::CertmeshApiDoc::openapi(),
        )
        .nest(
            koi_dns::http::paths::PREFIX,
            koi_dns::http::DnsApiDoc::openapi(),
        )
        .nest(
            koi_health::http::paths::PREFIX,
            koi_health::http::HealthApiDoc::openapi(),
        )
        .nest(
            koi_proxy::http::paths::PREFIX,
            koi_proxy::http::ProxyApiDoc::openapi(),
        )
        .nest(
            koi_udp::http::paths::PREFIX,
            koi_udp::http::UdpApiDoc::openapi(),
        )
        .nest(
            koi_runtime::http::paths::PREFIX,
            koi_runtime::http::RuntimeApiDoc::openapi(),
        );

    let info = InfoBuilder::new()
        .title("Koi Network Toolkit API")
        .version(env!("CARGO_PKG_VERSION"))
        .description(Some(
            "Local network toolkit: service discovery, DNS, health monitoring, \
             TLS proxy, and certificate mesh.",
        ))
        .license(Some(
            LicenseBuilder::new().name("Apache-2.0 OR MIT").build(),
        ))
        .build();

    let base = "https://github.com/sylin-org/koi/blob/main/docs";
    let tags = vec![
        TagBuilder::new()
            .name("system")
            .description(Some(
                "Core daemon lifecycle - status, version, health probes, \
                 and graceful shutdown.",
            ))
            .external_docs(Some(ExternalDocs::new(format!("{base}/guide-system.md"))))
            .build(),
        TagBuilder::new()
            .name("mdns")
            .description(Some(
                "Multicast DNS service discovery - announce, discover, \
                 and manage services on the local network. Includes \
                 admin operations for inspecting and controlling \
                 individual registrations.",
            ))
            .external_docs(Some(ExternalDocs::new(format!("{base}/guide-mdns.md"))))
            .build(),
        TagBuilder::new()
            .name("certmesh")
            .description(Some(
                "Zero-config TLS certificate mesh - automatic CA \
                 bootstrapping, certificate enrollment, renewal, \
                 revocation, and cluster-wide trust distribution.",
            ))
            .external_docs(Some(ExternalDocs::new(format!("{base}/guide-certmesh.md"))))
            .build(),
        TagBuilder::new()
            .name("dns")
            .description(Some(
                "Local DNS server - custom record management, \
                 upstream forwarding, and split-horizon resolution \
                 for development environments.",
            ))
            .external_docs(Some(ExternalDocs::new(format!("{base}/guide-dns.md"))))
            .build(),
        TagBuilder::new()
            .name("health")
            .description(Some(
                "Endpoint health monitoring - configure checks, \
                 view live status, and receive real-time health \
                 change events via SSE.",
            ))
            .external_docs(Some(ExternalDocs::new(format!("{base}/guide-health.md"))))
            .build(),
        TagBuilder::new()
            .name("proxy")
            .description(Some(
                "TLS-terminating reverse proxy - route traffic \
                 to local services with automatic certificate \
                 provisioning from the certmesh CA.",
            ))
            .external_docs(Some(ExternalDocs::new(format!("{base}/guide-proxy.md"))))
            .build(),
        TagBuilder::new()
            .name("udp")
            .description(Some(
                "UDP datagram bridging - bind host sockets, send \
                 and receive datagrams over HTTP/SSE.",
            ))
            .external_docs(Some(ExternalDocs::new(format!("{base}/guide-udp.md"))))
            .build(),
        TagBuilder::new()
            .name("runtime")
            .description(Some(
                "Runtime adapter - container and service lifecycle \
                 integration (Docker, Podman, systemd, Incus, Kubernetes).",
            ))
            .external_docs(Some(ExternalDocs::new(format!("{base}/guide-runtime.md"))))
            .build(),
    ];

    let mut openapi = openapi;
    openapi.info = info;
    openapi.tags = Some(tags);
    openapi
}

// ── DAT auth middleware ──────────────────────────────────────────────

/// Daemon Access Token (DAT) authentication middleware.
///
/// GET and OPTIONS requests are exempt (read-only, CORS preflight).
/// All other methods require a valid `x-koi-token` header.
/// Uses constant-time comparison to prevent timing attacks.
async fn dat_auth_middleware(
    req: Request<Body>,
    next: Next,
    expected_token: Arc<String>,
) -> Response {
    // GET, HEAD, and OPTIONS are exempt from auth.
    // HEAD is auto-matched to GET handlers by axum, so it must follow the same policy.
    let method = req.method().clone();
    if method == axum::http::Method::GET
        || method == axum::http::Method::HEAD
        || method == axum::http::Method::OPTIONS
    {
        return next.run(req).await;
    }

    // Check x-koi-token header with constant-time comparison.
    // The subtle crate guarantees constant-time execution regardless of length
    // difference, so no separate length check is needed.
    let authenticated = req
        .headers()
        .get(DAT_HEADER)
        .and_then(|val| val.to_str().ok())
        .map(|val| bool::from(val.as_bytes().ct_eq(expected_token.as_bytes())))
        .unwrap_or(false);

    if !authenticated {
        return (
            StatusCode::UNAUTHORIZED,
            axum::Json(serde_json::json!({
                "error": "unauthorized",
                "message": "Missing or invalid x-koi-token header"
            })),
        )
            .into_response();
    }

    next.run(req).await
}

// ── Handlers ────────────────────────────────────────────────────────

#[utoipa::path(get, path = "/healthz", tag = "system",
    summary = "Basic liveness probe",
    responses((status = 200, description = "Daemon is alive")))]
async fn health() -> &'static str {
    "OK"
}

#[utoipa::path(get, path = "/v1/status", tag = "system",
    summary = "Unified capability status",
    responses((status = 200, body = UnifiedStatusResponse)))]
async fn unified_status_handler(Extension(state): Extension<AppState>) -> Json<serde_json::Value> {
    // The capability ladder is assembled once in koi-compose, shared with the dashboard and
    // embedded snapshots. `/v1/status` emits just the status (no `enabled` field).
    let cores = crate::DaemonCores {
        mdns: state.mdns.clone(),
        certmesh: state.certmesh.clone(),
        dns: state.dns.clone(),
        health: state.health.clone(),
        proxy: state.proxy.clone(),
        udp: state.udp.clone(),
        runtime: state.runtime.clone(),
    };
    let capabilities: Vec<koi_common::capability::CapabilityStatus> =
        koi_compose::status::assemble_capabilities(&cores)
            .await
            .into_iter()
            .map(|c| c.status)
            .collect();

    let uptime_secs = state.started_at.elapsed().as_secs();
    Json(serde_json::json!({
        "version": env!("CARGO_PKG_VERSION"),
        "platform": std::env::consts::OS,
        "uptime_secs": uptime_secs,
        "daemon": true,
        "http_bind": state.http_bind,
        "mdns_browse_active": state.mdns_browse.as_ref().map(|m| m.is_active()),
        "capabilities": capabilities,
    }))
}

/// LAN interfaces for the `/v1/host` response: the interface that owns the
/// default route (matched by its source IP), or — failing that — every
/// non-loopback, non-link-local IPv4 interface.
fn default_lan_interfaces() -> Vec<NetworkInterface> {
    let all = if_addrs::get_if_addrs().unwrap_or_default();

    if let Some(ip) = default_route_ipv4() {
        if let Some(iface) = all.iter().find(|i| i.addr.ip() == std::net::IpAddr::V4(ip)) {
            return vec![NetworkInterface {
                name: iface.name.clone(),
                ip: ip.to_string(),
            }];
        }
    }

    all.into_iter()
        .filter(|iface| !iface.is_loopback())
        .filter_map(|iface| match iface.addr.ip() {
            std::net::IpAddr::V4(v4) if !v4.is_link_local() => Some(NetworkInterface {
                name: iface.name,
                ip: v4.to_string(),
            }),
            _ => None,
        })
        .collect()
}

/// The IPv4 source address the OS would use to reach the public internet — i.e.
/// the address of the default-route interface. A UDP socket "connected" to a
/// public IP sends no traffic; it only makes the kernel resolve its
/// source-address choice, which `local_addr()` then reports. Returns `None`
/// when there is no usable default route.
fn default_route_ipv4() -> Option<std::net::Ipv4Addr> {
    let sock = std::net::UdpSocket::bind(("0.0.0.0", 0)).ok()?;
    sock.connect(("8.8.8.8", 80)).ok()?;
    match sock.local_addr().ok()?.ip() {
        std::net::IpAddr::V4(v4) if !v4.is_unspecified() => Some(v4),
        _ => None,
    }
}

#[utoipa::path(get, path = "/v1/host", tag = "system",
    summary = "Host identity and network interfaces",
    responses((status = 200, body = HostInfoResponse)))]
async fn host_handler() -> Json<HostInfoResponse> {
    let raw = hostname::get()
        .ok()
        .and_then(|os| os.into_string().ok())
        .unwrap_or_else(|| "unknown".to_string());
    let fqdn = format!("{}.local", raw);

    // Identify the interface that owns the default route — the real LAN adapter
    // even on Windows, where virtual switches (vEthernet) share the physical
    // Ethernet IfType. We use the kernel's own route selection rather than a
    // network-enumeration crate (see `default_lan_interfaces`).
    let lan = default_lan_interfaces();

    Json(HostInfoResponse {
        hostname: raw,
        hostname_fqdn: fqdn,
        os: std::env::consts::OS.to_string(),
        arch: std::env::consts::ARCH.to_string(),
        interfaces: HostInterfaces { lan },
    })
}

#[utoipa::path(post, path = "/v1/admin/shutdown", tag = "system",
    summary = "Request graceful daemon shutdown",
    responses((status = 200, body = ShutdownResponse)))]
async fn shutdown_handler(Extension(state): Extension<AppState>) -> Json<serde_json::Value> {
    tracing::info!("Shutdown requested via admin endpoint");
    state.cancel.cancel();
    Json(serde_json::json!({ "status": "shutting_down" }))
}

/// Returns a router that responds 503 for any request to a disabled capability.
fn disabled_fallback_router(capability_name: &'static str) -> Router {
    Router::new().fallback(move || async move {
        let body = serde_json::json!({
            "error": "capability_disabled",
            "message": format!(
                "The '{}' capability is disabled on this daemon.",
                capability_name
            ),
        });
        (
            axum::http::StatusCode::SERVICE_UNAVAILABLE,
            axum::Json(body),
        )
    })
}

#[cfg(test)]
mod tests {
    use super::*;
    use axum::body::Body;
    use axum::http::Request;
    use tower::ServiceExt;

    #[tokio::test]
    async fn disabled_fallback_returns_503() {
        let app = disabled_fallback_router("mdns");
        let req = Request::get("/browse").body(Body::empty()).unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::SERVICE_UNAVAILABLE);
    }

    #[tokio::test]
    async fn disabled_fallback_body_has_error_field() {
        let app = disabled_fallback_router("certmesh");
        let req = Request::get("/status").body(Body::empty()).unwrap();
        let resp = app.oneshot(req).await.unwrap();
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        assert_eq!(json.get("error").unwrap(), "capability_disabled");
    }

    #[tokio::test]
    async fn disabled_fallback_message_includes_capability_name() {
        let app = disabled_fallback_router("mdns");
        let req = Request::get("/any").body(Body::empty()).unwrap();
        let resp = app.oneshot(req).await.unwrap();
        let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
            .await
            .unwrap();
        let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
        let msg = json.get("message").unwrap().as_str().unwrap();
        assert!(
            msg.contains("mdns"),
            "message should contain capability name: {msg}"
        );
    }

    #[tokio::test]
    async fn disabled_fallback_works_for_post() {
        let app = disabled_fallback_router("certmesh");
        let req = Request::post("/join").body(Body::empty()).unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::SERVICE_UNAVAILABLE);
    }

    // ── DAT auth: --http-bind exposure must never relax authentication ──
    // The token requirement is independent of the bind address, so these
    // wrap the exact production middleware and assert the policy directly.

    /// Minimal router applying the production `dat_auth_middleware`.
    fn dat_test_router(token: &str) -> Router {
        let expected = Arc::new(token.to_string());
        Router::new()
            .route("/probe", get(|| async { "ok" }).post(|| async { "ok" }))
            .layer(middleware::from_fn(move |req, next| {
                let expected = expected.clone();
                dat_auth_middleware(req, next, expected)
            }))
    }

    #[tokio::test]
    async fn get_is_exempt_from_dat_auth() {
        let app = dat_test_router("secret-token");
        let req = Request::get("/probe").body(Body::empty()).unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
    }

    #[tokio::test]
    async fn post_without_token_is_rejected() {
        let app = dat_test_router("secret-token");
        let req = Request::post("/probe").body(Body::empty()).unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::UNAUTHORIZED);
    }

    #[tokio::test]
    async fn post_with_valid_token_is_accepted() {
        let app = dat_test_router("secret-token");
        let req = Request::post("/probe")
            .header(DAT_HEADER, "secret-token")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::OK);
    }

    #[tokio::test]
    async fn post_with_wrong_token_is_rejected() {
        let app = dat_test_router("secret-token");
        let req = Request::post("/probe")
            .header(DAT_HEADER, "wrong-token")
            .body(Body::empty())
            .unwrap();
        let resp = app.oneshot(req).await.unwrap();
        assert_eq!(resp.status(), axum::http::StatusCode::UNAUTHORIZED);
    }

    #[test]
    fn openapi_spec_contains_system_paths() {
        let spec = build_openapi();
        let paths: Vec<&str> = spec.paths.paths.keys().map(|k| k.as_str()).collect();
        assert!(paths.contains(&"/healthz"), "missing /healthz: {paths:?}");
        assert!(
            paths.contains(&"/v1/status"),
            "missing /v1/status: {paths:?}"
        );
        assert!(paths.contains(&"/v1/host"), "missing /v1/host: {paths:?}");
        assert!(
            paths.contains(&"/v1/admin/shutdown"),
            "missing /v1/admin/shutdown: {paths:?}"
        );
    }

    #[test]
    fn openapi_spec_contains_domain_paths() {
        let spec = build_openapi();
        let paths: Vec<&str> = spec.paths.paths.keys().map(|k| k.as_str()).collect();
        // Spot-check one path per domain to verify nest() prefixing works
        assert!(
            paths.contains(&"/v1/mdns/discover"),
            "missing /v1/mdns/discover: {paths:?}"
        );
        assert!(
            paths.contains(&"/v1/dns/status"),
            "missing /v1/dns/status: {paths:?}"
        );
        assert!(
            paths.contains(&"/v1/health/status"),
            "missing /v1/health/status: {paths:?}"
        );
        assert!(
            paths.contains(&"/v1/proxy/status"),
            "missing /v1/proxy/status: {paths:?}"
        );
        assert!(
            paths.contains(&"/v1/certmesh/status"),
            "missing /v1/certmesh/status: {paths:?}"
        );
        assert!(
            paths.contains(&"/v1/udp/status"),
            "missing /v1/udp/status: {paths:?}"
        );
    }

    #[tokio::test]
    async fn host_handler_returns_default_interface_only() {
        let Json(resp) = host_handler().await;
        assert!(!resp.hostname.is_empty(), "hostname should not be empty");
        assert!(
            resp.hostname_fqdn.ends_with(".local"),
            "FQDN should end with .local: {}",
            resp.hostname_fqdn
        );
        // The LAN list should contain exactly the default-route interface
        // (not virtual switches, Docker bridges, etc.)
        assert!(
            !resp.interfaces.lan.is_empty(),
            "lan interfaces should not be empty on a machine with network"
        );
        for iface in &resp.interfaces.lan {
            let ip: std::net::IpAddr = iface.ip.parse().expect("should be a valid IP");
            assert!(!ip.is_loopback(), "LAN should not contain loopback");
        }
        // On a machine with a single physical NIC, expect exactly 1 entry
        println!(
            "host_handler returned {} LAN interface(s):",
            resp.interfaces.lan.len()
        );
        for iface in &resp.interfaces.lan {
            println!("  {} -> {}", iface.name, iface.ip);
        }
    }
}