bindcar 0.8.2

HTTP REST API for managing BIND9 zones via rndc
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
// Copyright (c) 2025 Erick Bourgeois, firestoned
// SPDX-License-Identifier: MIT

//! BIND9 RNDC API Server
//!
//! Supports two operating modes selected via subcommand:
//!
//! - `bindcar run` (default) — sidecar mode alongside a local BIND9 instance
//! - `bindcar drone` — standalone mode managing a remote BIND9 instance

use anyhow::Context;
use axum::{
    extract::State,
    http::StatusCode,
    middleware as axum_middleware,
    response::{IntoResponse, Response},
    routing::{get, post},
    Json, Router,
};
use clap::Parser;
use serde::Serialize;
use std::net::SocketAddr;
#[cfg(feature = "tls")]
use std::sync::Arc as StdArc;
use std::sync::Arc;
use tower_http::trace::TraceLayer;
use tracing::{debug, error, info, warn};
use utoipa::OpenApi;
use utoipa_swagger_ui::SwaggerUi;

// Import from the library
#[cfg(feature = "tls")]
use axum::extract::ConnectInfo;
#[cfg(feature = "tls")]
use bindcar::tls::TlsReloader;
use bindcar::tls::{scheme_for, TlsSettings, DEFAULT_RELOAD_INTERVAL_SECS};
use bindcar::{
    auth::authenticate,
    cli::{Cli, Commands},
    metrics, middleware,
    rate_limit::RateLimitConfig,
    rndc::RndcExecutor,
    types::{AppState, ErrorResponse},
    zones,
};
#[cfg(feature = "tls")]
use tower::Service as _;
use tower_governor::{
    governor::GovernorConfigBuilder, key_extractor::PeerIpKeyExtractor, GovernorLayer,
};

/// Crate version used by both the OpenAPI info block and health endpoint.
const VERSION: &str = env!("CARGO_PKG_VERSION");

/// Whether this binary was compiled with the `tls` feature.
const TLS_SUPPORTED: bool = cfg!(feature = "tls");

/// Refuse to start when TLS was configured but is not compiled in.
///
/// The same fail-closed reasoning as the runtime TLS config, extended to
/// compile-time capability: quietly ignoring `--tls-cert` would serve plaintext
/// on a deployment whose operator believes TLS is on. The flags are always
/// accepted by the parser so this produces an actionable error rather than an
/// "unknown argument".
///
/// # Arguments
/// * `tls_requested` - whether any TLS option was supplied
/// * `tls_supported` - whether this build has the `tls` feature
///
/// # Errors
/// Returns an error naming the missing feature when TLS was requested but the
/// binary cannot provide it.
fn check_tls_support(tls_requested: bool, tls_supported: bool) -> anyhow::Result<()> {
    if tls_requested && !tls_supported {
        anyhow::bail!(
            "TLS options were supplied but this bindcar binary was built without the \
`tls` feature, so it can only serve plaintext. Rebuild with `--features tls` \
(it is enabled by default), or remove the TLS options to serve plaintext deliberately."
        );
    }
    Ok(())
}

/// OpenAPI documentation structure
#[derive(OpenApi)]
#[openapi(
    paths(
        zones::create_zone,
        zones::delete_zone,
        zones::modify_zone,
        zones::reload_zone,
        zones::zone_status,
        zones::get_zone_ds,
        zones::checkds_zone,
        zones::freeze_zone,
        zones::thaw_zone,
        zones::notify_zone,
        zones::retransfer_zone,
        zones::server_status,
        zones::list_zones,
        zones::get_zone,
        bindcar::records::add_record,
        bindcar::records::remove_record,
        bindcar::records::update_record,
    ),
    components(
        schemas(
            zones::CreateZoneRequest,
            zones::ModifyZoneRequest,
            zones::ZoneResponse,
            zones::ZoneStatusResponse,
            zones::DsSetResponse,
            zones::DsRecordView,
            zones::CheckdsRequest,
            bindcar::dnssec::DnssecStatus,
            bindcar::dnssec::DnssecKeyStatus,
            bindcar::dnssec::CheckdsState,
            zones::ServerStatusResponse,
            zones::ZoneInfo,
            zones::ZoneListResponse,
            zones::ZoneConfig,
            zones::SoaRecord,
            zones::DnsRecord,
            bindcar::records::AddRecordRequest,
            bindcar::records::RemoveRecordRequest,
            bindcar::records::UpdateRecordRequest,
            bindcar::records::RecordResponse,
        )
    ),
    tags(
        (name = "zones", description = "Zone management endpoints"),
        (name = "records", description = "DNS record management endpoints"),
        (name = "server", description = "Server status endpoints")
    ),
    info(
        title = "Bindcar API",
        version = VERSION,
        description = "HTTP REST API for managing BIND9 zones and DNS records via RNDC and nsupdate",
        license(name = "MIT")
    )
)]
struct ApiDoc;

/// Server configuration
const DEFAULT_BIND_ZONE_DIR: &str = "/var/cache/bind";
const DEFAULT_API_PORT: u16 = 8080;
const DEFAULT_BIND_API_ADDRESS: &str = "0.0.0.0";

/// Health check response
#[derive(Serialize)]
struct HealthResponse {
    status: String,
    version: String,
}

/// Readiness check response
#[derive(Serialize)]
struct ReadyResponse {
    ready: bool,
    checks: Vec<String>,
}

/// Health check endpoint
async fn health_check() -> Json<HealthResponse> {
    Json(HealthResponse {
        status: "healthy".to_string(),
        version: VERSION.to_string(),
    })
}

/// Map a readiness sub-check outcome to a non-sensitive status token.
///
/// `/health`, `/ready`, and `/metrics` are intentionally unauthenticated (for
/// kubelet probes and Prometheus scraping), so their responses must never carry
/// internal detail. This emits only `"<name>: ok"` / `"<name>: error"` — the
/// underlying path or backend error text is logged server-side instead, never
/// returned to the caller.
fn ready_check_label(name: &str, ok: bool) -> String {
    format!("{}: {}", name, if ok { "ok" } else { "error" })
}

/// Metrics endpoint for Prometheus scraping
async fn metrics_handler() -> Response {
    match metrics::gather_metrics() {
        Ok(metrics_text) => (
            StatusCode::OK,
            [("Content-Type", "text/plain; version=0.0.4")],
            metrics_text,
        )
            .into_response(),
        Err(e) => {
            // Log the detail; return a generic message (this endpoint is
            // unauthenticated, so the body must not leak internals).
            error!("failed to gather metrics: {}", e);
            (
                StatusCode::INTERNAL_SERVER_ERROR,
                Json(ErrorResponse {
                    error: "Failed to gather metrics".to_string(),
                    details: None,
                }),
            )
                .into_response()
        }
    }
}

/// Probes the zone directory for the readiness endpoint.
///
/// Returns `true` only when `zone_dir` is a normalized absolute path that
/// exists and is a directory. The path and any IO error are logged
/// server-side and never returned to the caller — `/api/v1/ready` is
/// unauthenticated and must not disclose the filesystem layout.
///
/// # Arguments
/// * `zone_dir` - The configured zone directory (`BIND_ZONE_DIR`)
///
/// # Returns
/// `true` if the directory is usable, `false` otherwise. Never panics and
/// never propagates an error.
///
/// # Security
/// Defense-in-depth barrier for CodeQL `rust/path-injection`. `zone_dir` is
/// canonicalized once at startup (`zones::resolve_zone_dir`) and is operator
/// config, never HTTP input — but it reaches the handler through the axum
/// `State` extractor, which CodeQL models as untrusted. The guard therefore
/// re-asserts the startup invariant (absolute, no `..`/`.` components)
/// immediately before the `tokio::fs::metadata` sink.
///
/// The shape matters as much as the check: CodeQL's barrier guard is
/// intra-procedural and only takes effect when the guard is an early return
/// leaving the sink in straight-line code — the same shape used by
/// `zones::list_zones` before its `read_dir` sink. Expressing this as
/// `if bad { false } else { ...metadata()... }` inside `ready_check` did *not*
/// sanitize the flow (code-scanning alert #7 on PR #114). Do not inline this
/// helper back into `ready_check` or convert the guard to an if/else.
async fn probe_zone_dir(zone_dir: &str) -> bool {
    if !zones::is_normalized_zone_dir(zone_dir) || zone_dir.contains("..") {
        warn!(
            "zone directory {:?} is not a normalized absolute path; refusing to probe it",
            zone_dir
        );
        return false;
    }

    let metadata = match tokio::fs::metadata(zone_dir).await {
        Ok(metadata) => metadata,
        Err(e) => {
            warn!("zone directory {:?} not accessible: {}", zone_dir, e);
            return false;
        }
    };

    if !metadata.is_dir() {
        warn!("zone directory {:?} is not a directory", zone_dir);
        return false;
    }

    true
}

/// Readiness check endpoint
async fn ready_check(State(state): State<AppState>) -> Json<ReadyResponse> {
    let mut checks = Vec::new();
    let mut ready = true;

    // Check the zone directory. The response carries only ok/error; the path and
    // any IO error are logged server-side, never returned (the endpoint is
    // unauthenticated and must not disclose the filesystem layout).
    let zone_dir_ok = probe_zone_dir(&state.zone_dir).await;
    ready &= zone_dir_ok;
    checks.push(ready_check_label("zone_dir", zone_dir_ok));

    // Check if rndc is available. The backend error is logged, not returned.
    let rndc_ok = match state.rndc.status().await {
        Ok(_) => true,
        Err(e) => {
            warn!("RNDC not ready: {}", e);
            false
        }
    };
    ready &= rndc_ok;
    checks.push(ready_check_label("rndc", rndc_ok));

    Json(ReadyResponse { ready, checks })
}

#[tokio::main]
async fn main() -> anyhow::Result<()> {
    let cli = Cli::parse();
    init_tracing(cli.debug);

    // The insecure-auth override may come from the CLI flag or an env var (the
    // latter is convenient for container deployments without changing args).
    let insecure_override = cli.i_know_this_is_insecure
        || std::env::var("BINDCAR_ALLOW_INSECURE_AUTH")
            .ok()
            .and_then(|v| v.parse::<bool>().ok())
            .unwrap_or(false);

    // Refuse loudly if TLS was asked for but this build cannot provide it,
    // before anything binds.
    let tls_requested =
        cli.tls_cert.is_some() || cli.tls_key.is_some() || cli.tls_client_ca.is_some();
    check_tls_support(tls_requested, TLS_SUPPORTED)?;

    // Resolve the TLS transport config before anything binds. A half-configured
    // listener is fatal here rather than a silent downgrade to plaintext.
    let tls_settings = bindcar::tls::resolve_tls_settings(
        cli.tls_cert.clone(),
        cli.tls_key.clone(),
        cli.tls_client_ca.clone(),
    )
    .context("invalid TLS configuration")?;

    let reload_interval = cli
        .tls_reload_interval
        .unwrap_or(DEFAULT_RELOAD_INTERVAL_SECS);

    start_server(
        cli.resolved_command(),
        insecure_override,
        tls_settings,
        reload_interval,
    )
    .await
}

fn init_tracing(debug: bool) {
    let filter = if debug {
        tracing_subscriber::EnvFilter::new("debug")
    } else {
        tracing_subscriber::EnvFilter::try_from_default_env()
            .unwrap_or_else(|_| tracing_subscriber::EnvFilter::new("info"))
    };

    tracing_subscriber::fmt()
        .with_env_filter(filter)
        .json()
        .init();
}

async fn start_server(
    command: &Commands,
    insecure_override: bool,
    tls_settings: Option<TlsSettings>,
    tls_reload_interval: u64,
) -> anyhow::Result<()> {
    match command {
        Commands::Run => info!("starting bindcar v{} [sidecar mode]", VERSION),
        Commands::Drone => info!(
            "starting bindcar v{} [drone mode] - standalone, managing remote BIND9",
            VERSION
        ),
    }

    // initialize metrics
    metrics::init_metrics();

    // get configuration from environment
    let zone_dir =
        std::env::var("BIND_ZONE_DIR").unwrap_or_else(|_| DEFAULT_BIND_ZONE_DIR.to_string());
    let api_port = std::env::var("API_PORT")
        .ok()
        .and_then(|p| p.parse().ok())
        .unwrap_or(DEFAULT_API_PORT);
    let bind_host =
        std::env::var("BIND_API_ADDRESS").unwrap_or_else(|_| DEFAULT_BIND_API_ADDRESS.to_string());
    let disable_auth = std::env::var("DISABLE_AUTH")
        .ok()
        .and_then(|v| v.parse::<bool>().ok())
        .unwrap_or(false);

    info!("zone directory: {}", zone_dir);
    info!("api address: {}:{}", bind_host, api_port);
    // Startup guard (B-4): never silently expose an unauthenticated or
    // presence-only API on a non-loopback interface. Requires real auth
    // (TokenReview feature or BIND_API_TOKEN), a loopback bind, or an explicit
    // operator override.
    if let Err(e) = bindcar::auth::check_startup_auth_posture(
        !disable_auth,
        bindcar::auth::has_real_auth(),
        &bind_host,
        insecure_override,
    ) {
        error!("{}", e);
        return Err(anyhow::anyhow!(e));
    }

    if disable_auth {
        warn!("⚠️  authentication is disabled - api endpoints are unprotected!");
        warn!("⚠️  this should only be used in trusted environments (e.g., linkerd service mesh)");
    } else {
        info!("authentication is enabled");
        if std::env::var(bindcar::auth::BIND_API_TOKEN_ENV)
            .map(|v| !v.is_empty())
            .unwrap_or(false)
        {
            info!("shared-secret API token authentication is active (BIND_API_TOKEN)");
        }

        #[cfg(feature = "k8s-token-review")]
        {
            use bindcar::auth::{
                check_authorization_posture, detect_kube_auth_mode, shared_secret_configured,
                KubeAuthMode, TokenReviewConfig, ALLOW_ANY_SERVICE_ACCOUNT_ENV,
            };

            // TokenReview and shared-secret auth are mutually exclusive: a
            // configured shared secret (BIND_API_TOKEN) selects shared-secret
            // mode, in which TokenReview is never consulted at request time
            // (see auth::authenticate). Only enforce the fail-closed TokenReview
            // authorization posture (A2) when TokenReview is the active mode.
            if shared_secret_configured() {
                info!("auth mode: shared-secret (BIND_API_TOKEN) — Kubernetes TokenReview is not active");
            } else {
                // Fail-closed authorization posture (A2): with TokenReview active
                // but no namespace/service-account allowlist, any authenticated
                // ServiceAccount in the cluster would be authorized. Refuse to
                // start unless the operator configured an allowlist or opted in.
                let tr_config = TokenReviewConfig::from_env();
                let allow_any = std::env::var(ALLOW_ANY_SERVICE_ACCOUNT_ENV)
                    .ok()
                    .and_then(|v| v.parse::<bool>().ok())
                    .unwrap_or(false);
                if let Err(e) =
                    check_authorization_posture(tr_config.is_authorization_restricted(), allow_any)
                {
                    error!("{}", e);
                    return Err(anyhow::anyhow!(e));
                }
                if allow_any && !tr_config.is_authorization_restricted() {
                    warn!("⚠️  BIND_ALLOW_ANY_SERVICEACCOUNT is set: every authenticated ServiceAccount in the cluster is authorized");
                }

                match detect_kube_auth_mode() {
                    KubeAuthMode::Explicit { ref server, .. } => {
                        info!(
                            "kubernetes auth mode: explicit (KUBE_API_SERVER={})",
                            server
                        );
                    }
                    KubeAuthMode::Default => {
                        info!("kubernetes auth mode: try_default (KUBECONFIG / ~/.kube/config / in-cluster)");
                    }
                }
            }
        }
    }

    // load rate limiting configuration
    let rate_limit_config = RateLimitConfig::from_env();
    if let Err(e) = rate_limit_config.validate() {
        error!("invalid rate limit configuration: {}", e);
        return Err(anyhow::anyhow!("invalid rate limit configuration: {}", e));
    }

    if rate_limit_config.enabled {
        info!(
            "rate limiting enabled: {} requests per {} seconds (burst: {})",
            rate_limit_config.requests_per_period,
            rate_limit_config.period_secs,
            rate_limit_config.burst_size
        );
    } else {
        warn!("⚠️  rate limiting is disabled");
    }

    // get rndc configuration from environment or fallback to rndc.conf
    // Each parameter is checked independently - env var takes priority, then rndc.conf

    // Try to parse rndc.conf file first to have fallback values
    let config_paths = vec!["/etc/bind/rndc.conf", "/etc/rndc.conf"];
    let mut parsed_config = None;

    for path in &config_paths {
        match bindcar::rndc::parse_rndc_conf(path) {
            Ok(cfg) => {
                info!("successfully parsed rndc configuration from {}", path);
                parsed_config = Some(cfg);
                break;
            }
            Err(e) => {
                debug!("failed to parse {}: {}", path, e);
            }
        }
    }

    // Check each parameter independently: env var first, then rndc.conf, then hardcoded default
    let rndc_server = if let Ok(server) = std::env::var("RNDC_SERVER") {
        info!("using RNDC_SERVER from environment: {}", server);
        server
    } else if let Some(ref cfg) = parsed_config {
        info!("using server from rndc.conf: {}", cfg.server);
        cfg.server.clone()
    } else {
        let default = "127.0.0.1:953".to_string();
        warn!("using default RNDC_SERVER: {}", default);
        default
    };

    let rndc_algorithm = if let Ok(algorithm) = std::env::var("RNDC_ALGORITHM") {
        info!("using RNDC_ALGORITHM from environment: {}", algorithm);
        algorithm
    } else if let Some(ref cfg) = parsed_config {
        info!("using algorithm from rndc.conf: {}", cfg.algorithm);
        cfg.algorithm.clone()
    } else {
        let default = "sha256".to_string();
        warn!("using default RNDC_ALGORITHM: {}", default);
        default
    };

    let rndc_secret = if let Ok(secret) = std::env::var("RNDC_SECRET") {
        info!("using RNDC_SECRET from environment");
        secret
    } else if let Some(ref cfg) = parsed_config {
        info!("using secret from rndc.conf");
        cfg.secret.clone()
    } else {
        error!("rndc configuration not found!");
        error!("either set RNDC_SECRET environment variable or ensure /etc/bind/rndc.conf exists");
        return Err(anyhow::anyhow!(
            "rndc configuration required: set RNDC_SECRET env var or create /etc/bind/rndc.conf"
        ));
    };

    // Resolve and validate the zone directory once at startup. Canonicalizing the
    // operator-provided BIND_ZONE_DIR resolves symlinks and `..`, rejects a missing
    // or non-directory path up front, and breaks the env->filesystem taint flow
    // before the value is reused by the read_dir/metadata handlers (B-1).
    let zone_dir = zones::resolve_zone_dir(&zone_dir)
        .map_err(|e| anyhow::anyhow!("zone directory not usable: {}", e))?;
    info!("resolved zone directory: {}", zone_dir);

    // Optional DNSSEC key directory (ADR-0001): required only by the DS
    // endpoint. Same canonicalize-at-startup treatment as the zone
    // directory; a configured-but-unusable path is a hard startup error
    // rather than a silent downgrade.
    let key_dir = match std::env::var("BIND_KEY_DIR") {
        Ok(raw) => {
            let resolved = zones::resolve_zone_dir(&raw)
                .map_err(|e| anyhow::anyhow!("key directory not usable: {}", e))?;
            info!("resolved DNSSEC key directory: {}", resolved);
            Some(resolved)
        }
        Err(_) => {
            info!("BIND_KEY_DIR not set; the DS endpoint will return 501");
            None
        }
    };

    // create rndc executor
    let rndc = Arc::new(
        RndcExecutor::new(
            rndc_server.clone(),
            rndc_algorithm.clone(),
            rndc_secret.clone(),
        )
        .context("failed to create rndc client")?,
    );

    // Configure nsupdate executor (hybrid approach: env vars → rndc credentials)
    let nsupdate_key_name = std::env::var("NSUPDATE_KEY_NAME")
        .ok()
        .or_else(|| std::env::var("RNDC_KEY_NAME").ok())
        .or(Some("rndc-key".to_string()));

    let nsupdate_algorithm = std::env::var("NSUPDATE_ALGORITHM")
        .ok()
        .or(Some(rndc_algorithm.clone()));

    let nsupdate_secret = std::env::var("NSUPDATE_SECRET")
        .ok()
        .or(Some(rndc_secret.clone()));

    let nsupdate_server = std::env::var("NSUPDATE_SERVER")
        .ok()
        .unwrap_or_else(|| "127.0.0.1".to_string());

    let nsupdate_port = std::env::var("NSUPDATE_PORT")
        .ok()
        .and_then(|p| p.parse().ok())
        .unwrap_or(53);

    info!("nsupdate executor configuration:");
    info!("  server: {}:{}", nsupdate_server, nsupdate_port);
    info!("  TSIG key: {:?}", nsupdate_key_name);

    // create nsupdate executor
    let nsupdate = Arc::new(
        bindcar::nsupdate::NsupdateExecutor::new(
            nsupdate_server,
            nsupdate_port,
            nsupdate_key_name,
            nsupdate_algorithm,
            nsupdate_secret,
        )
        .context("failed to create nsupdate executor")?,
    );

    // create application state
    let state = AppState {
        rndc,
        nsupdate,
        zone_dir: zone_dir.clone(),
        key_dir,
    };

    // build api routes
    let api_routes = Router::new()
        .route("/zones", post(zones::create_zone).get(zones::list_zones))
        .route(
            "/zones/{name}",
            get(zones::get_zone)
                .delete(zones::delete_zone)
                .patch(zones::modify_zone),
        )
        .route("/zones/{name}/reload", post(zones::reload_zone))
        .route("/zones/{name}/status", get(zones::zone_status))
        .route("/zones/{name}/ds", get(zones::get_zone_ds))
        .route("/zones/{name}/dnssec/checkds", post(zones::checkds_zone))
        .route("/zones/{name}/freeze", post(zones::freeze_zone))
        .route("/zones/{name}/thaw", post(zones::thaw_zone))
        .route("/zones/{name}/notify", post(zones::notify_zone))
        .route("/zones/{name}/retransfer", post(zones::retransfer_zone))
        .route(
            "/zones/{name}/records",
            post(bindcar::records::add_record)
                .delete(bindcar::records::remove_record)
                .put(bindcar::records::update_record),
        )
        .route("/server/status", get(zones::server_status))
        .with_state(state.clone());

    // conditionally apply authentication middleware
    let api_routes = if !disable_auth {
        api_routes.layer(axum_middleware::from_fn(authenticate))
    } else {
        api_routes
    };

    // conditionally apply rate limiting layer
    let api_routes = if rate_limit_config.enabled {
        // Governor is configured by the interval between replenished cells, not
        // by requests-per-period. Deriving it here with integer division silently
        // floored the budget: the 100-per-60s default became 1 request per
        // second, and the operator's zone replay — a burst of create/freeze/
        // update/thaw/notify calls issued whenever a BIND9 Pod comes back empty —
        // ran straight into HTTP 429. The operator answers 429 with exponential
        // backoff, so a ~30s recovery stretched to ~130s.
        let replenish_period = rate_limit_config.replenish_period();

        // Build governor configuration
        // A-1: key on the real TCP peer IP, NOT the spoofable X-Forwarded-For /
        // X-Real-IP / Forwarded headers (SmartIpKeyExtractor). bindcar is reached
        // directly by the operator's pods (no trusted L7 proxy in front), so
        // trusting client-supplied forwarding headers would let any caller evade
        // the limit (rotate the header) or exhaust another client's bucket
        // (spoof the victim's IP).
        let governor_conf = Arc::new(
            GovernorConfigBuilder::default()
                .key_extractor(PeerIpKeyExtractor)
                .period(replenish_period)
                .burst_size(rate_limit_config.burst_size)
                .finish()
                .expect("Failed to create governor config"),
        );

        api_routes.layer(GovernorLayer::new(governor_conf))
    } else {
        api_routes
    };

    // The Swagger UI and OpenAPI spec are served UNAUTHENTICATED and disclose the
    // full mutate-API surface, so they are OFF by default and only mounted when
    // BIND_ENABLE_DOCS is truthy (A13). Enable them for local development only.
    let enable_docs = std::env::var("BIND_ENABLE_DOCS")
        .ok()
        .and_then(|v| v.parse::<bool>().ok())
        .unwrap_or(false);

    // build main router
    let mut app = Router::new();
    if enable_docs {
        info!("serving unauthenticated API docs at /api/v1/docs (BIND_ENABLE_DOCS=true)");
        app = app
            .merge(SwaggerUi::new("/api/v1/docs").url("/api/v1/openapi.json", ApiDoc::openapi()));
    }
    let app = app
        .route("/api/v1/health", get(health_check))
        .route("/api/v1/ready", get(ready_check))
        .route("/metrics", get(metrics_handler))
        .nest("/api/v1", api_routes)
        .with_state(state)
        .layer(axum_middleware::from_fn(middleware::track_metrics))
        .layer(TraceLayer::new_for_http());

    // start server
    let addr = format!("{}:{}", bind_host, api_port);
    let scheme = scheme_for(tls_settings.as_ref());

    info!(
        "bind9 rndc api server listening on {} ({})",
        addr,
        if tls_settings.is_some() {
            "TLS"
        } else {
            "plaintext"
        }
    );
    if enable_docs {
        info!("swagger ui available at {}://{}/api/v1/docs", scheme, addr);
    }

    let listener = tokio::net::TcpListener::bind(&addr).await?;

    // A build without the `tls` feature can only serve plaintext. `main` has
    // already refused to start if TLS was configured, so reaching here means
    // plaintext was intended.
    #[cfg(not(feature = "tls"))]
    {
        let _ = (tls_settings, tls_reload_interval);
        warn_plaintext_transport(&bind_host);
        axum::serve(
            listener,
            app.into_make_service_with_connect_info::<SocketAddr>(),
        )
        .await
        .context("server error")
    }

    #[cfg(feature = "tls")]
    {
        let Some(tls_settings) = tls_settings else {
            // Plaintext path — unchanged from previous releases.
            warn_plaintext_transport(&bind_host);
            axum::serve(
                listener,
                app.into_make_service_with_connect_info::<SocketAddr>(),
            )
            .await
            .context("server error")?;
            return Ok(());
        };

        if tls_settings.requires_client_auth() {
            info!(
            "mutual TLS enabled; clients must present a certificate trusted by the configured CA"
        );
        }

        // A failure here is fatal: there is no known-good configuration to fall back
        // to, and serving plaintext instead would be a silent downgrade.
        let reloader =
            StdArc::new(TlsReloader::new(tls_settings).context("failed to build TLS config")?);

        if TlsReloader::reloading_enabled(tls_reload_interval) {
            info!(
            "watching TLS certificate material for renewals every {}s (BIND_TLS_RELOAD_INTERVAL=0 to disable)",
            tls_reload_interval
        );
            spawn_tls_reload_task(StdArc::clone(&reloader), tls_reload_interval);
        } else {
            info!("TLS certificate reloading is disabled; a renewal requires a restart");
        }

        serve_tls(listener, app, reloader).await
    }
}

#[cfg(feature = "tls")]
/// Poll the TLS material for renewals, and reload on `SIGHUP`.
///
/// Polling rather than watching is deliberate: Kubernetes swaps a `..data`
/// symlink instead of rewriting files in place, which defeats inode-based
/// watchers. `SIGHUP` is offered alongside it so an operator can make rotation
/// deterministic instead of waiting out the interval.
///
/// # Arguments
/// * `reloader` - the shared reloader holding the live configuration
/// * `interval_secs` - seconds between polls; the caller has already checked it is non-zero
fn spawn_tls_reload_task(reloader: StdArc<TlsReloader>, interval_secs: u64) {
    tokio::spawn(async move {
        let mut ticker = tokio::time::interval(std::time::Duration::from_secs(interval_secs));
        // The first tick fires immediately; skip it so startup does not
        // pointlessly rebuild the config it just built.
        ticker.tick().await;

        #[cfg(unix)]
        let mut sighup = match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::hangup())
        {
            Ok(s) => Some(s),
            Err(e) => {
                warn!("could not install SIGHUP handler for TLS reload: {}", e);
                None
            }
        };

        loop {
            #[cfg(unix)]
            {
                match sighup.as_mut() {
                    Some(hup) => {
                        tokio::select! {
                            _ = ticker.tick() => {}
                            _ = hup.recv() => {
                                info!("SIGHUP received; checking TLS material now");
                            }
                        }
                    }
                    None => {
                        ticker.tick().await;
                    }
                }
            }
            #[cfg(not(unix))]
            {
                ticker.tick().await;
            }

            reloader.reload_if_changed();
        }
    });
}

/// Warn when a credential-bearing API is about to be served in the clear.
///
/// bindcar's callers authenticate with a Kubernetes ServiceAccount token or the
/// shared `BIND_API_TOKEN`. Over plaintext that credential is readable by
/// anything observing the link, so the operator should see this at every start.
/// Loopback binds are exempt — the traffic never leaves the host.
fn warn_plaintext_transport(bind_host: &str) {
    if bind_host.starts_with("127.") || bind_host == "localhost" || bind_host == "::1" {
        return;
    }

    warn!(
        "serving the API over plaintext HTTP on a non-loopback address; API credentials \
cross the network in the clear. Set --tls-cert/--tls-key (BIND_TLS_CERT/BIND_TLS_KEY) to enable TLS."
    );
}

#[cfg(feature = "tls")]
/// Serve the router over TLS.
///
/// Runs a manual accept loop so each connection is wrapped by
/// [`tokio_rustls::TlsAcceptor`] before hyper sees it. Peer address is injected
/// as [`ConnectInfo`] on every request, because the rate limiter's
/// `PeerIpKeyExtractor` reads it and would otherwise reject every request once
/// the listener stopped being an `axum::serve` one.
///
/// The configuration is read from `reloader` on every accept rather than being
/// captured once, so a certificate renewal reaches new connections without a
/// restart (roadmap 06).
///
/// # Arguments
/// * `listener` - the bound TCP listener
/// * `app` - the fully-built axum router
/// * `reloader` - holds the live rustls configuration
///
/// # Errors
/// Returns an error only if the listener itself fails. Per-connection failures
/// (handshake errors, client disconnects) are logged and skipped so one bad
/// client cannot take the server down.
async fn serve_tls(
    listener: tokio::net::TcpListener,
    app: Router,
    reloader: StdArc<TlsReloader>,
) -> anyhow::Result<()> {
    loop {
        let (stream, peer) = listener.accept().await.context("accept failed")?;
        // Read the live config per connection so a reload reaches new
        // connections immediately. `TlsAcceptor::from` wraps the `Arc`, so this
        // costs one atomic increment. Established connections keep the
        // certificate they started with, which is what makes rotation
        // non-disruptive.
        let acceptor = tokio_rustls::TlsAcceptor::from(reloader.current());
        let app = app.clone();

        tokio::spawn(async move {
            let tls_stream = match acceptor.accept(stream).await {
                Ok(s) => s,
                Err(e) => {
                    // Handshake failures are routine (probes, wrong SNI, a client
                    // with no cert under mTLS) and must not be fatal.
                    debug!("TLS handshake with {} failed: {}", peer, e);
                    return;
                }
            };

            let service = hyper::service::service_fn(
                move |mut req: hyper::Request<hyper::body::Incoming>| {
                    req.extensions_mut().insert(ConnectInfo(peer));
                    app.clone().call(req)
                },
            );

            if let Err(e) =
                hyper_util::server::conn::auto::Builder::new(hyper_util::rt::TokioExecutor::new())
                    .serve_connection_with_upgrades(
                        hyper_util::rt::TokioIo::new(tls_stream),
                        service,
                    )
                    .await
            {
                debug!("connection from {} ended: {}", peer, e);
            }
        });
    }
}

#[cfg(test)]
mod main_test;