koi-embedded 0.4.1

Embed local network discovery, DNS, health, and TLS directly in your Rust application
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
//! Embedded HTTP adapter - lightweight axum server for koi-embedded.
//!
//! When `http_enabled` is set on the builder, this module spins up a
//! HTTP server that mounts domain routes, system-level endpoints
//! (`/v1/status`, `/v1/host`), and optional dashboard, mDNS browser,
//! and OpenAPI docs.  Admin shutdown is not included.

use std::sync::Arc;

use axum::extract::Extension;
use axum::http::{header, HeaderValue, Method};
use axum::response::Json;
use axum::routing::get;
use axum::Router;
use serde::Serialize;
use tokio_util::sync::CancellationToken;
use tower_http::cors::CorsLayer;
use utoipa::{OpenApi, ToSchema};
use utoipa_scalar::{Scalar, Servable};

use koi_dashboard::browser::BrowserState;
use koi_dashboard::dashboard::DashboardState;

// ── Embedded app state for system-level handlers ────────────────────

#[derive(Clone)]
struct EmbeddedState {
    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,
}

/// Start the embedded HTTP server.
///
/// Mounts `/healthz` plus each enabled domain's routes at their standard
/// prefix (e.g., `/v1/mdns`, `/v1/dns`, `/v1/health`, `/v1/proxy`,
/// `/v1/certmesh`).  Disabled capabilities get a 503 fallback router.
///
/// When `dashboard_state` is `Some`, the dashboard SPA and its
/// snapshot/events endpoints are mounted at `/` and `/v1/dashboard/`.
///
/// When `browser_state` is `Some`, the mDNS browser SPA and its
/// snapshot/events endpoints are mounted at `/mdns-browser` and
/// `/v1/mdns/browser/`.
///
/// The server shuts down when `cancel` is cancelled.
#[allow(clippy::too_many_arguments)]
pub(crate) async fn serve(
    port: u16,
    mdns: Option<Arc<koi_mdns::MdnsCore>>,
    dns: Option<Arc<koi_dns::DnsRuntime>>,
    health: Option<Arc<koi_health::HealthRuntime>>,
    certmesh: Option<Arc<koi_certmesh::CertmeshCore>>,
    proxy: Option<Arc<koi_proxy::ProxyRuntime>>,
    udp: Option<Arc<koi_udp::UdpRuntime>>,
    runtime: Option<Arc<koi_runtime::RuntimeCore>>,
    dashboard_state: Option<DashboardState>,
    browser_state: Option<BrowserState>,
    api_docs_enabled: bool,
    cancel: CancellationToken,
) {
    let embedded_state = EmbeddedState {
        mdns: mdns.clone(),
        certmesh: certmesh.clone(),
        dns: dns.clone(),
        health: health.clone(),
        proxy: proxy.clone(),
        udp: udp.clone(),
        runtime: runtime.clone(),
        started_at: std::time::Instant::now(),
    };

    let mut app = Router::new()
        .route("/healthz", get(healthz))
        .route("/v1/status", get(status_handler))
        .route("/v1/host", get(host_handler));

    // ── Dashboard (opt-in) ───────────────────────────────────────

    if let Some(ref ds) = dashboard_state {
        app = app
            .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),
            )
            .layer(Extension(ds.clone()));
    }

    // ── mDNS browser (opt-in) ────────────────────────────────────

    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));
    }

    // ── Domain routes ────────────────────────────────────────────

    if let Some(ref core) = mdns {
        app = app.nest(
            koi_mdns::http::paths::PREFIX,
            koi_mdns::http::routes(core.clone()),
        );
    } else {
        app = app.nest(koi_mdns::http::paths::PREFIX, disabled_fallback("mdns"));
    }

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

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

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

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

    if let Some(ref udp_runtime) = 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("udp"));
    }

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

    // ── OpenAPI docs (opt-in) ────────────────────────────────────

    if api_docs_enabled {
        let openapi = build_embedded_openapi(&mdns, &dns, &health, &certmesh, &proxy, &udp);
        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(embedded_state));
    let cors = CorsLayer::new()
        .allow_origin([
            HeaderValue::from_static("http://localhost"),
            HeaderValue::from_static("http://127.0.0.1"),
        ])
        .allow_methods([Method::GET, Method::POST, Method::PUT, Method::DELETE])
        .allow_headers([header::CONTENT_TYPE]);
    app = app.layer(cors);

    // ── Bind & serve ─────────────────────────────────────────────

    let listener = match tokio::net::TcpListener::bind(("0.0.0.0", port)).await {
        Ok(l) => l,
        Err(e) => {
            tracing::error!(port, error = %e, "Failed to bind embedded HTTP server");
            return;
        }
    };

    tracing::info!(port, "Embedded HTTP adapter listening");

    if let Err(e) = axum::serve(listener, app)
        .with_graceful_shutdown(async move {
            cancel.cancelled().await;
        })
        .await
    {
        tracing::error!(error = %e, "Embedded HTTP adapter error");
    }

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

/// Liveness probe - matches standalone `/healthz`.
async fn healthz() -> &'static str {
    "OK"
}

// ── System-level response types ─────────────────────────────────────

#[derive(Debug, Serialize, ToSchema)]
struct StatusResponse {
    version: String,
    platform: String,
    uptime_secs: u64,
    daemon: bool,
    capabilities: Vec<koi_common::capability::CapabilityStatus>,
}

#[derive(Debug, Serialize, ToSchema)]
struct HostInfoResponse {
    hostname: String,
    hostname_fqdn: String,
    os: String,
    arch: String,
    interfaces: HostInterfaces,
}

#[derive(Debug, Serialize, ToSchema)]
struct HostInterfaces {
    lan: Vec<NetworkInterface>,
}

#[derive(Debug, Serialize, ToSchema)]
struct NetworkInterface {
    name: String,
    ip: String,
}

// ── System-level handlers ───────────────────────────────────────────

async fn status_handler(Extension(state): Extension<EmbeddedState>) -> Json<StatusResponse> {
    use koi_common::capability::{Capability, CapabilityStatus};

    let mut capabilities = Vec::new();

    if let Some(ref core) = state.mdns {
        capabilities.push(core.status());
    } else {
        capabilities.push(CapabilityStatus {
            name: "mdns".to_string(),
            summary: "disabled".to_string(),
            healthy: false,
        });
    }

    if let Some(ref core) = state.certmesh {
        capabilities.push(core.status());
    } else {
        capabilities.push(CapabilityStatus {
            name: "certmesh".to_string(),
            summary: "disabled".to_string(),
            healthy: false,
        });
    }

    if let Some(ref runtime) = state.dns {
        let running = runtime.status().await.running;
        if running {
            capabilities.push(runtime.core().status());
        } else {
            capabilities.push(CapabilityStatus {
                name: "dns".to_string(),
                summary: "stopped".to_string(),
                healthy: false,
            });
        }
    } else {
        capabilities.push(CapabilityStatus {
            name: "dns".to_string(),
            summary: "disabled".to_string(),
            healthy: false,
        });
    }

    if let Some(ref runtime) = state.health {
        let running = runtime.status().await.running;
        if running {
            capabilities.push(runtime.core().status());
        } else {
            capabilities.push(CapabilityStatus {
                name: "health".to_string(),
                summary: "stopped".to_string(),
                healthy: false,
            });
        }
    } else {
        capabilities.push(CapabilityStatus {
            name: "health".to_string(),
            summary: "disabled".to_string(),
            healthy: false,
        });
    }

    if let Some(ref runtime) = state.proxy {
        let status = runtime.status().await;
        capabilities.push(CapabilityStatus {
            name: "proxy".to_string(),
            summary: if status.is_empty() {
                "no listeners".to_string()
            } else {
                format!("{} listeners", status.len())
            },
            healthy: true,
        });
    } else {
        capabilities.push(CapabilityStatus {
            name: "proxy".to_string(),
            summary: "disabled".to_string(),
            healthy: false,
        });
    }

    if let Some(ref udp_runtime) = state.udp {
        capabilities.push(Capability::status(udp_runtime.as_ref()));
    } else {
        capabilities.push(CapabilityStatus {
            name: "udp".to_string(),
            summary: "disabled".to_string(),
            healthy: false,
        });
    }

    if let Some(ref rt) = state.runtime {
        capabilities.push(rt.capability_status().await);
    } else {
        capabilities.push(CapabilityStatus {
            name: "runtime".to_string(),
            summary: "disabled".to_string(),
            healthy: false,
        });
    }

    Json(StatusResponse {
        version: env!("CARGO_PKG_VERSION").to_string(),
        platform: std::env::consts::OS.to_string(),
        uptime_secs: state.started_at.elapsed().as_secs(),
        daemon: false,
        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,
    }
}

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!("{raw}.local");

    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 },
    })
}

/// Build an OpenAPI spec reflecting only the enabled domains.
fn build_embedded_openapi(
    mdns: &Option<Arc<koi_mdns::MdnsCore>>,
    dns: &Option<Arc<koi_dns::DnsRuntime>>,
    health: &Option<Arc<koi_health::HealthRuntime>>,
    certmesh: &Option<Arc<koi_certmesh::CertmeshCore>>,
    proxy: &Option<Arc<koi_proxy::ProxyRuntime>>,
    udp: &Option<Arc<koi_udp::UdpRuntime>>,
) -> utoipa::openapi::OpenApi {
    use utoipa::openapi::{InfoBuilder, LicenseBuilder, PathsBuilder};

    let info = InfoBuilder::new()
        .title("Koi Embedded API")
        .version(env!("CARGO_PKG_VERSION"))
        .description(Some(
            "Embedded Koi 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 mut openapi = utoipa::openapi::OpenApi::new(info, PathsBuilder::new());

    if mdns.is_some() {
        openapi = openapi.nest(
            koi_mdns::http::paths::PREFIX,
            koi_mdns::http::MdnsApiDoc::openapi(),
        );
    }
    if certmesh.is_some() {
        openapi = openapi.nest(
            koi_certmesh::http::paths::PREFIX,
            koi_certmesh::http::CertmeshApiDoc::openapi(),
        );
    }
    if dns.is_some() {
        openapi = openapi.nest(
            koi_dns::http::paths::PREFIX,
            koi_dns::http::DnsApiDoc::openapi(),
        );
    }
    if health.is_some() {
        openapi = openapi.nest(
            koi_health::http::paths::PREFIX,
            koi_health::http::HealthApiDoc::openapi(),
        );
    }
    if proxy.is_some() {
        openapi = openapi.nest(
            koi_proxy::http::paths::PREFIX,
            koi_proxy::http::ProxyApiDoc::openapi(),
        );
    }
    if udp.is_some() {
        openapi = openapi.nest(
            koi_udp::http::paths::PREFIX,
            koi_udp::http::UdpApiDoc::openapi(),
        );
    }

    openapi
}

/// 503 fallback for disabled capabilities.
fn disabled_fallback(capability: &'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 instance.",
                capability
            ),
        });
        (
            axum::http::StatusCode::SERVICE_UNAVAILABLE,
            axum::Json(body),
        )
    })
}