bext-php 0.2.0

Embedded PHP runtime for bext — custom SAPI linking libphp via Rust FFI
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
//! PHP runtime configuration.
//!
//! Parsed from the `[php]` section of `bext.config.toml`.

use serde::Deserialize;

/// Configuration for the embedded PHP runtime.
#[derive(Debug, Deserialize)]
pub struct PhpConfig {
    /// Enable the PHP runtime. Default: false.
    #[serde(default)]
    pub enabled: bool,

    /// Document root for PHP scripts. Requests are resolved relative to this.
    /// Default: "./public"
    #[serde(default = "default_document_root")]
    pub document_root: String,

    /// Number of PHP worker threads. Default: number of CPU cores.
    /// Each thread holds a PHP TSRM context and processes one request at a time.
    pub workers: Option<usize>,

    /// PHP INI overrides (key=value pairs).
    ///
    /// Example:
    /// ```toml
    /// [php.ini]
    /// display_errors = "Off"
    /// memory_limit = "256M"
    /// opcache.enable = "1"
    /// ```
    #[serde(default)]
    pub ini: std::collections::HashMap<String, String>,

    /// File extensions to treat as PHP scripts. Default: [".php"]
    #[serde(default = "default_extensions")]
    pub extensions: Vec<String>,

    /// Index file name for directory requests. Default: "index.php"
    #[serde(default = "default_index")]
    pub index: String,

    /// Maximum request body size in bytes. Default: 8MB.
    #[serde(default = "default_max_body")]
    pub max_body_bytes: usize,

    /// Maximum execution time per request in seconds. Default: 30.
    #[serde(default = "default_max_execution_time")]
    pub max_execution_time: u32,

    /// Enable ISR caching for PHP responses. Default: true.
    /// GET requests with 200 status are cached using the ISR cache with
    /// tag-based invalidation. POST/PUT/DELETE requests bypass the cache.
    /// Use route_rules to control TTL per path pattern.
    #[serde(default = "default_true_val")]
    pub cache_responses: bool,

    /// Worker lifecycle: rotate after this many requests. Default: 10000.
    /// Helps contain memory leaks in PHP extensions.
    #[serde(default = "default_max_requests")]
    pub max_requests: u64,

    /// Worker mode: path to the worker PHP script.
    /// When set, bext-php boots this script once per thread and dispatches
    /// requests to its `bext_handle_request($callback)` loop.
    /// Eliminates per-request framework bootstrap (~3ms for Laravel).
    ///
    /// Example worker script:
    /// ```php
    /// $app = require __DIR__.'/../bootstrap/app.php';
    /// $kernel = $app->make(\Illuminate\Contracts\Http\Kernel::class);
    /// while (bext_handle_request(function() use ($kernel) {
    ///     $response = $kernel->handle($request = \Illuminate\Http\Request::capture());
    ///     $response->send();
    ///     $kernel->terminate($request, $response);
    /// })) { gc_collect_cycles(); }
    /// ```
    pub worker_script: Option<String>,
}

impl Default for PhpConfig {
    fn default() -> Self {
        Self {
            enabled: false,
            document_root: default_document_root(),
            workers: None,
            ini: std::collections::HashMap::new(),
            extensions: default_extensions(),
            index: default_index(),
            max_body_bytes: default_max_body(),
            max_execution_time: default_max_execution_time(),
            max_requests: default_max_requests(),
            worker_script: None,
            cache_responses: true,
        }
    }
}

fn default_true_val() -> bool {
    true
}

impl PhpConfig {
    /// Effective worker count (configured or CPU count).
    ///
    /// NTS (non-thread-safe) PHP is limited to 1 worker because the PHP
    /// interpreter uses global state without TSRM protection.  ZTS builds
    /// can use multiple workers safely.
    pub fn effective_workers(&self) -> usize {
        let requested = self.workers.unwrap_or_else(|| {
            std::thread::available_parallelism()
                .map(|n| n.get())
                .unwrap_or(4)
        });

        #[cfg(not(php_zts))]
        {
            if requested > 1 {
                tracing::warn!(
                    requested = requested,
                    "PHP is NTS (non-thread-safe) — clamping to 1 worker. \
                     Rebuild PHP with --enable-zts for multi-threaded mode."
                );
            }
            #[allow(clippy::needless_return)]
            return 1;
        }

        #[cfg(php_zts)]
        requested
    }

    /// Build the INI entries string for `bext_php_module_init`.
    /// Applies sensible production defaults for OPcache/JIT when not
    /// explicitly overridden by the user.
    pub fn ini_entries_string(&self) -> String {
        let mut entries = String::new();

        // Production defaults — overridden by explicit [php.ini] entries
        // Note: JIT is intentionally NOT enabled by default — PHP 8.4's JIT
        // has stack size issues on some workloads.  Users can opt-in via:
        //   [php.ini]
        //   "opcache.jit" = "1255"
        //   "opcache.jit_buffer_size" = "64M"
        let defaults = [
            ("max_execution_time", self.max_execution_time.to_string()),
            // Disable stack size check — PHP 8.4's default limit (8MB) is too
            // small for the embedded SAPI's worker threads.  -1 = unlimited.
            ("zend.max_allowed_stack_size", "-1".into()),
            ("opcache.enable", "1".into()),
            ("opcache.enable_cli", "1".into()),
            ("opcache.validate_timestamps", "0".into()),
            ("opcache.memory_consumption", "128".into()),
            ("opcache.max_accelerated_files", "10000".into()),
            ("opcache.interned_strings_buffer", "16".into()),
            ("realpath_cache_size", "4096K".into()),
            ("realpath_cache_ttl", "600".into()),
            // ── Security hardening ──
            // Restrict filesystem access to the document root + /tmp.
            // Users can widen this via [php.ini] if needed.
            ("open_basedir", format!("{}:/tmp", self.document_root)),
            // Disable dynamic extension loading — prevents dl('malicious.so').
            ("enable_dl", "0".into()),
            // Disable dangerous functions that allow command execution or
            // process control. Users can override via [php.ini] if they
            // explicitly need these (e.g., for CLI tooling).
            ("disable_functions", [
                "exec", "system", "passthru", "shell_exec",
                "proc_open", "popen", "proc_close", "proc_terminate",
                "proc_get_status", "proc_nice",
                "pcntl_exec", "pcntl_fork", "pcntl_signal", "pcntl_waitpid",
                "pcntl_wexitstatus", "pcntl_alarm",
                "dl",
                "putenv",       // can manipulate LD_PRELOAD → RCE
                "apache_setenv",
                "show_source", "phpinfo",
            ].join(",").into()),
            // Prevent information disclosure.
            ("expose_php", "Off".into()),
            ("display_errors", "Off".into()),
            ("log_errors", "On".into()),
        ];

        for (key, value) in &defaults {
            if !self.ini.contains_key(*key) {
                if key.contains('\n')
                    || key.contains('\r')
                    || key.contains('\0')
                    || value.contains('\n')
                    || value.contains('\r')
                    || value.contains('\0')
                {
                    eprintln!(
                        "[SECURITY] Skipping INI entry with unsafe characters: {}",
                        key
                    );
                    continue;
                }
                entries.push_str(&format!("{}={}\n", key, value));
            }
        }

        // Security-critical INI keys that weaken the sandbox when overridden.
        // Warn loudly so operators notice if their config removes protections.
        const SECURITY_CRITICAL_KEYS: &[&str] = &[
            "disable_functions",
            "open_basedir",
            "enable_dl",
            "allow_url_include",
            "allow_url_fopen",
        ];

        // Apply user overrides (these take precedence)
        for (key, value) in &self.ini {
            if key.contains('\n')
                || key.contains('\r')
                || key.contains('\0')
                || value.contains('\n')
                || value.contains('\r')
                || value.contains('\0')
            {
                eprintln!(
                    "[SECURITY] Skipping INI entry with unsafe characters: {}",
                    key
                );
                continue;
            }
            if SECURITY_CRITICAL_KEYS.iter().any(|&k| k == key.as_str()) {
                eprintln!(
                    "[SECURITY WARNING] PHP INI override for '{}' — this weakens the \
                     default sandbox. Ensure this is intentional. Value: '{}'",
                    key, value
                );
                tracing::warn!(
                    key = key.as_str(),
                    value = value.as_str(),
                    "PHP security-critical INI override — default sandbox weakened"
                );
            }
            entries.push_str(&format!("{}={}\n", key, value));
        }

        entries
    }

    /// Whether worker mode is configured and available.
    /// Worker mode requires ZTS PHP — NTS PHP can only run classic mode
    /// because the PHP interpreter uses process-global state that isn't
    /// safe to access from spawned threads in worker mode.
    pub fn is_worker_mode(&self) -> bool {
        if self.worker_script.is_none() {
            return false;
        }

        #[cfg(php_zts)]
        {
            true
        }

        #[cfg(not(php_zts))]
        {
            tracing::warn!(
                "Worker mode requires ZTS PHP (--enable-zts). \
                 Falling back to classic mode."
            );
            false
        }
    }

    /// Check whether a request path should be handled by PHP.
    pub fn is_php_request(&self, path: &str) -> bool {
        // Direct match on extension
        for ext in &self.extensions {
            if path.ends_with(ext.as_str()) {
                return true;
            }
        }
        // Directory request → try index file
        if path.ends_with('/') || !path.contains('.') {
            return true; // Will resolve to index.php
        }
        false
    }

    /// Resolve a request path to a filesystem path.
    ///
    /// Returns the absolute script path if the file exists, or None.
    pub fn resolve_script(&self, request_path: &str) -> Option<String> {
        let doc_root = std::path::Path::new(&self.document_root);

        // Strip leading slash and reject path traversal patterns
        let relative = request_path.trim_start_matches('/');
        if relative.contains("..") || relative.contains('\0') {
            return None;
        }

        // Direct file match — then verify it's inside document_root via canonicalize
        // to prevent symlink-based traversal attacks.
        let candidate = doc_root.join(relative);
        if candidate.is_file() {
            // Canonicalize both paths to resolve symlinks
            let canon_root = std::fs::canonicalize(doc_root).ok()?;
            let canon_file = std::fs::canonicalize(&candidate).ok()?;
            if !canon_file.starts_with(&canon_root) {
                tracing::warn!(
                    path = %request_path,
                    resolved = %canon_file.display(),
                    root = %canon_root.display(),
                    "Path traversal blocked (symlink escape)"
                );
                return None;
            }
            return canon_file.to_str().map(|s| s.to_string());
        }

        // Try appending index file for directory-like paths
        let index_candidate = doc_root.join(relative).join(&self.index);

        if index_candidate.is_file() {
            return index_candidate.to_str().map(|s| s.to_string());
        }

        // Try router script (front controller pattern: all requests → index.php)
        let router = doc_root.join(&self.index);
        if router.is_file() {
            return router.to_str().map(|s| s.to_string());
        }

        None
    }
}

fn default_document_root() -> String {
    "./public".into()
}

fn default_extensions() -> Vec<String> {
    vec![".php".into()]
}

fn default_index() -> String {
    "index.php".into()
}

fn default_max_body() -> usize {
    8 * 1024 * 1024
}

fn default_max_execution_time() -> u32 {
    30
}

fn default_max_requests() -> u64 {
    10_000
}

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

    // ─── Default values ──────────────────────────────────────────────────

    #[test]
    fn default_config() {
        let config = PhpConfig::default();
        assert!(!config.enabled);
        assert_eq!(config.document_root, "./public");
        assert_eq!(config.extensions, vec![".php"]);
        assert_eq!(config.index, "index.php");
        assert_eq!(config.max_body_bytes, 8 * 1024 * 1024);
        assert_eq!(config.max_execution_time, 30);
        assert_eq!(config.max_requests, 10_000);
        assert!(config.workers.is_none());
        assert!(config.ini.is_empty());
    }

    // ─── INI generation ──────────────────────────────────────────────────

    #[test]
    fn ini_entries_string() {
        let mut config = PhpConfig::default();
        config.ini.insert("memory_limit".into(), "256M".into());
        config.ini.insert("display_errors".into(), "Off".into());
        let ini = config.ini_entries_string();
        assert!(ini.contains("max_execution_time=30"));
        assert!(ini.contains("memory_limit=256M"));
        assert!(ini.contains("display_errors=Off"));
    }

    #[test]
    fn ini_entries_includes_defaults_when_no_overrides() {
        let config = PhpConfig::default();
        let ini = config.ini_entries_string();
        assert!(ini.contains("max_execution_time=30"));
        assert!(ini.contains("opcache.enable=1"));
        assert!(ini.contains("opcache.validate_timestamps=0"));
        assert!(ini.contains("realpath_cache_size=4096K"));
        // JIT is NOT enabled by default (stack size issues in PHP 8.4)
        assert!(!ini.contains("opcache.jit="));
    }

    #[test]
    fn ini_entries_custom_execution_time() {
        let mut config = PhpConfig::default();
        config.max_execution_time = 120;
        let ini = config.ini_entries_string();
        assert!(ini.starts_with("max_execution_time=120\n"));
    }

    // ─── Request detection ───────────────────────────────────────────────

    #[test]
    fn is_php_request_extensions() {
        let config = PhpConfig::default();
        assert!(config.is_php_request("/index.php"));
        assert!(config.is_php_request("/api/users.php"));
        assert!(config.is_php_request("/")); // directory → index.php
        assert!(config.is_php_request("/api/users")); // no extension → try PHP
        assert!(!config.is_php_request("/style.css"));
        assert!(!config.is_php_request("/script.js"));
        assert!(!config.is_php_request("/image.png"));
    }

    #[test]
    fn is_php_request_custom_extensions() {
        let mut config = PhpConfig::default();
        config.extensions = vec![".php".into(), ".phtml".into(), ".php7".into()];
        assert!(config.is_php_request("/template.phtml"));
        assert!(config.is_php_request("/legacy.php7"));
        assert!(config.is_php_request("/index.php"));
        assert!(!config.is_php_request("/style.css"));
    }

    #[test]
    fn is_php_request_trailing_slash() {
        let config = PhpConfig::default();
        assert!(config.is_php_request("/admin/"));
        assert!(config.is_php_request("/"));
        assert!(config.is_php_request("/api/v2/"));
    }

    #[test]
    fn is_php_request_no_extension_paths() {
        let config = PhpConfig::default();
        // Paths without extensions are treated as PHP (front controller)
        assert!(config.is_php_request("/users"));
        assert!(config.is_php_request("/api/v2/products"));
        assert!(config.is_php_request("/dashboard"));
    }

    #[test]
    fn is_php_request_static_files_rejected() {
        let config = PhpConfig::default();
        assert!(!config.is_php_request("/favicon.ico"));
        assert!(!config.is_php_request("/robots.txt"));
        assert!(!config.is_php_request("/sitemap.xml"));
        assert!(!config.is_php_request("/assets/app.js"));
        assert!(!config.is_php_request("/css/main.css"));
        assert!(!config.is_php_request("/images/logo.png"));
        assert!(!config.is_php_request("/fonts/inter.woff2"));
    }

    // ─── Script resolution ───────────────────────────────────────────────

    #[test]
    fn resolve_script_direct_file() {
        let tmp = std::env::temp_dir().join("bext-php-test-resolve");
        let _ = std::fs::remove_dir_all(&tmp);
        std::fs::create_dir_all(&tmp).unwrap();
        std::fs::write(tmp.join("info.php"), "<?php phpinfo();").unwrap();

        let mut config = PhpConfig::default();
        config.document_root = tmp.to_str().unwrap().to_string();

        let resolved = config.resolve_script("/info.php");
        assert!(resolved.is_some());
        assert!(resolved.unwrap().ends_with("info.php"));

        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn resolve_script_index_file() {
        let tmp = std::env::temp_dir().join("bext-php-test-index");
        let _ = std::fs::remove_dir_all(&tmp);
        std::fs::create_dir_all(&tmp).unwrap();
        std::fs::write(tmp.join("index.php"), "<?php echo 'home';").unwrap();

        let mut config = PhpConfig::default();
        config.document_root = tmp.to_str().unwrap().to_string();

        // Root path should resolve to index.php
        let resolved = config.resolve_script("/");
        assert!(resolved.is_some());
        assert!(resolved.unwrap().ends_with("index.php"));

        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn resolve_script_front_controller() {
        let tmp = std::env::temp_dir().join("bext-php-test-router");
        let _ = std::fs::remove_dir_all(&tmp);
        std::fs::create_dir_all(&tmp).unwrap();
        std::fs::write(tmp.join("index.php"), "<?php /* router */").unwrap();

        let mut config = PhpConfig::default();
        config.document_root = tmp.to_str().unwrap().to_string();

        // Non-existent path should fall back to index.php (front controller)
        let resolved = config.resolve_script("/api/users/42");
        assert!(resolved.is_some());
        assert!(resolved.unwrap().ends_with("index.php"));

        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn resolve_script_subdirectory() {
        let tmp = std::env::temp_dir().join("bext-php-test-subdir");
        let _ = std::fs::remove_dir_all(&tmp);
        std::fs::create_dir_all(tmp.join("admin")).unwrap();
        std::fs::write(tmp.join("admin/dashboard.php"), "<?php").unwrap();

        let mut config = PhpConfig::default();
        config.document_root = tmp.to_str().unwrap().to_string();

        let resolved = config.resolve_script("/admin/dashboard.php");
        assert!(resolved.is_some());
        assert!(resolved.unwrap().contains("admin/dashboard.php"));

        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn resolve_script_missing_doc_root() {
        let config = PhpConfig {
            document_root: "/nonexistent/path/xyz".into(),
            ..PhpConfig::default()
        };
        assert!(config.resolve_script("/index.php").is_none());
    }

    #[test]
    fn resolve_script_path_traversal_blocked() {
        let config = PhpConfig::default();
        assert!(config.resolve_script("/../../../etc/passwd").is_none());
        assert!(config
            .resolve_script("/admin/../../../etc/shadow")
            .is_none());
        assert!(config.resolve_script("/..").is_none());
    }

    #[test]
    fn resolve_script_custom_index() {
        let tmp = std::env::temp_dir().join("bext-php-test-custom-idx");
        let _ = std::fs::remove_dir_all(&tmp);
        std::fs::create_dir_all(&tmp).unwrap();
        std::fs::write(tmp.join("app.php"), "<?php").unwrap();

        let config = PhpConfig {
            document_root: tmp.to_str().unwrap().to_string(),
            index: "app.php".into(),
            ..PhpConfig::default()
        };

        let resolved = config.resolve_script("/");
        assert!(resolved.is_some());
        assert!(resolved.unwrap().ends_with("app.php"));

        let _ = std::fs::remove_dir_all(&tmp);
    }

    // ─── Workers ─────────────────────────────────────────────────────────

    #[test]
    fn effective_workers_default() {
        let config = PhpConfig::default();
        assert!(config.effective_workers() > 0);
    }

    #[test]
    fn effective_workers_override() {
        let mut config = PhpConfig::default();
        config.workers = Some(8);
        #[cfg(php_zts)]
        assert_eq!(config.effective_workers(), 8);
        #[cfg(not(php_zts))]
        assert_eq!(config.effective_workers(), 1);
    }

    // ─── TOML deserialization ────────────────────────────────────────────

    #[test]
    fn toml_round_trip() {
        let toml_str = r#"
            enabled = true
            document_root = "/var/www/html"
            workers = 4
            index = "app.php"
            max_execution_time = 60
            max_requests = 5000
            extensions = [".php", ".phtml"]

            [ini]
            memory_limit = "512M"
            "opcache.enable" = "1"
            "opcache.jit" = "1255"
        "#;
        let config: PhpConfig = toml::from_str(toml_str).unwrap();
        assert!(config.enabled);
        assert_eq!(config.document_root, "/var/www/html");
        assert_eq!(config.workers, Some(4));
        assert_eq!(config.index, "app.php");
        assert_eq!(config.max_execution_time, 60);
        assert_eq!(config.max_requests, 5000);
        assert_eq!(config.ini.get("memory_limit").unwrap(), "512M");
        assert_eq!(config.ini.get("opcache.enable").unwrap(), "1");
        assert_eq!(config.extensions, vec![".php", ".phtml"]);
    }

    #[test]
    fn toml_minimal() {
        let toml_str = r#"enabled = true"#;
        let config: PhpConfig = toml::from_str(toml_str).unwrap();
        assert!(config.enabled);
        assert_eq!(config.document_root, "./public");
        assert_eq!(config.extensions, vec![".php"]);
    }

    #[test]
    fn toml_empty() {
        let config: PhpConfig = toml::from_str("").unwrap();
        assert!(!config.enabled);
    }

    #[test]
    fn toml_max_body_override() {
        let toml_str = r#"max_body_bytes = 1048576"#;
        let config: PhpConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(config.max_body_bytes, 1_048_576); // 1MB
    }

    #[test]
    fn toml_nested_in_server_config() {
        let toml_str = r#"
            [php]
            enabled = true
            document_root = "/srv/app/public"
            workers = 2

            [php.ini]
            "session.save_handler" = "files"
        "#;

        #[derive(serde::Deserialize)]
        struct Wrapper {
            php: PhpConfig,
        }

        let wrapper: Wrapper = toml::from_str(toml_str).unwrap();
        assert!(wrapper.php.enabled);
        assert_eq!(wrapper.php.document_root, "/srv/app/public");
        assert_eq!(wrapper.php.workers, Some(2));
        assert_eq!(
            wrapper.php.ini.get("session.save_handler").unwrap(),
            "files"
        );
    }

    // ─── Worker mode detection ───────────────────────────────────────────

    #[test]
    fn is_worker_mode_without_script() {
        let config = PhpConfig::default();
        assert!(!config.is_worker_mode());
    }

    #[test]
    fn is_worker_mode_with_script() {
        let config = PhpConfig {
            worker_script: Some("./worker.php".into()),
            ..PhpConfig::default()
        };
        // ZTS: worker mode enabled. NTS: falls back to classic.
        #[cfg(php_zts)]
        assert!(config.is_worker_mode());
        #[cfg(not(php_zts))]
        assert!(!config.is_worker_mode());
    }

    // ─── cache_responses field ───────────────────────────────────────────

    #[test]
    fn cache_responses_default_true() {
        let config = PhpConfig::default();
        assert!(config.cache_responses);
    }

    #[test]
    fn cache_responses_disable() {
        let toml_str = r#"cache_responses = false"#;
        let config: PhpConfig = toml::from_str(toml_str).unwrap();
        assert!(!config.cache_responses);
    }

    // ─── TOML with worker_script ─────────────────────────────────────────

    #[test]
    fn toml_worker_script() {
        let toml_str = r#"
            enabled = true
            worker_script = "./bootstrap/worker.php"
            workers = 4
        "#;
        let config: PhpConfig = toml::from_str(toml_str).unwrap();
        assert_eq!(
            config.worker_script.as_deref(),
            Some("./bootstrap/worker.php")
        );
        assert_eq!(config.workers, Some(4));
    }

    #[test]
    fn toml_full_with_all_fields() {
        let toml_str = r#"
            enabled = true
            document_root = "/var/www"
            workers = 8
            max_execution_time = 120
            max_requests = 50000
            max_body_bytes = 16777216
            cache_responses = false
            worker_script = "/opt/app/worker.php"
            extensions = [".php", ".phtml"]
            index = "app.php"

            [ini]
            memory_limit = "1G"
        "#;
        let config: PhpConfig = toml::from_str(toml_str).unwrap();
        assert!(config.enabled);
        assert_eq!(config.document_root, "/var/www");
        assert_eq!(config.workers, Some(8));
        assert_eq!(config.max_execution_time, 120);
        assert_eq!(config.max_requests, 50000);
        assert_eq!(config.max_body_bytes, 16_777_216);
        assert!(!config.cache_responses);
        assert_eq!(config.worker_script.as_deref(), Some("/opt/app/worker.php"));
        assert_eq!(config.extensions, vec![".php", ".phtml"]);
        assert_eq!(config.index, "app.php");
        assert_eq!(config.ini.get("memory_limit").unwrap(), "1G");
    }

    // ─── INI edge cases ──────────────────────────────────────────────────

    #[test]
    fn ini_user_overrides_default() {
        let mut config = PhpConfig::default();
        // User sets opcache.enable=0 which should override the default of 1
        config.ini.insert("opcache.enable".into(), "0".into());
        let ini = config.ini_entries_string();
        // The user's value should appear (defaults don't re-add already-set keys)
        assert!(ini.contains("opcache.enable=0"));
        // Should NOT have opcache.enable=1 from defaults
        let count = ini.matches("opcache.enable=").count();
        assert_eq!(count, 1);
    }

    // ─── is_php_request edge cases ───────────────────────────────────────

    #[test]
    fn is_php_request_empty_path() {
        let config = PhpConfig::default();
        // Empty string has no extension and no slash → treated as PHP (front controller)
        assert!(config.is_php_request(""));
    }

    #[test]
    fn is_php_request_double_extension() {
        let config = PhpConfig::default();
        assert!(config.is_php_request("/file.backup.php"));
        assert!(!config.is_php_request("/file.php.bak"));
    }

    #[test]
    fn is_php_request_with_query_component() {
        let config = PhpConfig::default();
        // In practice, the handler passes only the path (no query string).
        // But if a query is included, .php extension should still match.
        assert!(config.is_php_request("/index.php"));
        // Path with query: the "?" introduces a "." which causes the
        // no-extension check to fail — callers should strip query first.
        // This documents the current behavior:
        assert!(!config.is_php_request("/index.php?foo=bar"));
    }

    // ─── resolve_script edge cases ───────────────────────────────────────

    #[test]
    fn resolve_script_empty_path() {
        let tmp = std::env::temp_dir().join("bext-php-test-empty");
        let _ = std::fs::remove_dir_all(&tmp);
        std::fs::create_dir_all(&tmp).unwrap();
        std::fs::write(tmp.join("index.php"), "<?php").unwrap();

        let config = PhpConfig {
            document_root: tmp.to_str().unwrap().to_string(),
            ..PhpConfig::default()
        };

        // Empty path should resolve to index.php
        let resolved = config.resolve_script("");
        assert!(resolved.is_some());
        assert!(resolved.unwrap().ends_with("index.php"));

        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn resolve_script_dot_dot_in_component() {
        let config = PhpConfig::default();
        assert!(config.resolve_script("/foo/../bar.php").is_none());
        assert!(config.resolve_script("/../index.php").is_none());
        assert!(config.resolve_script("/a/b/../../c").is_none());
    }

    // ─── Security tests ──────────────────────────────────────────────────

    #[test]
    fn resolve_script_null_byte_blocked() {
        let config = PhpConfig::default();
        assert!(config.resolve_script("/index.php\0.jpg").is_none());
        assert!(config.resolve_script("/\0/etc/passwd").is_none());
    }

    #[test]
    fn resolve_script_symlink_escape_blocked() {
        let tmp = std::env::temp_dir().join("bext-php-test-symlink");
        let _ = std::fs::remove_dir_all(&tmp);
        std::fs::create_dir_all(&tmp).unwrap();
        std::fs::write(tmp.join("legit.php"), "<?php").unwrap();

        // Create a symlink pointing outside the document root
        #[cfg(unix)]
        {
            let _ = std::os::unix::fs::symlink("/etc/hostname", tmp.join("escape.php"));

            let config = PhpConfig {
                document_root: tmp.to_str().unwrap().to_string(),
                ..PhpConfig::default()
            };

            // Legit file should resolve
            assert!(config.resolve_script("/legit.php").is_some());

            // Symlink escaping document root should be blocked
            assert!(config.resolve_script("/escape.php").is_none());
        }

        let _ = std::fs::remove_dir_all(&tmp);
    }

    #[test]
    fn resolve_script_encoded_traversal_blocked() {
        let config = PhpConfig::default();
        // URL-encoded path traversal should also be blocked if decoded
        assert!(config.resolve_script("/..%2f..%2fetc/passwd").is_none());
        // Double dots in any form
        assert!(config.resolve_script("/....//....//etc/passwd").is_none());
    }

    #[test]
    fn is_php_request_bext_internal_skipped() {
        // /__bext/* paths should NOT be treated as PHP requests
        // (the handler checks this, not is_php_request, but document the expectation)
        let config = PhpConfig::default();
        // These would match the "no extension" rule, but the handler skips them
        assert!(config.is_php_request("/__bext/jsc-render"));
        assert!(config.is_php_request("/__bext/php-call"));
        // The handler adds: && !path.starts_with("/__bext/")
    }

    #[test]
    fn ini_no_injection() {
        let mut config = PhpConfig::default();
        // INI values with newlines could inject settings
        config.ini.insert("safe_key".into(), "safe_value".into());
        config
            .ini
            .insert("inject\nmalicious".into(), "value".into());
        let ini = config.ini_entries_string();
        // The injected key appears as-is (PHP will reject it)
        // This documents the current behavior — future: validate keys
        assert!(ini.contains("safe_key=safe_value"));
    }
}