everruns-platform 0.19.2

Backend control-plane entities and store contracts for the Everruns Platform
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
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
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
//! Docker Engine REST API client.
//!
//! Decision: Uses reqwest for HTTP/TCP connections to Docker Engine API v1.47.
//! Docker host resolution: config → env `CONTAINER_SANDBOX_DOCKER_HOST` → default
//! `unix:///var/run/docker.sock` (the secure local default).
//! Unix socket transport is not yet supported by this reqwest-based client (it
//! requires a hyper unix connector). Until that lands, leaving the host at the
//! default fails closed at request time with a clear error instead of silently
//! falling back to an unauthenticated network endpoint. See TM-SANDBOX-011.
//!
//! Security: the default must never be a plaintext, unauthenticated TCP endpoint
//! (e.g. `http://localhost:2375`). Such an endpoint, if ever reachable over a
//! network, grants full Docker control of the host (container escape). Operators
//! that need a TCP daemon must set `CONTAINER_SANDBOX_DOCKER_HOST` explicitly and
//! protect it with mTLS (`https://`); plaintext TCP must never be networked.
//!
//! Decision: All methods return `Result<T, String>` for consistency with the Daytona client
//! pattern and easy mapping to ToolExecutionResult errors.

use serde::{Deserialize, Serialize};
use serde_json::{Value, json};
use std::io::Read as _;
use tracing::{debug, warn};

/// Docker Engine API version prefix.
const API_VERSION: &str = "/v1.47";

/// Default Docker host when no config or env is set.
///
/// The local unix socket is the secure default: it is host-local and protected
/// by filesystem permissions rather than exposed on the network. It is
/// deliberately NOT a plaintext TCP endpoint — an unauthenticated
/// `http://localhost:2375` default would grant full host control if ever
/// networked (see TM-SANDBOX-011). Unix-socket transport is not yet implemented
/// by this client, so this default fails closed (see `resolve_docker_host`).
const DEFAULT_DOCKER_HOST: &str = "unix:///var/run/docker.sock";

/// Environment variable for Docker host override.
const DOCKER_HOST_ENV: &str = "CONTAINER_SANDBOX_DOCKER_HOST";
const MAX_EXEC_OUTPUT_BYTES: usize = 8 * 1024 * 1024;
const MAX_ARCHIVE_RESPONSE_BYTES: usize = 8 * 1024 * 1024;
const MAX_ARCHIVE_FILE_BYTES: usize = 4 * 1024 * 1024;

// ============================================================================
// Types
// ============================================================================

/// Container creation configuration.
#[derive(Debug, Clone, Serialize)]
pub struct ContainerCreateConfig {
    #[serde(rename = "Image")]
    pub image: String,
    #[serde(rename = "Cmd")]
    pub cmd: Vec<String>,
    #[serde(rename = "WorkingDir")]
    pub working_dir: String,
    #[serde(rename = "Labels")]
    pub labels: std::collections::HashMap<String, String>,
    #[serde(rename = "HostConfig")]
    pub host_config: HostConfig,
}

/// Container host configuration (resource limits, networking).
#[derive(Debug, Clone, Serialize)]
pub struct HostConfig {
    #[serde(rename = "Runtime", skip_serializing_if = "String::is_empty")]
    pub runtime: String,
    #[serde(rename = "NetworkMode")]
    pub network_mode: String,
    #[serde(rename = "Memory")]
    pub memory: i64,
    #[serde(rename = "NanoCpus")]
    pub nano_cpus: i64,
    #[serde(rename = "PidsLimit")]
    pub pids_limit: i64,
    #[serde(rename = "Init")]
    pub init: bool,
}

/// Response from container create.
#[derive(Debug, Deserialize)]
pub struct ContainerCreateResponse {
    #[serde(rename = "Id")]
    pub id: String,
    #[serde(rename = "Warnings", default)]
    pub warnings: Vec<String>,
}

/// Container inspect response (subset of fields we need).
#[derive(Debug, Deserialize)]
pub struct ContainerInspect {
    #[serde(rename = "Id")]
    pub id: String,
    #[serde(rename = "State")]
    pub state: ContainerState,
    #[serde(rename = "Name")]
    pub name: String,
}

/// Container state from inspect.
#[derive(Debug, Deserialize)]
pub struct ContainerState {
    #[serde(rename = "Status")]
    pub status: String,
    #[serde(rename = "Running")]
    pub running: bool,
    #[serde(rename = "ExitCode")]
    pub exit_code: i64,
}

/// Container list item.
#[derive(Debug, Deserialize)]
pub struct ContainerListItem {
    #[serde(rename = "Id")]
    pub id: String,
    #[serde(rename = "Names")]
    pub names: Vec<String>,
    #[serde(rename = "State")]
    pub state: String,
    #[serde(rename = "Status")]
    pub status: String,
    #[serde(rename = "Labels")]
    pub labels: std::collections::HashMap<String, String>,
}

/// Exec create response.
#[derive(Debug, Deserialize)]
pub struct ExecCreateResponse {
    #[serde(rename = "Id")]
    pub id: String,
}

/// Exec inspect response.
#[derive(Debug, Deserialize)]
pub struct ExecInspect {
    #[serde(rename = "ExitCode")]
    pub exit_code: Option<i64>,
    #[serde(rename = "Running")]
    pub running: bool,
}

/// Result of exec start (captured output).
pub struct ExecOutput {
    pub output: String,
    pub exit_code: i64,
}

// ============================================================================
// DockerClient
// ============================================================================

pub struct DockerClient {
    http: reqwest::Client,
    /// Resolved HTTP base URL, or a deferred fail-closed error if the configured
    /// host uses a transport this client cannot speak (currently: unix sockets).
    /// We surface the error on the first request rather than panicking in `new`.
    base_url: Result<String, String>,
}

impl DockerClient {
    /// Create a new DockerClient.
    ///
    /// Host resolution priority:
    /// 1. Explicit `docker_host` parameter (from config)
    /// 2. `CONTAINER_SANDBOX_DOCKER_HOST` env var
    /// 3. Default: `unix:///var/run/docker.sock` (secure local default)
    ///
    /// The default unix socket is not yet supported by this reqwest-based
    /// transport, so when the resolved host is a unix socket the client fails
    /// closed: requests return a clear error asking the operator to set
    /// `CONTAINER_SANDBOX_DOCKER_HOST` to an `http(s)://` daemon (protected with
    /// mTLS for any non-loopback address). This is deliberately safer than
    /// silently defaulting to an unauthenticated `http://localhost:2375`.
    pub fn new(docker_host: Option<&str>) -> Self {
        let raw_host = docker_host
            .map(String::from)
            .or_else(|| std::env::var(DOCKER_HOST_ENV).ok())
            .unwrap_or_else(|| DEFAULT_DOCKER_HOST.to_string());

        let base_url = resolve_docker_host(&raw_host);

        match &base_url {
            Ok(url) => debug!(base_url = %url, "DockerClient initialized"),
            Err(e) => warn!(error = %e, "DockerClient initialized with unusable Docker host"),
        }

        let http = reqwest::Client::builder()
            .connect_timeout(std::time::Duration::from_secs(30))
            .timeout(std::time::Duration::from_secs(300))
            .build()
            .expect("failed to build reqwest client");

        Self { http, base_url }
    }

    /// For tests: create with explicit base URL.
    #[cfg(test)]
    pub fn with_base_url(base_url: String) -> Self {
        let base_url = Ok(base_url.trim_end_matches('/').to_string());
        let http = reqwest::Client::builder()
            .connect_timeout(std::time::Duration::from_secs(30))
            .timeout(std::time::Duration::from_secs(300))
            .build()
            .expect("failed to build reqwest client");
        Self { http, base_url }
    }

    /// Build a full request URL, propagating the deferred host-resolution error
    /// (e.g. an unsupported unix-socket default) as a request-time failure.
    fn url(&self, path: &str) -> Result<String, String> {
        let base = self.base_url.as_ref().map_err(|e| e.clone())?;
        Ok(format!("{base}{API_VERSION}{path}"))
    }

    // --- Generic request helpers ---

    async fn request(
        &self,
        method: reqwest::Method,
        path: &str,
        body: Option<Value>,
    ) -> Result<Value, String> {
        let url = self.url(path)?;
        let mut req = self
            .http
            .request(method, &url)
            .header("Content-Type", "application/json");

        if let Some(b) = body {
            req = req.json(&b);
        }

        let resp = req
            .send()
            .await
            .map_err(|e| format!("Docker API connection failed: {e}"))?;

        let status = resp.status();
        let body_text = resp
            .text()
            .await
            .map_err(|e| format!("Failed to read Docker response: {e}"))?;

        if !status.is_success() {
            return Err(map_docker_error(status.as_u16(), &body_text));
        }

        if body_text.is_empty() {
            return Ok(json!({}));
        }

        serde_json::from_str(&body_text).map_err(|e| format!("Invalid JSON from Docker: {e}"))
    }

    async fn request_typed<T: serde::de::DeserializeOwned>(
        &self,
        method: reqwest::Method,
        path: &str,
        body: Option<Value>,
    ) -> Result<T, String> {
        let url = self.url(path)?;
        let mut req = self
            .http
            .request(method, &url)
            .header("Content-Type", "application/json");

        if let Some(b) = body {
            req = req.json(&b);
        }

        let resp = req
            .send()
            .await
            .map_err(|e| format!("Docker API connection failed: {e}"))?;

        let status = resp.status();
        let body_text = resp
            .text()
            .await
            .map_err(|e| format!("Failed to read Docker response: {e}"))?;

        if !status.is_success() {
            return Err(map_docker_error(status.as_u16(), &body_text));
        }

        serde_json::from_str(&body_text).map_err(|e| format!("Invalid JSON from Docker: {e}"))
    }

    async fn request_bytes_limited(
        &self,
        method: reqwest::Method,
        path: &str,
        max_bytes: usize,
    ) -> Result<Vec<u8>, String> {
        let url = self.url(path)?;
        let mut resp = self
            .http
            .request(method, &url)
            .send()
            .await
            .map_err(|e| format!("Docker API connection failed: {e}"))?;

        let status = resp.status();
        if !status.is_success() {
            let body_text = resp
                .text()
                .await
                .map_err(|e| format!("Failed to read response: {e}"))?;
            return Err(map_docker_error(status.as_u16(), &body_text));
        }

        read_response_bytes_limited(&mut resp, max_bytes).await
    }

    async fn request_no_content(
        &self,
        method: reqwest::Method,
        path: &str,
        body: Option<Value>,
    ) -> Result<(), String> {
        let url = self.url(path)?;
        let mut req = self
            .http
            .request(method, &url)
            .header("Content-Type", "application/json");

        if let Some(b) = body {
            req = req.json(&b);
        }

        let resp = req
            .send()
            .await
            .map_err(|e| format!("Docker API connection failed: {e}"))?;

        let status = resp.status();
        if !status.is_success() {
            let body_text = resp
                .text()
                .await
                .map_err(|e| format!("Failed to read response: {e}"))?;
            return Err(map_docker_error(status.as_u16(), &body_text));
        }

        Ok(())
    }

    // ========================================================================
    // Network operations
    // ========================================================================

    /// Create an isolated bridge network for a sandbox.
    pub async fn create_network(
        &self,
        name: &str,
        labels: std::collections::HashMap<String, String>,
    ) -> Result<String, String> {
        debug!(name = %name, "Creating Docker network");
        let body = json!({
            "Name": name,
            "Driver": "bridge",
            "Labels": labels,
        });
        let resp: Value = self
            .request(reqwest::Method::POST, "/networks/create", Some(body))
            .await?;
        resp.get("Id")
            .and_then(|v| v.as_str())
            .map(String::from)
            .ok_or_else(|| "Missing network Id in response".to_string())
    }

    /// Remove a network by ID.
    pub async fn remove_network(&self, id: &str) -> Result<(), String> {
        debug!(id = %id, "Removing Docker network");
        self.request_no_content(reqwest::Method::DELETE, &format!("/networks/{id}"), None)
            .await
    }

    // ========================================================================
    // Container lifecycle
    // ========================================================================

    /// Create a container with the given configuration.
    pub async fn create_container(
        &self,
        name: &str,
        config: &ContainerCreateConfig,
    ) -> Result<ContainerCreateResponse, String> {
        debug!(name = %name, image = %config.image, "Creating container");
        let body =
            serde_json::to_value(config).map_err(|e| format!("Failed to serialize config: {e}"))?;
        let encoded_name = urlencoding::encode(name);
        self.request_typed(
            reqwest::Method::POST,
            &format!("/containers/create?name={encoded_name}"),
            Some(body),
        )
        .await
    }

    /// Start a stopped container.
    pub async fn start_container(&self, id: &str) -> Result<(), String> {
        debug!(id = %id, "Starting container");
        self.request_no_content(
            reqwest::Method::POST,
            &format!("/containers/{id}/start"),
            None,
        )
        .await
    }

    /// Gracefully stop a running container.
    pub async fn stop_container(&self, id: &str, timeout_seconds: u32) -> Result<(), String> {
        debug!(id = %id, timeout = timeout_seconds, "Stopping container");
        self.request_no_content(
            reqwest::Method::POST,
            &format!("/containers/{id}/stop?t={timeout_seconds}"),
            None,
        )
        .await
    }

    /// Remove a container (force remove if running).
    pub async fn remove_container(&self, id: &str) -> Result<(), String> {
        debug!(id = %id, "Removing container");
        self.request_no_content(
            reqwest::Method::DELETE,
            &format!("/containers/{id}?force=true"),
            None,
        )
        .await
    }

    /// Inspect a container (get detailed state).
    pub async fn inspect_container(&self, id: &str) -> Result<ContainerInspect, String> {
        self.request_typed(
            reqwest::Method::GET,
            &format!("/containers/{id}/json"),
            None,
        )
        .await
    }

    /// List containers matching label filters.
    pub async fn list_containers(
        &self,
        label_filters: &[(&str, &str)],
    ) -> Result<Vec<ContainerListItem>, String> {
        let filters: std::collections::HashMap<&str, Vec<String>> =
            std::collections::HashMap::from([(
                "label",
                label_filters
                    .iter()
                    .map(|(k, v)| format!("{k}={v}"))
                    .collect(),
            )]);

        let filters_json =
            serde_json::to_string(&filters).map_err(|e| format!("Filter encoding error: {e}"))?;

        self.request_typed(
            reqwest::Method::GET,
            &format!(
                "/containers/json?all=true&filters={}",
                urlencoding::encode(&filters_json)
            ),
            None,
        )
        .await
    }

    // ========================================================================
    // Exec operations
    // ========================================================================

    /// Create an exec instance in a container.
    pub async fn exec_create(
        &self,
        container_id: &str,
        cmd: &[&str],
        working_dir: Option<&str>,
    ) -> Result<String, String> {
        debug!(container_id = %container_id, cmd = ?cmd, "Creating exec instance");
        let mut body = json!({
            "AttachStdout": true,
            "AttachStderr": true,
            "Cmd": cmd,
        });
        if let Some(wd) = working_dir {
            body["WorkingDir"] = json!(wd);
        }

        let resp: ExecCreateResponse = self
            .request_typed(
                reqwest::Method::POST,
                &format!("/containers/{container_id}/exec"),
                Some(body),
            )
            .await?;
        Ok(resp.id)
    }

    /// Start an exec instance and capture output.
    ///
    /// Docker multiplexes stdout/stderr into a single stream with 8-byte headers.
    /// We demux the stream and combine stdout+stderr into a single string.
    pub async fn exec_start(&self, exec_id: &str) -> Result<String, String> {
        debug!(exec_id = %exec_id, "Starting exec");
        let url = self.url(&format!("/exec/{exec_id}/start"))?;
        let resp = self
            .http
            .post(&url)
            .header("Content-Type", "application/json")
            .json(&json!({"Detach": false, "Tty": false}))
            .send()
            .await
            .map_err(|e| format!("Docker exec start failed: {e}"))?;

        let status = resp.status();
        if !status.is_success() {
            let body_text = resp
                .text()
                .await
                .map_err(|e| format!("Failed to read response: {e}"))?;
            return Err(map_docker_error(status.as_u16(), &body_text));
        }

        let mut resp = resp;
        let raw = read_response_bytes_limited(&mut resp, MAX_EXEC_OUTPUT_BYTES)
            .await
            .map_err(|e| format!("Failed to read exec output: {e}"))?;

        Ok(demux_docker_stream(&raw))
    }

    /// Get the exit code of a completed exec instance.
    pub async fn exec_inspect(&self, exec_id: &str) -> Result<ExecInspect, String> {
        self.request_typed(reqwest::Method::GET, &format!("/exec/{exec_id}/json"), None)
            .await
    }

    /// Execute a command and return combined output + exit code.
    ///
    /// After `exec_start` returns (which blocks until the command finishes),
    /// `exec_inspect` should report the exit code. In rare cases the exit code
    /// may not yet be populated, so we retry up to 3 times with a brief delay.
    pub async fn exec(
        &self,
        container_id: &str,
        cmd: &[&str],
        working_dir: Option<&str>,
    ) -> Result<ExecOutput, String> {
        let exec_id = self.exec_create(container_id, cmd, working_dir).await?;
        let output = self.exec_start(&exec_id).await?;

        // Retry inspect up to 3 times to handle rare race where exit_code is not yet set.
        let mut exit_code: Option<i64> = None;
        for attempt in 0..3 {
            let inspect = self.exec_inspect(&exec_id).await?;
            if let Some(code) = inspect.exit_code {
                exit_code = Some(code);
                break;
            }
            if attempt < 2 {
                debug!(exec_id = %exec_id, attempt = attempt + 1, "exec_inspect returned no exit_code, retrying");
                tokio::time::sleep(std::time::Duration::from_millis(100)).await;
            }
        }

        Ok(ExecOutput {
            output,
            exit_code: exit_code.unwrap_or(-1),
        })
    }

    // ========================================================================
    // File operations (tar-based archive API)
    // ========================================================================

    /// Read a file from a container via the archive API.
    /// Returns the file content as bytes.
    pub async fn get_archive(&self, container_id: &str, path: &str) -> Result<Vec<u8>, String> {
        debug!(container_id = %container_id, path = %path, "Reading file from container");
        let encoded_path = urlencoding::encode(path);
        let tar_bytes = self
            .request_bytes_limited(
                reqwest::Method::GET,
                &format!("/containers/{container_id}/archive?path={encoded_path}"),
                MAX_ARCHIVE_RESPONSE_BYTES,
            )
            .await?;

        extract_file_from_tar(&tar_bytes, MAX_ARCHIVE_FILE_BYTES)
    }

    /// Write a file to a container via the archive API.
    /// Content is wrapped in a tar archive and PUT to the container.
    pub async fn put_archive(
        &self,
        container_id: &str,
        dir_path: &str,
        filename: &str,
        content: &[u8],
    ) -> Result<(), String> {
        sanitize_filename(filename)?;
        debug!(container_id = %container_id, dir_path = %dir_path, filename = %filename, "Writing file to container");
        let tar_bytes = create_tar_with_file(filename, content)?;
        let encoded_path = urlencoding::encode(dir_path);
        let url = self.url(&format!(
            "/containers/{container_id}/archive?path={encoded_path}"
        ))?;

        let resp = self
            .http
            .put(&url)
            .header("Content-Type", "application/x-tar")
            .body(tar_bytes)
            .send()
            .await
            .map_err(|e| format!("Docker archive upload failed: {e}"))?;

        let status = resp.status();
        if !status.is_success() {
            let body_text = resp
                .text()
                .await
                .map_err(|e| format!("Failed to read response: {e}"))?;
            return Err(map_docker_error(status.as_u16(), &body_text));
        }

        Ok(())
    }
}

// ============================================================================
// Helpers
// ============================================================================

/// Resolve a raw Docker host string into an HTTP base URL this client can use.
///
/// `http://` and `https://` hosts are accepted (trailing slashes trimmed).
/// Unix-socket hosts (`unix://`, including the secure default
/// `unix:///var/run/docker.sock`) and any other unsupported scheme fail closed
/// with an actionable error: this reqwest-based client cannot speak the unix
/// transport yet, and we must never silently fall back to an unauthenticated
/// network endpoint. The error is surfaced at request time. See TM-SANDBOX-011.
fn resolve_docker_host(raw: &str) -> Result<String, String> {
    let host = raw.trim();
    if host.starts_with("http://") || host.starts_with("https://") {
        return Ok(host.trim_end_matches('/').to_string());
    }
    if host.starts_with("unix://") {
        return Err(format!(
            "Docker host '{host}' uses a unix socket, which this client does not \
             support yet. Set CONTAINER_SANDBOX_DOCKER_HOST to an http(s):// Docker \
             daemon (use https:// with mTLS for any non-loopback address; never \
             expose plaintext TCP on a network)."
        ));
    }
    Err(format!(
        "Unsupported Docker host '{host}'. Set CONTAINER_SANDBOX_DOCKER_HOST to an \
         http(s):// Docker daemon URL (use https:// with mTLS for any non-loopback \
         address)."
    ))
}

/// Validate that a filename is safe for use inside a tar archive.
/// Rejects path traversal (`..`), absolute paths (`/`), and backslash separators.
fn sanitize_filename(filename: &str) -> Result<(), String> {
    if filename.is_empty() {
        return Err("Filename must not be empty".to_string());
    }
    if filename.contains("..") {
        return Err(format!("Filename contains path traversal (..): {filename}"));
    }
    if filename.contains('/') {
        return Err(format!(
            "Filename contains directory separator (/): {filename}"
        ));
    }
    if filename.contains('\\') {
        return Err(format!(
            "Filename contains backslash separator (\\): {filename}"
        ));
    }
    Ok(())
}

/// Map Docker API HTTP errors to human-readable messages.
fn map_docker_error(status: u16, body: &str) -> String {
    // Try to extract Docker's error message from JSON response
    let detail = serde_json::from_str::<Value>(body)
        .ok()
        .and_then(|v| v.get("message").and_then(|m| m.as_str()).map(String::from))
        .unwrap_or_else(|| body.to_string());

    match status {
        304 => format!("Container already in requested state: {detail}"),
        404 => format!("Not found: {detail}"),
        409 => format!("Conflict (container/network already exists): {detail}"),
        500 => {
            if detail.contains("runtime not found") {
                format!("Container runtime not found. Is sysbox installed? ({detail})")
            } else {
                format!("Docker Engine error: {detail}")
            }
        }
        _ => format!("Docker API error (HTTP {status}): {detail}"),
    }
}

/// Demultiplex Docker's multiplexed stdout/stderr stream.
///
/// Docker exec with `Tty: false` returns a stream where each frame has:
/// - byte 0: stream type (1 = stdout, 2 = stderr)
/// - bytes 1-3: reserved (zero)
/// - bytes 4-7: big-endian payload size
/// - bytes 8..8+size: payload
fn demux_docker_stream(raw: &[u8]) -> String {
    let mut output = String::new();
    let mut pos = 0;

    while pos + 8 <= raw.len() {
        // Stream type at byte 0 (we combine stdout+stderr)
        let size =
            u32::from_be_bytes([raw[pos + 4], raw[pos + 5], raw[pos + 6], raw[pos + 7]]) as usize;
        pos += 8;

        if pos + size > raw.len() {
            warn!(
                expected = size,
                available = raw.len() - pos,
                "Truncated Docker stream frame"
            );
            // Append whatever we have
            output.push_str(&String::from_utf8_lossy(&raw[pos..]));
            break;
        }

        output.push_str(&String::from_utf8_lossy(&raw[pos..pos + size]));
        pos += size;
    }

    output
}

/// Extract the first regular file's content from a tar archive (Docker GET /archive response).
/// Skips directory entries to find the actual file content.
fn extract_file_from_tar(tar_bytes: &[u8], max_bytes: usize) -> Result<Vec<u8>, String> {
    let mut archive = tar::Archive::new(tar_bytes);
    let entries = archive
        .entries()
        .map_err(|e| format!("Failed to read tar archive: {e}"))?;

    for entry_result in entries {
        let mut entry = entry_result.map_err(|e| format!("Failed to read tar entry: {e}"))?;
        let entry_type = entry.header().entry_type();
        if entry_type.is_dir() {
            continue;
        }
        let file_size = entry
            .header()
            .size()
            .map_err(|e| format!("Failed to read tar header size: {e}"))?;
        if file_size > max_bytes as u64 {
            return Err(format!(
                "File from tar exceeds maximum size ({file_size} > {max_bytes} bytes)"
            ));
        }
        let mut content = Vec::new();
        entry
            .read_to_end(&mut content)
            .map_err(|e| format!("Failed to read file from tar: {e}"))?;
        if content.len() > max_bytes {
            return Err(format!(
                "File from tar exceeds maximum size ({} > {max_bytes} bytes)",
                content.len()
            ));
        }
        return Ok(content);
    }

    Err("No regular file found in tar archive".to_string())
}

async fn read_response_bytes_limited(
    resp: &mut reqwest::Response,
    max_bytes: usize,
) -> Result<Vec<u8>, String> {
    let mut buffer = Vec::new();
    while let Some(chunk) = resp
        .chunk()
        .await
        .map_err(|e| format!("Failed to read bytes: {e}"))?
    {
        let new_len = buffer
            .len()
            .checked_add(chunk.len())
            .ok_or_else(|| "Response size overflow".to_string())?;
        if new_len > max_bytes {
            return Err(format!(
                "Response exceeds maximum size ({new_len} > {max_bytes} bytes)"
            ));
        }
        buffer.extend_from_slice(&chunk);
    }
    Ok(buffer)
}

/// Create a tar archive containing a single file.
fn create_tar_with_file(filename: &str, content: &[u8]) -> Result<Vec<u8>, String> {
    let mut builder = tar::Builder::new(Vec::new());
    let mut header = tar::Header::new_gnu();
    header.set_size(content.len() as u64);
    header.set_mode(0o644);
    header.set_cksum();
    builder
        .append_data(&mut header, filename, content)
        .map_err(|e| format!("Failed to create tar archive: {e}"))?;
    builder
        .into_inner()
        .map_err(|e| format!("Failed to finalize tar archive: {e}"))
}

// ============================================================================
// Tests
// ============================================================================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_url_construction() {
        let client = DockerClient::with_base_url("http://10.0.0.3:2375".to_string());
        assert_eq!(
            client.url("/containers/json").unwrap(),
            "http://10.0.0.3:2375/v1.47/containers/json"
        );
    }

    #[test]
    fn test_resolve_docker_host_accepts_http() {
        assert_eq!(
            resolve_docker_host("http://localhost:2375").unwrap(),
            "http://localhost:2375"
        );
    }

    #[test]
    fn test_resolve_docker_host_accepts_https_and_trims_slash() {
        assert_eq!(
            resolve_docker_host("https://docker.internal:2376/").unwrap(),
            "https://docker.internal:2376"
        );
    }

    #[test]
    fn test_resolve_docker_host_default_is_secure_unix_socket() {
        // The default must be the host-local unix socket, never plaintext TCP.
        assert_eq!(DEFAULT_DOCKER_HOST, "unix:///var/run/docker.sock");
    }

    #[test]
    fn test_resolve_docker_host_unix_socket_fails_closed() {
        // Unix-socket transport is unsupported today; it must fail closed with an
        // actionable error rather than fall back to an unauthenticated endpoint.
        let err = resolve_docker_host(DEFAULT_DOCKER_HOST).unwrap_err();
        assert!(err.contains("unix socket"), "unexpected error: {err}");
        assert!(
            err.contains("CONTAINER_SANDBOX_DOCKER_HOST"),
            "error should name the override env var: {err}"
        );
    }

    #[test]
    fn test_resolve_docker_host_unknown_scheme_fails_closed() {
        let err = resolve_docker_host("tcp://10.0.0.3:2375").unwrap_err();
        assert!(err.contains("Unsupported Docker host"), "got: {err}");
    }

    #[test]
    fn test_default_client_fails_closed_at_url_build() {
        // With no config/env, the default unix socket means url() returns the
        // deferred fail-closed error instead of building a plaintext-TCP URL.
        // Note: relies on CONTAINER_SANDBOX_DOCKER_HOST being unset in this env.
        if std::env::var(DOCKER_HOST_ENV).is_err() {
            let client = DockerClient::new(None);
            let err = client.url("/containers/json").unwrap_err();
            assert!(err.contains("unix socket"), "unexpected error: {err}");
        }
    }

    #[test]
    fn test_demux_docker_stream_stdout() {
        // stdout frame: type=1, size=5, payload="hello"
        let mut frame = vec![1, 0, 0, 0, 0, 0, 0, 5]; // header
        frame.extend_from_slice(b"hello");
        assert_eq!(demux_docker_stream(&frame), "hello");
    }

    #[test]
    fn test_demux_docker_stream_mixed() {
        // stdout "hello", stderr " world"
        let mut frame = vec![1, 0, 0, 0, 0, 0, 0, 5];
        frame.extend_from_slice(b"hello");
        frame.extend_from_slice(&[2, 0, 0, 0, 0, 0, 0, 6]);
        frame.extend_from_slice(b" world");
        assert_eq!(demux_docker_stream(&frame), "hello world");
    }

    #[test]
    fn test_demux_empty_stream() {
        assert_eq!(demux_docker_stream(&[]), "");
    }

    #[test]
    fn test_demux_truncated_frame() {
        // Frame claims 100 bytes but only 3 available
        let mut frame = vec![1, 0, 0, 0, 0, 0, 0, 100];
        frame.extend_from_slice(b"abc");
        assert_eq!(demux_docker_stream(&frame), "abc");
    }

    #[test]
    fn test_create_and_extract_tar() {
        let content = b"Hello, container!";
        let tar_bytes = create_tar_with_file("test.txt", content).unwrap();
        let extracted = extract_file_from_tar(&tar_bytes, 1024).unwrap();
        assert_eq!(extracted, content);
    }

    #[test]
    fn test_map_docker_error_not_found() {
        let msg = map_docker_error(404, r#"{"message":"No such container: abc123"}"#);
        assert!(msg.contains("Not found"));
        assert!(msg.contains("No such container"));
    }

    #[test]
    fn test_map_docker_error_conflict() {
        let msg = map_docker_error(409, r#"{"message":"name already in use"}"#);
        assert!(msg.contains("Conflict"));
    }

    #[test]
    fn test_map_docker_error_runtime_not_found() {
        let msg = map_docker_error(500, r#"{"message":"OCI runtime not found: sysbox-runc"}"#);
        assert!(msg.contains("runtime not found"));
        assert!(msg.contains("sysbox"));
    }

    #[test]
    fn test_container_create_config_serialization() {
        let config = ContainerCreateConfig {
            image: "ubuntu:24.04".to_string(),
            cmd: vec![
                "tail".to_string(),
                "-f".to_string(),
                "/dev/null".to_string(),
            ],
            working_dir: "/workspace".to_string(),
            labels: std::collections::HashMap::from([(
                "managed-by".to_string(),
                "everruns".to_string(),
            )]),
            host_config: HostConfig {
                runtime: String::new(),
                network_mode: "bridge".to_string(),
                memory: 2_147_483_648,
                nano_cpus: 1_000_000_000,
                pids_limit: 256,
                init: true,
            },
        };

        let json = serde_json::to_value(&config).unwrap();
        assert_eq!(json["Image"], "ubuntu:24.04");
        assert_eq!(json["HostConfig"]["Memory"], 2_147_483_648_i64);
        assert_eq!(json["HostConfig"]["Init"], true);
        // Empty runtime should not appear in serialized output
        assert!(json["HostConfig"].get("Runtime").is_none());
    }

    #[test]
    fn test_label_filter_encoding() {
        let filters: std::collections::HashMap<&str, Vec<String>> =
            std::collections::HashMap::from([(
                "label",
                vec![
                    "managed-by=everruns".to_string(),
                    "session=abc123".to_string(),
                ],
            )]);
        let json = serde_json::to_string(&filters).unwrap();
        assert!(json.contains("managed-by=everruns"));
        assert!(json.contains("session=abc123"));
    }

    #[test]
    fn test_url_trailing_slash_trimmed() {
        let client = DockerClient::with_base_url("http://10.0.0.3:2375/".to_string());
        assert_eq!(
            client.url("/containers/json").unwrap(),
            "http://10.0.0.3:2375/v1.47/containers/json"
        );
    }

    #[test]
    fn test_sanitize_filename_rejects_dot_dot() {
        let err = sanitize_filename("../etc/passwd").unwrap_err();
        assert!(err.contains("path traversal"));
    }

    #[test]
    fn test_sanitize_filename_rejects_embedded_dot_dot() {
        let err = sanitize_filename("foo/../bar").unwrap_err();
        assert!(err.contains("path traversal"));
    }

    #[test]
    fn test_sanitize_filename_rejects_slash() {
        let err = sanitize_filename("subdir/file.txt").unwrap_err();
        assert!(err.contains("directory separator"));
    }

    #[test]
    fn test_sanitize_filename_rejects_backslash() {
        let err = sanitize_filename("subdir\\file.txt").unwrap_err();
        assert!(err.contains("backslash"));
    }

    #[test]
    fn test_sanitize_filename_rejects_empty() {
        let err = sanitize_filename("").unwrap_err();
        assert!(err.contains("empty"));
    }

    #[test]
    fn test_sanitize_filename_accepts_valid() {
        assert!(sanitize_filename("hello.txt").is_ok());
        assert!(sanitize_filename("my-file_v2.tar.gz").is_ok());
    }

    #[test]
    fn test_extract_tar_skips_directories() {
        // Build a tar with a directory entry followed by a regular file.
        let mut builder = tar::Builder::new(Vec::new());

        // Add a directory entry
        let mut dir_header = tar::Header::new_gnu();
        dir_header.set_entry_type(tar::EntryType::Directory);
        dir_header.set_size(0);
        dir_header.set_mode(0o755);
        dir_header.set_cksum();
        builder
            .append_data(&mut dir_header, "mydir/", &[] as &[u8])
            .unwrap();

        // Add a regular file
        let content = b"file content";
        let mut file_header = tar::Header::new_gnu();
        file_header.set_size(content.len() as u64);
        file_header.set_mode(0o644);
        file_header.set_cksum();
        builder
            .append_data(&mut file_header, "mydir/file.txt", &content[..])
            .unwrap();

        let tar_bytes = builder.into_inner().unwrap();
        let extracted = extract_file_from_tar(&tar_bytes, 1024).unwrap();
        assert_eq!(extracted, content);
    }

    #[test]
    fn test_extract_tar_rejects_large_file() {
        let content = vec![b'a'; 32];
        let tar_bytes = create_tar_with_file("large.txt", &content).unwrap();
        let err = extract_file_from_tar(&tar_bytes, 16).unwrap_err();
        assert!(err.contains("exceeds maximum size"));
    }
}