summaryrefslogtreecommitdiff
path: root/src/server.rs
blob: a2aef5cf1bdaf5bde2d2680df4336fd2828c2190 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
use crate::build_guard::{BuildGuard, BuildScheduler};
use crate::config::{Config, SiteConfig};
use crate::polling::PollingManager;
use anyhow::Result;
use log::{error, info, warn};
use std::path::PathBuf;
use std::sync::{Arc, RwLock};
use tiny_http::{Header, Method, Request, Response, Server};
use tokio::signal::unix::{SignalKind, signal};

#[derive(serde::Serialize)]
struct ErrorResponse {
    error: &'static str,
}

#[derive(serde::Serialize)]
struct QueuedResponse {
    status: &'static str,
}

#[derive(serde::Serialize)]
struct HealthResponse {
    status: &'static str,
}

fn json_response(status: u16, body: &str) -> Response<std::io::Cursor<Vec<u8>>> {
    let data = body.as_bytes().to_vec();
    Response::from_data(data)
        .with_status_code(status)
        .with_header(Header::from_bytes("Content-Type", "application/json").expect("valid header"))
}

fn empty_response(status: u16) -> Response<std::io::Empty> {
    Response::empty(status)
}

#[derive(Clone)]
pub struct AppState {
    pub config: Arc<RwLock<Config>>,
    pub config_path: Arc<PathBuf>,
    pub build_scheduler: Arc<BuildScheduler>,
    pub polling_manager: Arc<PollingManager>,
}

/// Extract Bearer token from `tiny_http` headers.
fn extract_bearer_token(headers: &[Header]) -> Option<&str> {
    headers
        .iter()
        .find(|h| h.field.equiv("Authorization"))
        .and_then(|h| h.value.as_str().strip_prefix("Bearer "))
}

fn validate_token(provided: &str, expected: &str) -> bool {
    let a = provided.as_bytes();
    let b = expected.as_bytes();

    // Constant-time comparison — OWASP requirement.
    // Length check is not constant-time, but token length is not secret
    // (same early-return approach as subtle::ConstantTimeEq for slices).
    if a.len() != b.len() {
        return false;
    }

    let mut acc: u8 = 0;
    for (x, y) in a.iter().zip(b.iter()) {
        acc |= x ^ y;
    }
    acc == 0
}

/// Check if path is a single segment (e.g., "/my-site").
fn is_site_path(path: &str) -> bool {
    path.starts_with('/') && path.len() > 1 && !path[1..].contains('/')
}

/// Handle POST `/{site_name}`.
fn handle_deploy(
    request: Request,
    site_name: &str,
    state: &AppState,
    handle: &tokio::runtime::Handle,
) {
    info!("[{site_name}] deployment request received");

    // Find site
    let site = state
        .config
        .read()
        .expect("config lock poisoned")
        .find_site(site_name)
        .cloned();
    let Some(site) = site else {
        info!("[{site_name}] site not found");
        let body = serde_json::to_string(&ErrorResponse { error: "not_found" })
            .expect("static JSON serialization");
        let _ = request.respond(json_response(404, &body));
        return;
    };

    // Auth check (if configured)
    if !site.webhook_token.is_empty() {
        let token_valid = extract_bearer_token(request.headers())
            .is_some_and(|token| validate_token(token, &site.webhook_token));

        if !token_valid {
            info!("[{site_name}] unauthorized request");
            let body = serde_json::to_string(&ErrorResponse {
                error: "unauthorized",
            })
            .expect("static JSON serialization");
            let _ = request.respond(json_response(401, &body));
            return;
        }
    }

    // Try immediate build
    let Some(guard) = BuildGuard::try_acquire(site_name.to_owned(), &state.build_scheduler) else {
        // Build in progress — try to queue
        if state.build_scheduler.try_queue(site_name) {
            info!("[{site_name}] build queued");
            let body = serde_json::to_string(&QueuedResponse { status: "queued" })
                .expect("static JSON serialization");
            let _ = request.respond(json_response(202, &body));
            return;
        }
        // Already queued — collapse
        info!("[{site_name}] build already queued, collapsing");
        let _ = request.respond(empty_response(202));
        return;
    };

    info!("[{site_name}] deployment accepted");

    // Spawn async build pipeline with queue drain loop
    let state = state.clone();
    let site_name = site_name.to_owned();
    handle.spawn(async move {
        let mut current_site = site;
        let mut current_guard = guard;
        loop {
            #[allow(clippy::large_futures)]
            run_build_pipeline(
                state.clone(),
                site_name.clone(),
                current_site.clone(),
                current_guard,
            )
            .await;
            // Guard dropped here — build lock released

            if !state.build_scheduler.take_queued(&site_name) {
                break;
            }
            info!("[{site_name}] processing queued rebuild");
            let Some(new_site) = state
                .config
                .read()
                .expect("config lock poisoned")
                .find_site(&site_name)
                .cloned()
            else {
                warn!("[{site_name}] site removed from config, skipping queued rebuild");
                break;
            };
            let Some(new_guard) =
                BuildGuard::try_acquire(site_name.clone(), &state.build_scheduler)
            else {
                break; // someone else grabbed it
            };
            current_site = new_site;
            current_guard = new_guard;
        }
    });

    let _ = request.respond(empty_response(202));
}

/// Main request loop (runs on `std::thread`).
#[allow(clippy::needless_pass_by_value)] // ownership required by std::thread::spawn callers
pub(crate) fn handle_requests(
    server: Arc<Server>,
    state: AppState,
    handle: tokio::runtime::Handle,
) {
    for request in server.incoming_requests() {
        let path = request.url().split('?').next().unwrap_or("").to_owned();
        let method = request.method().clone();

        match (method, path.as_str()) {
            (Method::Get, "/health") => {
                let body = serde_json::to_string(&HealthResponse { status: "ok" })
                    .expect("static JSON serialization");
                let _ = request.respond(json_response(200, &body));
            }
            (_, "/health") => {
                let _ = request.respond(empty_response(405));
            }
            (Method::Post, _) if is_site_path(&path) => {
                let site_name = &path[1..];
                handle_deploy(request, site_name, &state, &handle);
            }
            (_, _) if is_site_path(&path) => {
                let _ = request.respond(empty_response(405));
            }
            _ => {
                let body = serde_json::to_string(&ErrorResponse { error: "not_found" })
                    .expect("static JSON serialization");
                let _ = request.respond(json_response(404, &body));
            }
        }
    }
}

/// Run the complete build pipeline: git sync → build → publish.
#[allow(clippy::large_futures)]
pub(crate) async fn run_build_pipeline(
    state: AppState,
    site_name: String,
    site: SiteConfig,
    _guard: BuildGuard,
) {
    let (base_dir, log_dir, container_runtime, max_builds_to_keep, git_timeout) = {
        let config = state.config.read().expect("config lock poisoned");
        (
            config.base_dir.clone(),
            config.log_dir.clone(),
            config.container_runtime.clone(),
            config.max_builds_to_keep,
            config
                .git_timeout
                .unwrap_or(crate::git::GIT_TIMEOUT_DEFAULT),
        )
    };

    match crate::pipeline::run_build(
        &site_name,
        &site,
        &base_dir,
        &log_dir,
        &container_runtime,
        max_builds_to_keep,
        git_timeout,
        false,
    )
    .await
    {
        Ok(result) => {
            info!(
                "[{site_name}] pipeline completed: build_dir={} duration_secs={}",
                result.build_dir.display(),
                result.duration.as_secs()
            );
        }
        Err(e) => {
            error!("[{site_name}] pipeline failed: {e}");
        }
    }
}

/// Setup SIGHUP signal handler for configuration hot-reload.
pub(crate) fn setup_sighup_handler(state: AppState) {
    tokio::spawn(async move {
        #[allow(clippy::expect_used)] // fatal: cannot proceed without signal handler
        let mut sighup =
            signal(SignalKind::hangup()).expect("failed to setup SIGHUP signal handler");

        loop {
            sighup.recv().await;
            info!("SIGHUP received, reloading configuration");

            let config_path = state.config_path.as_ref();
            match Config::load(config_path).await {
                Ok(new_config) => {
                    let old_sites_count = state
                        .config
                        .read()
                        .expect("config lock poisoned")
                        .sites
                        .len();
                    let new_sites_count = new_config.sites.len();

                    // Check for non-reloadable changes and capture old values
                    let (old_listen, old_base, old_log_dir, old_log_level) = {
                        let old_config = state.config.read().expect("config lock poisoned");
                        if old_config.listen_address != new_config.listen_address {
                            warn!(
                                "listen_address changed but cannot be reloaded (restart required): old={} new={}",
                                old_config.listen_address, new_config.listen_address
                            );
                        }
                        if old_config.base_dir != new_config.base_dir {
                            warn!(
                                "base_dir changed but cannot be reloaded (restart required): old={} new={}",
                                old_config.base_dir.display(),
                                new_config.base_dir.display()
                            );
                        }
                        if old_config.log_dir != new_config.log_dir {
                            warn!(
                                "log_dir changed but cannot be reloaded (restart required): old={} new={}",
                                old_config.log_dir.display(),
                                new_config.log_dir.display()
                            );
                        }
                        if old_config.log_level != new_config.log_level {
                            warn!(
                                "log_level changed but cannot be reloaded (restart required): old={} new={}",
                                old_config.log_level, new_config.log_level
                            );
                        }
                        (
                            old_config.listen_address.clone(),
                            old_config.base_dir.clone(),
                            old_config.log_dir.clone(),
                            old_config.log_level.clone(),
                        )
                    };

                    // Preserve non-reloadable fields from the running config
                    let mut final_config = new_config;
                    final_config.listen_address = old_listen;
                    final_config.base_dir = old_base;
                    final_config.log_dir = old_log_dir;
                    final_config.log_level = old_log_level;

                    // Apply the merged configuration
                    *state.config.write().expect("config lock poisoned") = final_config;

                    // Restart polling tasks with new configuration
                    info!("restarting polling tasks");
                    state.polling_manager.stop_all().await;
                    state.polling_manager.start_polling(state.clone()).await;

                    info!(
                        "configuration reloaded successfully: old_sites_count={old_sites_count} new_sites_count={new_sites_count}"
                    );
                }
                Err(e) => {
                    error!("failed to reload configuration, keeping current config: {e}");
                }
            }
        }
    });
}

/// Start the server in production mode.
///
/// # Errors
///
/// Returns an error if the TCP listener cannot bind or the server encounters
/// a fatal I/O error.
pub async fn run(config: Config, config_path: PathBuf) -> Result<()> {
    let addr = config.parsed_listen_address();

    let state = AppState {
        config: Arc::new(RwLock::new(config)),
        config_path: Arc::new(config_path),
        build_scheduler: Arc::new(BuildScheduler::new()),
        polling_manager: Arc::new(PollingManager::new()),
    };

    // Setup SIGHUP handler for configuration hot-reload
    setup_sighup_handler(state.clone());

    // Start polling tasks for sites with poll_interval configured
    state.polling_manager.start_polling(state.clone()).await;

    let server = Arc::new(Server::http(addr).map_err(|e| anyhow::anyhow!("failed to bind: {e}"))?);
    info!("server listening on {addr}");

    // Shutdown handler: signal → unblock server
    let shutdown_server = Arc::clone(&server);
    tokio::spawn(async move {
        let mut sigterm = signal(SignalKind::terminate()).expect("failed to setup SIGTERM handler");
        let mut sigint = signal(SignalKind::interrupt()).expect("failed to setup SIGINT handler");
        tokio::select! {
            _ = sigterm.recv() => info!("received SIGTERM, shutting down"),
            _ = sigint.recv() => info!("received SIGINT, shutting down"),
        }
        shutdown_server.unblock();
    });

    // Run HTTP loop on blocking thread
    let handle = tokio::runtime::Handle::current();
    tokio::task::spawn_blocking(move || {
        handle_requests(server, state, handle);
    })
    .await?;

    Ok(())
}

/// Run the server with a pre-built Server, shutting down when `shutdown_signal` resolves.
///
/// Used by integration tests via [`test_support::run_server`].
/// Returns a `std::thread::JoinHandle` for the request-handling thread.
#[cfg(any(test, feature = "integration"))]
pub(crate) fn run_with_server(
    state: AppState,
    server: Arc<Server>,
    shutdown_signal: impl std::future::Future<Output = ()> + Send + 'static,
) -> std::thread::JoinHandle<()> {
    let handle = tokio::runtime::Handle::current();

    // Shutdown: wait for signal, then unblock
    let shutdown_server = Arc::clone(&server);
    tokio::spawn(async move {
        shutdown_signal.await;
        shutdown_server.unblock();
    });

    // Spawn request handler on std::thread, return handle for joining
    std::thread::spawn(move || {
        handle_requests(server, state, handle);
    })
}

#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::indexing_slicing, clippy::expect_used)]
mod tests {
    use super::*;
    use crate::config::{BuildOverrides, SiteConfig};
    use std::path::PathBuf;

    fn test_state(config: Config) -> AppState {
        AppState {
            config: Arc::new(RwLock::new(config)),
            config_path: Arc::new(PathBuf::from("witryna.toml")),
            build_scheduler: Arc::new(BuildScheduler::new()),
            polling_manager: Arc::new(PollingManager::new()),
        }
    }

    fn test_config() -> Config {
        Config {
            listen_address: "127.0.0.1:8080".to_owned(),
            container_runtime: "podman".to_owned(),
            base_dir: PathBuf::from("/var/lib/witryna"),
            log_dir: PathBuf::from("/var/log/witryna"),
            log_level: "info".to_owned(),
            max_builds_to_keep: 5,
            git_timeout: None,
            sites: vec![],
        }
    }

    fn test_config_with_sites() -> Config {
        Config {
            sites: vec![SiteConfig {
                name: "my-site".to_owned(),
                repo_url: "https://github.com/user/my-site.git".to_owned(),
                branch: "main".to_owned(),
                webhook_token: "secret-token".to_owned(),
                webhook_token_file: None,

                build_overrides: BuildOverrides::default(),
                poll_interval: None,
                build_timeout: None,
                cache_dirs: None,
                post_deploy: None,
                env: None,
                container_memory: None,
                container_cpus: None,
                container_pids_limit: None,
                container_network: "none".to_owned(),
                git_depth: None,
                container_workdir: None,
                config_file: None,
            }],
            ..test_config()
        }
    }

    /// Start a test server on a random port, returning the server handle, state, and port.
    fn test_server(config: Config) -> (Arc<Server>, AppState, u16) {
        let state = test_state(config);
        let server = Arc::new(Server::http("127.0.0.1:0").unwrap());
        let port = match server.server_addr() {
            tiny_http::ListenAddr::IP(a) => a.port(),
            _ => unreachable!("expected IP address"),
        };
        let handle = tokio::runtime::Handle::current();
        let server_clone = server.clone();
        let state_clone = state.clone();
        std::thread::spawn(move || handle_requests(server_clone, state_clone, handle));
        (server, state, port)
    }

    #[tokio::test]
    async fn health_endpoint_returns_ok() {
        let (server, _state, port) = test_server(test_config_with_sites());
        let resp = reqwest::get(format!("http://127.0.0.1:{port}/health"))
            .await
            .unwrap();
        assert_eq!(resp.status().as_u16(), 200);
        let json: serde_json::Value = resp.json().await.unwrap();
        assert_eq!(json["status"], "ok");
        server.unblock();
    }

    #[tokio::test]
    async fn json_responses_have_content_type_header() {
        let (server, _state, port) = test_server(test_config_with_sites());
        let resp = reqwest::get(format!("http://127.0.0.1:{port}/health"))
            .await
            .unwrap();
        assert_eq!(
            resp.headers()
                .get("content-type")
                .unwrap()
                .to_str()
                .unwrap(),
            "application/json"
        );
        server.unblock();
    }

    #[tokio::test]
    async fn unknown_site_post_returns_not_found() {
        let (server, _state, port) = test_server(test_config());
        let client = reqwest::Client::new();
        let resp = client
            .post(format!("http://127.0.0.1:{port}/nonexistent"))
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status().as_u16(), 404);
        let json: serde_json::Value = resp.json().await.unwrap();
        assert_eq!(json["error"], "not_found");
        server.unblock();
    }

    #[tokio::test]
    async fn deploy_known_site_with_valid_token_returns_accepted() {
        let (server, _state, port) = test_server(test_config_with_sites());
        let client = reqwest::Client::new();
        let resp = client
            .post(format!("http://127.0.0.1:{port}/my-site"))
            .header("Authorization", "Bearer secret-token")
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status().as_u16(), 202);
        server.unblock();
    }

    #[tokio::test]
    async fn deploy_missing_auth_header_returns_unauthorized() {
        let (server, _state, port) = test_server(test_config_with_sites());
        let client = reqwest::Client::new();
        let resp = client
            .post(format!("http://127.0.0.1:{port}/my-site"))
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status().as_u16(), 401);
        let json: serde_json::Value = resp.json().await.unwrap();
        assert_eq!(json["error"], "unauthorized");
        server.unblock();
    }

    #[tokio::test]
    async fn deploy_invalid_token_returns_unauthorized() {
        let (server, _state, port) = test_server(test_config_with_sites());
        let client = reqwest::Client::new();
        let resp = client
            .post(format!("http://127.0.0.1:{port}/my-site"))
            .header("Authorization", "Bearer wrong-token")
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status().as_u16(), 401);
        let json: serde_json::Value = resp.json().await.unwrap();
        assert_eq!(json["error"], "unauthorized");
        server.unblock();
    }

    #[tokio::test]
    async fn deploy_malformed_auth_header_returns_unauthorized() {
        let (server, _state, port) = test_server(test_config_with_sites());
        let client = reqwest::Client::new();
        // Test without "Bearer " prefix
        let resp = client
            .post(format!("http://127.0.0.1:{port}/my-site"))
            .header("Authorization", "secret-token")
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status().as_u16(), 401);
        let json: serde_json::Value = resp.json().await.unwrap();
        assert_eq!(json["error"], "unauthorized");
        server.unblock();
    }

    #[tokio::test]
    async fn deploy_basic_auth_returns_unauthorized() {
        let (server, _state, port) = test_server(test_config_with_sites());
        let client = reqwest::Client::new();
        // Test Basic auth instead of Bearer
        let resp = client
            .post(format!("http://127.0.0.1:{port}/my-site"))
            .header("Authorization", "Basic dXNlcjpwYXNz")
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status().as_u16(), 401);
        let json: serde_json::Value = resp.json().await.unwrap();
        assert_eq!(json["error"], "unauthorized");
        server.unblock();
    }

    #[tokio::test]
    async fn deploy_get_method_not_allowed() {
        let (server, _state, port) = test_server(test_config_with_sites());
        let resp = reqwest::get(format!("http://127.0.0.1:{port}/my-site"))
            .await
            .unwrap();
        assert_eq!(resp.status().as_u16(), 405);
        server.unblock();
    }

    #[tokio::test]
    async fn deploy_unknown_site_with_token_returns_not_found() {
        let (server, _state, port) = test_server(test_config_with_sites());
        let client = reqwest::Client::new();
        let resp = client
            .post(format!("http://127.0.0.1:{port}/unknown-site"))
            .header("Authorization", "Bearer any-token")
            .send()
            .await
            .unwrap();
        // Returns 404 before checking token (site lookup first)
        assert_eq!(resp.status().as_u16(), 404);
        let json: serde_json::Value = resp.json().await.unwrap();
        assert_eq!(json["error"], "not_found");
        server.unblock();
    }

    fn test_config_with_two_sites() -> Config {
        Config {
            listen_address: "127.0.0.1:8080".to_owned(),
            container_runtime: "podman".to_owned(),
            base_dir: PathBuf::from("/var/lib/witryna"),
            log_dir: PathBuf::from("/var/log/witryna"),
            log_level: "info".to_owned(),
            max_builds_to_keep: 5,
            git_timeout: None,
            sites: vec![
                SiteConfig {
                    name: "site-one".to_owned(),
                    repo_url: "https://github.com/user/site-one.git".to_owned(),
                    branch: "main".to_owned(),
                    webhook_token: "token-one".to_owned(),
                    webhook_token_file: None,

                    build_overrides: BuildOverrides::default(),
                    poll_interval: None,
                    build_timeout: None,
                    cache_dirs: None,
                    post_deploy: None,
                    env: None,
                    container_memory: None,
                    container_cpus: None,
                    container_pids_limit: None,
                    container_network: "none".to_owned(),
                    git_depth: None,
                    container_workdir: None,
                    config_file: None,
                },
                SiteConfig {
                    name: "site-two".to_owned(),
                    repo_url: "https://github.com/user/site-two.git".to_owned(),
                    branch: "main".to_owned(),
                    webhook_token: "token-two".to_owned(),
                    webhook_token_file: None,

                    build_overrides: BuildOverrides::default(),
                    poll_interval: None,
                    build_timeout: None,
                    cache_dirs: None,
                    post_deploy: None,
                    env: None,
                    container_memory: None,
                    container_cpus: None,
                    container_pids_limit: None,
                    container_network: "none".to_owned(),
                    git_depth: None,
                    container_workdir: None,
                    config_file: None,
                },
            ],
        }
    }

    #[tokio::test]
    async fn deploy_concurrent_same_site_gets_queued() {
        let (server, state, port) = test_server(test_config_with_sites());
        let client = reqwest::Client::new();

        // Pre-mark site as building to simulate an in-progress build
        state
            .build_scheduler
            .in_progress
            .lock()
            .unwrap()
            .insert("my-site".to_owned());

        // First request to same site should be queued (202 with body)
        let resp1 = client
            .post(format!("http://127.0.0.1:{port}/my-site"))
            .header("Authorization", "Bearer secret-token")
            .send()
            .await
            .unwrap();
        assert_eq!(resp1.status().as_u16(), 202);
        let json: serde_json::Value = resp1.json().await.unwrap();
        assert_eq!(json["status"], "queued");

        // Second request should be collapsed (202, no body)
        let resp2 = client
            .post(format!("http://127.0.0.1:{port}/my-site"))
            .header("Authorization", "Bearer secret-token")
            .send()
            .await
            .unwrap();
        assert_eq!(resp2.status().as_u16(), 202);

        server.unblock();
    }

    #[tokio::test]
    async fn deploy_concurrent_different_sites_both_succeed() {
        let (server, _state, port) = test_server(test_config_with_two_sites());
        let client = reqwest::Client::new();

        // First site deployment
        let resp1 = client
            .post(format!("http://127.0.0.1:{port}/site-one"))
            .header("Authorization", "Bearer token-one")
            .send()
            .await
            .unwrap();
        assert_eq!(resp1.status().as_u16(), 202);

        // Second site deployment should also succeed
        let resp2 = client
            .post(format!("http://127.0.0.1:{port}/site-two"))
            .header("Authorization", "Bearer token-two")
            .send()
            .await
            .unwrap();
        assert_eq!(resp2.status().as_u16(), 202);

        server.unblock();
    }

    #[tokio::test]
    async fn deploy_site_in_progress_checked_after_auth() {
        let (server, state, port) = test_server(test_config_with_sites());

        // Pre-mark site as building
        state
            .build_scheduler
            .in_progress
            .lock()
            .unwrap()
            .insert("my-site".to_owned());

        let client = reqwest::Client::new();

        // Request with wrong token should return 401 (auth checked before build status)
        let resp = client
            .post(format!("http://127.0.0.1:{port}/my-site"))
            .header("Authorization", "Bearer wrong-token")
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status().as_u16(), 401);
        let json: serde_json::Value = resp.json().await.unwrap();
        assert_eq!(json["error"], "unauthorized");

        server.unblock();
    }

    #[tokio::test]
    async fn sighup_preserves_non_reloadable_fields() {
        // Original config with specific non-reloadable values
        let original = Config {
            listen_address: "127.0.0.1:8080".to_owned(),
            container_runtime: "podman".to_owned(),
            base_dir: PathBuf::from("/var/lib/witryna"),
            log_dir: PathBuf::from("/var/log/witryna"),
            log_level: "info".to_owned(),
            max_builds_to_keep: 5,
            git_timeout: None,
            sites: vec![SiteConfig {
                name: "old-site".to_owned(),
                repo_url: "https://example.com/old.git".to_owned(),
                branch: "main".to_owned(),
                webhook_token: "old-token".to_owned(),
                webhook_token_file: None,

                build_overrides: BuildOverrides::default(),
                poll_interval: None,
                build_timeout: None,
                cache_dirs: None,
                post_deploy: None,
                env: None,
                container_memory: None,
                container_cpus: None,
                container_pids_limit: None,
                container_network: "none".to_owned(),
                git_depth: None,
                container_workdir: None,
                config_file: None,
            }],
        };

        let state = test_state(original);

        // Simulate a new config loaded from disk with changed non-reloadable
        // AND reloadable fields
        let new_config = Config {
            listen_address: "0.0.0.0:9999".to_owned(),
            container_runtime: "docker".to_owned(),
            base_dir: PathBuf::from("/tmp/new-base"),
            log_dir: PathBuf::from("/tmp/new-logs"),
            log_level: "debug".to_owned(),
            max_builds_to_keep: 10,
            git_timeout: None,
            sites: vec![SiteConfig {
                name: "new-site".to_owned(),
                repo_url: "https://example.com/new.git".to_owned(),
                branch: "develop".to_owned(),
                webhook_token: "new-token".to_owned(),
                webhook_token_file: None,

                build_overrides: BuildOverrides::default(),
                poll_interval: None,
                build_timeout: None,
                cache_dirs: None,
                post_deploy: None,
                env: None,
                container_memory: None,
                container_cpus: None,
                container_pids_limit: None,
                container_network: "none".to_owned(),
                git_depth: None,
                container_workdir: None,
                config_file: None,
            }],
        };

        // Apply the same merge logic used in setup_sighup_handler
        let (old_listen, old_base, old_log_dir, old_log_level) = {
            let old_config = state.config.read().unwrap();
            (
                old_config.listen_address.clone(),
                old_config.base_dir.clone(),
                old_config.log_dir.clone(),
                old_config.log_level.clone(),
            )
        };

        let mut final_config = new_config;
        final_config.listen_address = old_listen;
        final_config.base_dir = old_base;
        final_config.log_dir = old_log_dir;
        final_config.log_level = old_log_level;

        *state.config.write().unwrap() = final_config;

        // Verify non-reloadable fields are preserved and reloadable fields are updated
        let (listen, base, log_d, log_l, runtime, max_builds, sites_len, site_name) = {
            let config = state.config.read().unwrap();
            (
                config.listen_address.clone(),
                config.base_dir.clone(),
                config.log_dir.clone(),
                config.log_level.clone(),
                config.container_runtime.clone(),
                config.max_builds_to_keep,
                config.sites.len(),
                config.sites[0].name.clone(),
            )
        };
        assert_eq!(listen, "127.0.0.1:8080");
        assert_eq!(base, PathBuf::from("/var/lib/witryna"));
        assert_eq!(log_d, PathBuf::from("/var/log/witryna"));
        assert_eq!(log_l, "info");
        assert_eq!(runtime, "docker");
        assert_eq!(max_builds, 10);
        assert_eq!(sites_len, 1);
        assert_eq!(site_name, "new-site");
    }

    fn test_config_with_disabled_auth() -> Config {
        Config {
            sites: vec![SiteConfig {
                name: "open-site".to_owned(),
                repo_url: "https://github.com/user/open-site.git".to_owned(),
                branch: "main".to_owned(),
                webhook_token: String::new(),
                webhook_token_file: None,
                build_overrides: BuildOverrides::default(),
                poll_interval: None,
                build_timeout: None,
                cache_dirs: None,
                post_deploy: None,
                env: None,
                container_memory: None,
                container_cpus: None,
                container_pids_limit: None,
                container_network: "none".to_owned(),
                git_depth: None,
                container_workdir: None,
                config_file: None,
            }],
            ..test_config()
        }
    }

    #[tokio::test]
    async fn deploy_disabled_auth_returns_accepted() {
        let (server, _state, port) = test_server(test_config_with_disabled_auth());
        let client = reqwest::Client::new();

        // Request without Authorization header should succeed
        let resp = client
            .post(format!("http://127.0.0.1:{port}/open-site"))
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status().as_u16(), 202);

        server.unblock();
    }

    #[tokio::test]
    async fn deploy_disabled_auth_ignores_token() {
        let (server, _state, port) = test_server(test_config_with_disabled_auth());
        let client = reqwest::Client::new();

        // Request WITH a Bearer token should also succeed (token ignored)
        let resp = client
            .post(format!("http://127.0.0.1:{port}/open-site"))
            .header("Authorization", "Bearer any-token")
            .send()
            .await
            .unwrap();
        assert_eq!(resp.status().as_u16(), 202);

        server.unblock();
    }
}