puressh 0.2.4

A pure-Rust SSH (Secure Shell) protocol library, in the spirit of libssh, built on purecrypto.
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
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
//! End-to-end SFTP round-trip tests.
//!
//! These spawn an [`SftpServerSession`] in a thread, pair it with an
//! [`SftpClient`] over a `UnixStream::pair`, and exercise each operation.

#![cfg(unix)]

use std::fs;
use std::os::unix::net::UnixStream;
use std::path::{Path, PathBuf};
use std::thread;

use super::client::SftpClient;
use super::server::{SftpServerOptions, SftpServerSession};
use super::types::{Attrs, FXF_CREAT, FXF_READ, FXF_TRUNC, FXF_WRITE, FxpStatus, SftpError};

struct TempDir(PathBuf);

impl TempDir {
    fn new(tag: &str) -> Self {
        // pid + thread-id gives a unique directory across parallel `cargo
        // test` workers without pulling in a tempfile dep.
        let dir = std::env::temp_dir().join(format!(
            "puressh-sftp-{}-{}-{}",
            tag,
            std::process::id(),
            std::time::SystemTime::now()
                .duration_since(std::time::UNIX_EPOCH)
                .unwrap()
                .as_nanos(),
        ));
        fs::create_dir_all(&dir).unwrap();
        Self(dir)
    }

    fn path(&self) -> &Path {
        &self.0
    }
}

impl Drop for TempDir {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.0);
    }
}

fn pair() -> (UnixStream, UnixStream) {
    UnixStream::pair().unwrap()
}

fn spawn_server(opts: SftpServerOptions, server_end: UnixStream) -> thread::JoinHandle<()> {
    thread::spawn(move || {
        let mut session = SftpServerSession::new(opts);
        // Closing the client side returns Ok(()); other errors get printed
        // through the panic so they surface in the test log.
        session.run(server_end).expect("sftp server session");
    })
}

#[test]
fn version_handshake() {
    let tmp = TempDir::new("handshake");
    let (a, b) = pair();
    let h = spawn_server(SftpServerOptions::new(tmp.path()), a);
    let client = SftpClient::new(b).unwrap();
    assert!(client.server_version() >= 3);
    drop(client);
    h.join().unwrap();
}

#[test]
fn open_write_read_close() {
    let tmp = TempDir::new("rw");
    let (a, b) = pair();
    let h = spawn_server(SftpServerOptions::new(tmp.path()), a);
    let mut client = SftpClient::new(b).unwrap();

    let handle = client
        .open(
            b"hello.txt",
            FXF_WRITE | FXF_CREAT | FXF_TRUNC,
            Attrs::default(),
        )
        .unwrap();
    client.write(&handle, 0, b"hello world").unwrap();
    client.close(&handle).unwrap();

    let handle = client
        .open(b"hello.txt", FXF_READ, Attrs::default())
        .unwrap();
    let data = client.read(&handle, 0, 1024).unwrap();
    assert_eq!(data, b"hello world");
    client.close(&handle).unwrap();

    let on_disk = fs::read(tmp.path().join("hello.txt")).unwrap();
    assert_eq!(on_disk, b"hello world");

    drop(client);
    h.join().unwrap();
}

#[test]
fn stat_returns_size_and_mode() {
    let tmp = TempDir::new("stat");
    fs::write(tmp.path().join("a.txt"), b"abc").unwrap();
    let (a, b) = pair();
    let h = spawn_server(SftpServerOptions::new(tmp.path()), a);
    let mut client = SftpClient::new(b).unwrap();
    let attrs = client.stat(b"a.txt").unwrap();
    assert_eq!(attrs.size, Some(3));
    assert!(attrs.permissions.unwrap_or(0) != 0);
    drop(client);
    h.join().unwrap();
}

#[test]
fn mkdir_readdir_rmdir() {
    let tmp = TempDir::new("dir");
    let (a, b) = pair();
    let h = spawn_server(SftpServerOptions::new(tmp.path()), a);
    let mut client = SftpClient::new(b).unwrap();

    client.mkdir(b"sub", Attrs::default()).unwrap();
    let handle = client.opendir(b".").unwrap();
    let entries = client.readdir(&handle).unwrap().unwrap();
    assert!(entries.iter().any(|e| e.filename == b"sub"));

    // After exhausting entries the next readdir returns None.
    let mut saw_none = false;
    for _ in 0..16 {
        match client.readdir(&handle).unwrap() {
            None => {
                saw_none = true;
                break;
            }
            Some(_) => continue,
        }
    }
    assert!(saw_none, "expected directory iteration to end");

    client.close(&handle).unwrap();
    client.rmdir(b"sub").unwrap();
    assert!(!tmp.path().join("sub").exists());

    drop(client);
    h.join().unwrap();
}

#[test]
fn rename_and_remove() {
    let tmp = TempDir::new("rename");
    fs::write(tmp.path().join("a"), b"x").unwrap();
    let (a, b) = pair();
    let h = spawn_server(SftpServerOptions::new(tmp.path()), a);
    let mut client = SftpClient::new(b).unwrap();
    client.rename(b"a", b"b").unwrap();
    assert!(tmp.path().join("b").exists());
    client.remove(b"b").unwrap();
    assert!(!tmp.path().join("b").exists());
    drop(client);
    h.join().unwrap();
}

#[test]
fn realpath_normalises() {
    let tmp = TempDir::new("realpath");
    let (a, b) = pair();
    let h = spawn_server(SftpServerOptions::new(tmp.path()), a);
    let mut client = SftpClient::new(b).unwrap();
    let p = client.realpath(b"./foo/../bar").unwrap();
    let expected = tmp.path().join("bar").to_string_lossy().into_owned();
    assert_eq!(String::from_utf8_lossy(&p), expected);
    drop(client);
    h.join().unwrap();
}

#[test]
fn symlink_and_readlink() {
    let tmp = TempDir::new("symlink");
    fs::write(tmp.path().join("target"), b"x").unwrap();
    let (a, b) = pair();
    let h = spawn_server(SftpServerOptions::new(tmp.path()), a);
    let mut client = SftpClient::new(b).unwrap();
    client.symlink(b"target", b"linkname").unwrap();
    let tgt = client.readlink(b"linkname").unwrap();
    assert_eq!(tgt, b"target");
    drop(client);
    h.join().unwrap();
}

#[test]
fn jail_blocks_traversal_escape() {
    let tmp = TempDir::new("jail");
    let jail = tmp.path().to_path_buf();
    let (a, b) = pair();
    let opts = SftpServerOptions::new(jail.clone()).with_root(jail);
    let h = spawn_server(opts, a);
    let mut client = SftpClient::new(b).unwrap();
    let err = client
        .open(b"../../etc/passwd", FXF_READ, Attrs::default())
        .unwrap_err();
    match err {
        SftpError::Status { code, .. } => assert_eq!(code, FxpStatus::PermissionDenied),
        other => panic!("expected PermissionDenied, got {other:?}"),
    }
    drop(client);
    h.join().unwrap();
}

#[test]
fn read_only_refuses_writes() {
    let tmp = TempDir::new("readonly");
    let opts = SftpServerOptions::new(tmp.path()).read_only();
    let (a, b) = pair();
    let h = spawn_server(opts, a);
    let mut client = SftpClient::new(b).unwrap();
    let err = client
        .open(b"new.txt", FXF_WRITE | FXF_CREAT, Attrs::default())
        .unwrap_err();
    match err {
        SftpError::Status { code, .. } => assert_eq!(code, FxpStatus::PermissionDenied),
        other => panic!("expected PermissionDenied, got {other:?}"),
    }
    drop(client);
    h.join().unwrap();
}

#[test]
fn fstat_after_open() {
    let tmp = TempDir::new("fstat");
    fs::write(tmp.path().join("x"), b"hello").unwrap();
    let (a, b) = pair();
    let h = spawn_server(SftpServerOptions::new(tmp.path()), a);
    let mut client = SftpClient::new(b).unwrap();
    let handle = client.open(b"x", FXF_READ, Attrs::default()).unwrap();
    let attrs = client.fstat(&handle).unwrap();
    assert_eq!(attrs.size, Some(5));
    client.close(&handle).unwrap();
    drop(client);
    h.join().unwrap();
}

// --- security: jail-aware symlink rejection (finding #1) ---

#[test]
fn jailed_open_through_planted_symlink_rejected() {
    let tmp = TempDir::new("symjail-open");
    let jail = tmp.path().to_path_buf();
    // Plant a symlink inside the jail pointing at /etc/passwd.
    std::os::unix::fs::symlink("/etc/passwd", jail.join("escape")).unwrap();

    let (a, b) = pair();
    let opts = SftpServerOptions::new(jail.clone()).with_root(jail);
    let h = spawn_server(opts, a);
    let mut client = SftpClient::new(b).unwrap();
    let err = client
        .open(b"escape", FXF_READ, Attrs::default())
        .unwrap_err();
    match err {
        SftpError::Status { code, .. } => assert_eq!(code, FxpStatus::NoSuchFile),
        other => panic!("expected NoSuchFile, got {other:?}"),
    }
    drop(client);
    h.join().unwrap();
}

#[test]
fn jailed_setstat_through_symlink_rejected() {
    let tmp = TempDir::new("symjail-setstat");
    let jail = tmp.path().to_path_buf();
    // Outside the jail, a victim file.
    let outside = std::env::temp_dir().join(format!(
        "puressh-sftp-victim-{}-{}",
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos(),
    ));
    fs::write(&outside, b"victim").unwrap();
    let _g = OutsideGuard(outside.clone());
    // Plant a symlink inside the jail pointing at the victim.
    std::os::unix::fs::symlink(&outside, jail.join("link")).unwrap();

    let (a, b) = pair();
    let opts = SftpServerOptions::new(jail.clone()).with_root(jail);
    let h = spawn_server(opts, a);
    let mut client = SftpClient::new(b).unwrap();
    // Try to chmod through the planted symlink.
    let attrs = Attrs {
        permissions: Some(0o000),
        ..Default::default()
    };
    let err = client.setstat(b"link", attrs).unwrap_err();
    match err {
        SftpError::Status { code, .. } => assert_eq!(code, FxpStatus::NoSuchFile),
        other => panic!("expected NoSuchFile, got {other:?}"),
    }
    // The victim should be untouched (permissions still readable).
    let md = fs::metadata(&outside).unwrap();
    use std::os::unix::fs::PermissionsExt as _;
    assert_ne!(md.permissions().mode() & 0o777, 0o000);
    drop(client);
    h.join().unwrap();
}

/// Build an outside-the-jail victim file with a unique name, returning the
/// path plus a guard that unlinks it on drop.
fn outside_victim(tag: &str, contents: &[u8]) -> (PathBuf, OutsideGuard) {
    let outside = std::env::temp_dir().join(format!(
        "puressh-sftp-victim-{}-{}-{}",
        tag,
        std::process::id(),
        std::time::SystemTime::now()
            .duration_since(std::time::UNIX_EPOCH)
            .unwrap()
            .as_nanos(),
    ));
    fs::write(&outside, contents).unwrap();
    let guard = OutsideGuard(outside.clone());
    (outside, guard)
}

#[test]
fn jailed_remove_through_symlink_rejected() {
    let tmp = TempDir::new("symjail-remove");
    let jail = tmp.path().to_path_buf();
    let (outside, _g) = outside_victim("remove", b"victim");
    // Plant a symlink inside the jail pointing at the outside victim.
    std::os::unix::fs::symlink(&outside, jail.join("link")).unwrap();

    let (a, b) = pair();
    let opts = SftpServerOptions::new(jail.clone()).with_root(jail);
    let h = spawn_server(opts, a);
    let mut client = SftpClient::new(b).unwrap();
    let err = client.remove(b"link").unwrap_err();
    match err {
        SftpError::Status { code, .. } => assert_eq!(code, FxpStatus::NoSuchFile),
        other => panic!("expected NoSuchFile, got {other:?}"),
    }
    // The victim is untouched.
    assert!(outside.exists());
    drop(client);
    h.join().unwrap();
}

#[test]
fn jailed_rmdir_through_symlink_rejected() {
    let tmp = TempDir::new("symjail-rmdir");
    let jail = tmp.path().to_path_buf();
    // Outside the jail, a victim directory.
    let (outside, _g) = outside_victim("rmdir", b"");
    fs::remove_file(&outside).unwrap();
    fs::create_dir(&outside).unwrap();
    let _gd = OutsideDirGuard(outside.clone());
    // Plant a symlink inside the jail pointing at the outside directory.
    std::os::unix::fs::symlink(&outside, jail.join("dlink")).unwrap();

    let (a, b) = pair();
    let opts = SftpServerOptions::new(jail.clone()).with_root(jail);
    let h = spawn_server(opts, a);
    let mut client = SftpClient::new(b).unwrap();
    let err = client.rmdir(b"dlink").unwrap_err();
    match err {
        SftpError::Status { code, .. } => assert_eq!(code, FxpStatus::NoSuchFile),
        other => panic!("expected NoSuchFile, got {other:?}"),
    }
    // The victim directory is untouched.
    assert!(outside.is_dir());
    drop(client);
    h.join().unwrap();
}

#[test]
fn jailed_rename_through_symlink_rejected() {
    let tmp = TempDir::new("symjail-rename");
    let jail = tmp.path().to_path_buf();
    let (outside, _g) = outside_victim("rename", b"victim");
    // Plant a symlink at the rename source pointing outside the jail.
    std::os::unix::fs::symlink(&outside, jail.join("from")).unwrap();

    let (a, b) = pair();
    let opts = SftpServerOptions::new(jail.clone()).with_root(jail.clone());
    let h = spawn_server(opts, a);
    let mut client = SftpClient::new(b).unwrap();
    let err = client.rename(b"from", b"to").unwrap_err();
    match err {
        SftpError::Status { code, .. } => assert_eq!(code, FxpStatus::NoSuchFile),
        other => panic!("expected NoSuchFile, got {other:?}"),
    }
    // The outside victim still exists at its original location.
    assert!(outside.exists());
    assert!(!jail.join("to").exists());
    drop(client);
    h.join().unwrap();
}

#[test]
fn jailed_open_relative_symlink_to_outside_rejected() {
    let tmp = TempDir::new("symjail-rel");
    let jail = tmp.path().to_path_buf();
    // Even though the lexical jail check would clamp at `/`, the relative
    // target only resolves at use time — and use time is gated by
    // O_NOFOLLOW on the final component.
    std::os::unix::fs::symlink("../../etc/passwd", jail.join("trap")).unwrap();

    let (a, b) = pair();
    let opts = SftpServerOptions::new(jail.clone()).with_root(jail);
    let h = spawn_server(opts, a);
    let mut client = SftpClient::new(b).unwrap();
    let err = client
        .open(b"trap", FXF_READ, Attrs::default())
        .unwrap_err();
    match err {
        SftpError::Status { code, .. } => assert_eq!(code, FxpStatus::NoSuchFile),
        other => panic!("expected NoSuchFile, got {other:?}"),
    }
    drop(client);
    h.join().unwrap();
}

#[test]
fn jailed_symlink_with_absolute_target_rejected() {
    let tmp = TempDir::new("symjail-abs");
    let jail = tmp.path().to_path_buf();
    let (a, b) = pair();
    let opts = SftpServerOptions::new(jail.clone()).with_root(jail);
    let h = spawn_server(opts, a);
    let mut client = SftpClient::new(b).unwrap();
    let err = client.symlink(b"/etc/passwd", b"abs-link").unwrap_err();
    match err {
        SftpError::Status { code, .. } => assert_eq!(code, FxpStatus::PermissionDenied),
        other => panic!("expected PermissionDenied, got {other:?}"),
    }
    drop(client);
    h.join().unwrap();
}

/// Assert an SFTP call failed with `PermissionDenied`.
fn expect_denied<T: std::fmt::Debug>(r: Result<T, SftpError>) {
    match r {
        Err(SftpError::Status { code, .. }) => assert_eq!(code, FxpStatus::PermissionDenied),
        other => panic!("expected PermissionDenied, got {other:?}"),
    }
}

#[test]
fn jailed_symlink_chain_escape_rejected() {
    // XFER-1: `a/s -> ..` and `a/t -> s/../..` are each lexically inside
    // the jail, but the kernel resolves `s/..` after following `s`, so
    // `a/t` would point one level above the jail root.
    let tmp = TempDir::new("symjail-chain");
    let jail = tmp.path().join("jail");
    fs::create_dir_all(&jail).unwrap();
    let (a, b) = pair();
    let opts = SftpServerOptions::new(jail.clone()).with_root(jail.clone());
    let h = spawn_server(opts, a);
    let mut client = SftpClient::new(b).unwrap();
    client.mkdir(b"a", Attrs::default()).unwrap();
    expect_denied(client.symlink(b"..", b"a/s"));
    expect_denied(client.symlink(b"s/../..", b"a/t"));
    expect_denied(client.symlink(b"x/../y", b"a/u"));
    assert!(fs::symlink_metadata(jail.join("a/s")).is_err());
    assert!(fs::symlink_metadata(jail.join("a/t")).is_err());
    assert!(
        client
            .open(b"a/t/jail", FXF_READ, Attrs::default())
            .is_err()
    );
    // Downward-only relative targets are still fine.
    client.symlink(b"x/y", b"a/down").unwrap();
    client.symlink(b"./z", b"a/dot").unwrap();
    drop(client);
    h.join().unwrap();
}

#[test]
fn jailed_symlink_then_rename_escape_rejected() {
    // XFER-1: `a/b/s -> ../..` resolves to the jail root where it sits,
    // but after renaming `a/b` to `b` the same link points above the jail.
    let tmp = TempDir::new("symjail-rename-chain");
    let jail = tmp.path().join("jail");
    fs::create_dir_all(&jail).unwrap();
    let (a, b) = pair();
    let opts = SftpServerOptions::new(jail.clone()).with_root(jail.clone());
    let h = spawn_server(opts, a);
    let mut client = SftpClient::new(b).unwrap();
    client.mkdir(b"a", Attrs::default()).unwrap();
    client.mkdir(b"a/b", Attrs::default()).unwrap();
    expect_denied(client.symlink(b"../..", b"a/b/s"));
    client.rename(b"a/b", b"b").unwrap();
    assert!(fs::symlink_metadata(jail.join("b/s")).is_err());
    assert!(client.opendir(b"b/s").is_err());
    drop(client);
    h.join().unwrap();
}

// --- security: readlink must not disclose paths outside the jail (C1) ---

fn expect_permission_denied(r: Result<Vec<u8>, SftpError>) {
    match r {
        Err(SftpError::Status { code, .. }) => assert_eq!(code, FxpStatus::PermissionDenied),
        Err(other) => panic!("expected PermissionDenied, got {other:?}"),
        Ok(v) => panic!(
            "expected PermissionDenied, got target {:?}",
            String::from_utf8_lossy(&v)
        ),
    }
}

#[test]
fn jailed_readlink_absolute_target_outside_jail_denied() {
    let tmp = TempDir::new("readlink-jail-abs-out");
    let jail = tmp.path().to_path_buf();
    std::os::unix::fs::symlink("/etc/passwd", jail.join("escape")).unwrap();

    let (a, b) = pair();
    let opts = SftpServerOptions::new(jail.clone()).with_root(jail);
    let h = spawn_server(opts, a);
    let mut client = SftpClient::new(b).unwrap();
    expect_permission_denied(client.readlink(b"escape"));
    drop(client);
    h.join().unwrap();
}

#[test]
fn jailed_readlink_relative_escape_denied() {
    let tmp = TempDir::new("readlink-jail-rel-out");
    let jail = tmp.path().to_path_buf();
    fs::create_dir_all(jail.join("sub")).unwrap();
    // From `sub/`, `../../etc/passwd` lexically leaves the jail.
    std::os::unix::fs::symlink("../../etc/passwd", jail.join("sub/trap")).unwrap();
    // A target with more `..` than there are ancestors is refused too.
    std::os::unix::fs::symlink("../../../../../../x", jail.join("deep")).unwrap();

    let (a, b) = pair();
    let opts = SftpServerOptions::new(jail.clone()).with_root(jail);
    let h = spawn_server(opts, a);
    let mut client = SftpClient::new(b).unwrap();
    expect_permission_denied(client.readlink(b"sub/trap"));
    expect_permission_denied(client.readlink(b"deep"));
    drop(client);
    h.join().unwrap();
}

#[test]
fn jailed_readlink_absolute_target_inside_jail_rewritten() {
    let tmp = TempDir::new("readlink-jail-abs-in");
    let jail = tmp.path().to_path_buf();
    fs::create_dir_all(jail.join("sub")).unwrap();
    fs::write(jail.join("sub/file"), b"x").unwrap();
    // Absolute host path to a file inside the jail.
    std::os::unix::fs::symlink(jail.join("sub/file"), jail.join("abs")).unwrap();

    // Default: hide the jail prefix, like realpath.
    let (a, b) = pair();
    let opts = SftpServerOptions::new(jail.clone()).with_root(jail.clone());
    let h = spawn_server(opts, a);
    let mut client = SftpClient::new(b).unwrap();
    let tgt = client.readlink(b"abs").unwrap();
    assert_eq!(String::from_utf8_lossy(&tgt), "/sub/file");
    drop(client);
    h.join().unwrap();

    // Explicit opt-out keeps the host path (still inside the jail).
    let (a, b) = pair();
    let opts = SftpServerOptions::new(jail.clone())
        .with_root(jail.clone())
        .hide_jail_in_realpath(false);
    let h = spawn_server(opts, a);
    let mut client = SftpClient::new(b).unwrap();
    let tgt = client.readlink(b"abs").unwrap();
    assert_eq!(
        String::from_utf8_lossy(&tgt),
        jail.join("sub/file").to_string_lossy()
    );
    drop(client);
    h.join().unwrap();
}

#[test]
fn jailed_readlink_relative_target_inside_jail_verbatim() {
    let tmp = TempDir::new("readlink-jail-rel-in");
    let jail = tmp.path().to_path_buf();
    fs::create_dir_all(jail.join("sub")).unwrap();
    std::os::unix::fs::symlink("../sub/file", jail.join("sub/rel")).unwrap();

    let (a, b) = pair();
    let opts = SftpServerOptions::new(jail.clone()).with_root(jail);
    let h = spawn_server(opts, a);
    let mut client = SftpClient::new(b).unwrap();
    let tgt = client.readlink(b"sub/rel").unwrap();
    assert_eq!(String::from_utf8_lossy(&tgt), "../sub/file");
    drop(client);
    h.join().unwrap();
}

#[test]
fn unjailed_readlink_returns_absolute_target_verbatim() {
    let tmp = TempDir::new("readlink-nojail");
    let dir = tmp.path().to_path_buf();
    std::os::unix::fs::symlink("/etc/passwd", dir.join("abs")).unwrap();

    let (a, b) = pair();
    let opts = SftpServerOptions::new(dir);
    let h = spawn_server(opts, a);
    let mut client = SftpClient::new(b).unwrap();
    let tgt = client.readlink(b"abs").unwrap();
    assert_eq!(String::from_utf8_lossy(&tgt), "/etc/passwd");
    drop(client);
    h.join().unwrap();
}

#[test]
fn jailed_realpath_strips_jail_prefix_when_opted_in() {
    let tmp = TempDir::new("realpath-jail");
    let jail = tmp.path().to_path_buf();
    let (a, b) = pair();
    let opts = SftpServerOptions::new(jail.clone())
        .with_root(jail.clone())
        .hide_jail_in_realpath(true);
    let h = spawn_server(opts, a);
    let mut client = SftpClient::new(b).unwrap();
    // Asking the jailed server to realpath "." should give us "/" not the
    // jail's absolute path on disk.
    let p = client.realpath(b".").unwrap();
    let s = String::from_utf8_lossy(&p);
    assert!(
        !s.contains(jail.to_string_lossy().as_ref()),
        "jail leaked in realpath: {s}"
    );
    assert_eq!(s, "/", "expected '/' inside jail, got {s}");
    let p = client.realpath(b"sub/file").unwrap();
    assert_eq!(String::from_utf8_lossy(&p), "/sub/file");
    drop(client);
    h.join().unwrap();
}

#[test]
fn jailed_realpath_hides_jail_prefix_by_default() {
    // The default is now `hide_jail_in_realpath(true)` so the host's
    // filesystem layout is never leaked unless the operator opts out.
    let tmp = TempDir::new("realpath-jail-default");
    let jail = tmp.path().to_path_buf();
    let (a, b) = pair();
    let opts = SftpServerOptions::new(jail.clone()).with_root(jail.clone());
    let h = spawn_server(opts, a);
    let mut client = SftpClient::new(b).unwrap();
    let p = client.realpath(b".").unwrap();
    let s = String::from_utf8_lossy(&p).to_string();
    assert_eq!(s, "/", "default should hide jail prefix in realpath");
    drop(client);
    h.join().unwrap();
}

#[test]
fn jailed_realpath_leaks_when_explicit_opt_out() {
    // Setting `hide_jail_in_realpath(false)` restores the historical
    // host-path behaviour for back-compat with clients that need it.
    let tmp = TempDir::new("realpath-jail-leak-optout");
    let jail = tmp.path().to_path_buf();
    let canon_jail = std::fs::canonicalize(&jail).unwrap_or_else(|_| jail.clone());
    let (a, b) = pair();
    let opts = SftpServerOptions::new(jail.clone())
        .with_root(jail.clone())
        .hide_jail_in_realpath(false);
    let h = spawn_server(opts, a);
    let mut client = SftpClient::new(b).unwrap();
    let p = client.realpath(b".").unwrap();
    let s = String::from_utf8_lossy(&p).to_string();
    assert!(
        s == jail.to_string_lossy() || s == canon_jail.to_string_lossy(),
        "expected unstripped jail path with opt-out, got {s}"
    );
    drop(client);
    h.join().unwrap();
}

// --- security: setstat size cap (finding #4) ---

#[test]
fn setstat_set_len_above_cap_rejected() {
    let tmp = TempDir::new("setlen");
    fs::write(tmp.path().join("f"), b"x").unwrap();
    let opts = SftpServerOptions::new(tmp.path()).with_max_set_len(1024);
    let (a, b) = pair();
    let h = spawn_server(opts, a);
    let mut client = SftpClient::new(b).unwrap();
    let attrs = Attrs {
        size: Some(8 * 1024), // above the 1 KiB cap
        ..Default::default()
    };
    let err = client.setstat(b"f", attrs).unwrap_err();
    match err {
        SftpError::Status { code, .. } => assert_eq!(code, FxpStatus::PermissionDenied),
        other => panic!("expected PermissionDenied, got {other:?}"),
    }
    // File is unchanged.
    assert_eq!(fs::read(tmp.path().join("f")).unwrap(), b"x");
    drop(client);
    h.join().unwrap();
}

// --- security: setuid/setgid/sticky stripping (finding #9) ---

#[test]
fn open_strips_setuid_bit_by_default() {
    use std::os::unix::fs::PermissionsExt as _;
    let tmp = TempDir::new("setuid");
    let (a, b) = pair();
    let h = spawn_server(SftpServerOptions::new(tmp.path()), a);
    let mut client = SftpClient::new(b).unwrap();
    let attrs = Attrs {
        // 04755: setuid + rwxr-xr-x
        permissions: Some(0o4755),
        ..Default::default()
    };
    let handle = client
        .open(b"suid.bin", FXF_WRITE | FXF_CREAT, attrs)
        .unwrap();
    client.close(&handle).unwrap();
    let md = fs::metadata(tmp.path().join("suid.bin")).unwrap();
    assert_eq!(
        md.permissions().mode() & 0o7777,
        0o0755,
        "setuid should be stripped by default"
    );
    drop(client);
    h.join().unwrap();
}

#[test]
fn setstat_strips_special_bits_by_default() {
    use std::os::unix::fs::PermissionsExt as _;
    let tmp = TempDir::new("setstat-special");
    fs::write(tmp.path().join("f"), b"x").unwrap();
    fs::set_permissions(tmp.path().join("f"), fs::Permissions::from_mode(0o644)).unwrap();
    let (a, b) = pair();
    let h = spawn_server(SftpServerOptions::new(tmp.path()), a);
    let mut client = SftpClient::new(b).unwrap();
    let attrs = Attrs {
        permissions: Some(0o6755), // setuid + setgid
        ..Default::default()
    };
    client.setstat(b"f", attrs).unwrap();
    let md = fs::metadata(tmp.path().join("f")).unwrap();
    assert_eq!(md.permissions().mode() & 0o7777, 0o0755);
    drop(client);
    h.join().unwrap();
}

struct OutsideGuard(PathBuf);
impl Drop for OutsideGuard {
    fn drop(&mut self) {
        let _ = fs::remove_file(&self.0);
    }
}

struct OutsideDirGuard(PathBuf);
impl Drop for OutsideDirGuard {
    fn drop(&mut self) {
        let _ = fs::remove_dir_all(&self.0);
    }
}

#[test]
fn large_file_round_trip() {
    let tmp = TempDir::new("large");
    let (a, b) = pair();
    let h = spawn_server(SftpServerOptions::new(tmp.path()), a);
    let mut client = SftpClient::new(b).unwrap();

    let handle = client
        .open(b"big", FXF_WRITE | FXF_CREAT | FXF_TRUNC, Attrs::default())
        .unwrap();
    let chunk = vec![0xab_u8; 32 * 1024];
    let total_chunks = 4_u64;
    for i in 0..total_chunks {
        client
            .write(&handle, i * chunk.len() as u64, &chunk)
            .unwrap();
    }
    client.close(&handle).unwrap();

    let handle = client.open(b"big", FXF_READ, Attrs::default()).unwrap();
    let mut got = Vec::new();
    let mut offset = 0u64;
    loop {
        let buf = client.read(&handle, offset, 32 * 1024).unwrap();
        if buf.is_empty() {
            break;
        }
        offset += buf.len() as u64;
        got.extend_from_slice(&buf);
    }
    client.close(&handle).unwrap();
    assert_eq!(got.len() as u64, total_chunks * chunk.len() as u64);
    assert!(got.iter().all(|&b| b == 0xab));

    drop(client);
    h.join().unwrap();
}

// --- OpenSSH SFTP extension tests ---

use super::packet::{Packet, read_packet, write_packet};

/// Drive an INIT/VERSION handshake on the given transport and return the
/// extension list the server advertised.
fn handshake(t: &mut UnixStream) -> Vec<(Vec<u8>, Vec<u8>)> {
    write_packet(
        t,
        &Packet::Init {
            version: super::types::SFTP_VERSION,
            extensions: vec![],
        },
    )
    .unwrap();
    let body = read_packet(t).unwrap();
    match Packet::decode(&body).unwrap() {
        Packet::Version { extensions, .. } => extensions,
        other => panic!("expected VERSION, got {other:?}"),
    }
}

/// Build the raw payload for an extension request body (string fields after
/// the extension name). Mirrors what an SFTP client would write into the
/// `data` portion of `Packet::Extended`.
fn ext_strings(parts: &[&[u8]]) -> Vec<u8> {
    let mut out = Vec::new();
    for p in parts {
        out.extend_from_slice(&(p.len() as u32).to_be_bytes());
        out.extend_from_slice(p);
    }
    out
}

/// Round-trip one SSH_FXP_EXTENDED request and return the reply packet.
fn ext_request(t: &mut UnixStream, request: &[u8], payload: &[u8]) -> Packet {
    let pkt = Packet::Extended {
        id: 42,
        request: request.to_vec(),
        data: payload.to_vec(),
    };
    write_packet(t, &pkt).unwrap();
    let body = read_packet(t).unwrap();
    Packet::decode(&body).unwrap()
}

#[test]
fn version_advertises_openssh_extensions() {
    let tmp = TempDir::new("ext-advertise");
    let (a, mut b) = pair();
    let h = spawn_server(SftpServerOptions::new(tmp.path()), a);
    let exts = handshake(&mut b);
    let names: Vec<String> = exts
        .iter()
        .map(|(k, _)| String::from_utf8_lossy(k).into_owned())
        .collect();
    for want in &[
        "posix-rename@openssh.com",
        "statvfs@openssh.com",
        "fstatvfs@openssh.com",
        "hardlink@openssh.com",
        "fsync@openssh.com",
    ] {
        assert!(
            names.iter().any(|n| n == want),
            "missing {want} in advertised extensions: {names:?}"
        );
    }
    drop(b);
    h.join().unwrap();
}

#[test]
fn posix_rename_overwrites_destination() {
    let tmp = TempDir::new("posix-rename-overwrite");
    fs::write(tmp.path().join("a"), b"alpha").unwrap();
    fs::write(tmp.path().join("b"), b"beta-original").unwrap();
    let (a, mut b) = pair();
    let h = spawn_server(SftpServerOptions::new(tmp.path()), a);
    let _ = handshake(&mut b);

    let payload = ext_strings(&[b"a", b"b"]);
    let reply = ext_request(&mut b, b"posix-rename@openssh.com", &payload);
    match reply {
        Packet::Status { code, .. } => assert_eq!(code, FxpStatus::Ok),
        other => panic!("expected STATUS, got {other:?}"),
    }
    assert!(!tmp.path().join("a").exists());
    assert_eq!(fs::read(tmp.path().join("b")).unwrap(), b"alpha");

    drop(b);
    h.join().unwrap();
}

#[test]
fn posix_rename_outside_jail_rejected() {
    let tmp = TempDir::new("posix-rename-jail");
    let jail = tmp.path().to_path_buf();
    fs::write(jail.join("inside"), b"x").unwrap();
    let (a, mut b) = pair();
    let opts = SftpServerOptions::new(jail.clone()).with_root(jail);
    let h = spawn_server(opts, a);
    let _ = handshake(&mut b);

    let payload = ext_strings(&[b"inside", b"../../tmp/escape"]);
    let reply = ext_request(&mut b, b"posix-rename@openssh.com", &payload);
    match reply {
        Packet::Status { code, .. } => assert_eq!(code, FxpStatus::PermissionDenied),
        other => panic!("expected STATUS, got {other:?}"),
    }

    drop(b);
    h.join().unwrap();
}

#[test]
fn posix_rename_through_symlink_rejected() {
    let tmp = TempDir::new("posix-rename-symjail");
    let jail = tmp.path().to_path_buf();
    let (outside, _g) = outside_victim("posix-rename", b"victim");
    // Plant a symlink at the rename source pointing outside the jail. The
    // lexical jail check passes (the link itself is inside), so the
    // final-component symlink guard is what must reject it.
    std::os::unix::fs::symlink(&outside, jail.join("from")).unwrap();
    let (a, mut b) = pair();
    let opts = SftpServerOptions::new(jail.clone()).with_root(jail.clone());
    let h = spawn_server(opts, a);
    let _ = handshake(&mut b);

    let payload = ext_strings(&[b"from", b"to"]);
    let reply = ext_request(&mut b, b"posix-rename@openssh.com", &payload);
    match reply {
        Packet::Status { code, .. } => assert_eq!(code, FxpStatus::NoSuchFile),
        other => panic!("expected STATUS, got {other:?}"),
    }
    // The outside victim is untouched and no `to` entry was created.
    assert!(outside.exists());
    assert!(!jail.join("to").exists());

    drop(b);
    h.join().unwrap();
}

#[test]
fn hardlink_creates_second_inode_reference() {
    use std::os::unix::fs::MetadataExt as _;
    let tmp = TempDir::new("hardlink");
    fs::write(tmp.path().join("orig"), b"shared").unwrap();
    let (a, mut b) = pair();
    let h = spawn_server(SftpServerOptions::new(tmp.path()), a);
    let _ = handshake(&mut b);

    let payload = ext_strings(&[b"orig", b"linked"]);
    let reply = ext_request(&mut b, b"hardlink@openssh.com", &payload);
    match reply {
        Packet::Status { code, .. } => assert_eq!(code, FxpStatus::Ok),
        other => panic!("expected STATUS, got {other:?}"),
    }
    let m1 = fs::metadata(tmp.path().join("orig")).unwrap();
    let m2 = fs::metadata(tmp.path().join("linked")).unwrap();
    assert_eq!(m1.ino(), m2.ino(), "expected same inode after hardlink");
    assert!(m2.nlink() >= 2);

    drop(b);
    h.join().unwrap();
}

#[test]
fn hardlink_outside_jail_rejected() {
    let tmp = TempDir::new("hardlink-jail");
    let jail = tmp.path().to_path_buf();
    fs::write(jail.join("inside"), b"x").unwrap();
    let (a, mut b) = pair();
    let opts = SftpServerOptions::new(jail.clone()).with_root(jail);
    let h = spawn_server(opts, a);
    let _ = handshake(&mut b);

    let payload = ext_strings(&[b"inside", b"../../tmp/hardlink-escape"]);
    let reply = ext_request(&mut b, b"hardlink@openssh.com", &payload);
    match reply {
        Packet::Status { code, .. } => assert_eq!(code, FxpStatus::PermissionDenied),
        other => panic!("expected STATUS, got {other:?}"),
    }

    drop(b);
    h.join().unwrap();
}

#[test]
fn fsync_returns_ok_for_open_handle() {
    let tmp = TempDir::new("fsync-ok");
    let (a, mut b) = pair();
    let h = spawn_server(SftpServerOptions::new(tmp.path()), a);
    let _ = handshake(&mut b);

    // Open a file via raw packets (we already consumed the handshake here,
    // so SftpClient::new wouldn't work on the same transport).
    let open = Packet::Open {
        id: 1,
        path: b"f".to_vec(),
        pflags: FXF_WRITE | FXF_CREAT,
        attrs: Attrs::default(),
    };
    write_packet(&mut b, &open).unwrap();
    let body = read_packet(&mut b).unwrap();
    let handle = match Packet::decode(&body).unwrap() {
        Packet::Handle { handle, .. } => handle,
        other => panic!("expected HANDLE, got {other:?}"),
    };

    let write = Packet::Write {
        id: 2,
        handle: handle.clone(),
        offset: 0,
        data: b"some bytes".to_vec(),
    };
    write_packet(&mut b, &write).unwrap();
    let _ = read_packet(&mut b).unwrap();

    let payload = ext_strings(&[&handle]);
    let reply = ext_request(&mut b, b"fsync@openssh.com", &payload);
    match reply {
        Packet::Status { code, .. } => assert_eq!(code, FxpStatus::Ok),
        other => panic!("expected STATUS, got {other:?}"),
    }

    drop(b);
    h.join().unwrap();
}

#[test]
fn fsync_unknown_handle_rejected() {
    let tmp = TempDir::new("fsync-bad");
    let (a, mut b) = pair();
    let h = spawn_server(SftpServerOptions::new(tmp.path()), a);
    let _ = handshake(&mut b);

    let fake = 0xdeadbeefu64.to_le_bytes().to_vec();
    let payload = ext_strings(&[&fake]);
    let reply = ext_request(&mut b, b"fsync@openssh.com", &payload);
    match reply {
        Packet::Status { code, .. } => assert_eq!(code, FxpStatus::Failure),
        other => panic!("expected STATUS, got {other:?}"),
    }

    drop(b);
    h.join().unwrap();
}

#[test]
fn statvfs_returns_filesystem_stats() {
    let tmp = TempDir::new("statvfs");
    let (a, mut b) = pair();
    let h = spawn_server(SftpServerOptions::new(tmp.path()), a);
    let _ = handshake(&mut b);

    let payload = ext_strings(&[b"."]);
    let reply = ext_request(&mut b, b"statvfs@openssh.com", &payload);
    let data = match reply {
        Packet::ExtendedReply { data, .. } => data,
        other => panic!("expected EXTENDED_REPLY, got {other:?}"),
    };
    assert_eq!(data.len(), 8 * 11, "statvfs reply must be 11 u64s");
    // f_namemax is the eleventh u64.
    let mut namemax_bytes = [0u8; 8];
    namemax_bytes.copy_from_slice(&data[80..88]);
    let namemax = u64::from_be_bytes(namemax_bytes);
    assert!(namemax >= 64, "expected f_namemax >= 64, got {namemax}");

    drop(b);
    h.join().unwrap();
}

#[test]
fn fstatvfs_returns_filesystem_stats() {
    let tmp = TempDir::new("fstatvfs");
    fs::write(tmp.path().join("f"), b"x").unwrap();
    let (a, mut b) = pair();
    let h = spawn_server(SftpServerOptions::new(tmp.path()), a);
    let _ = handshake(&mut b);

    let open = Packet::Open {
        id: 1,
        path: b"f".to_vec(),
        pflags: FXF_READ,
        attrs: Attrs::default(),
    };
    write_packet(&mut b, &open).unwrap();
    let body = read_packet(&mut b).unwrap();
    let handle = match Packet::decode(&body).unwrap() {
        Packet::Handle { handle, .. } => handle,
        other => panic!("expected HANDLE, got {other:?}"),
    };

    let payload = ext_strings(&[&handle]);
    let reply = ext_request(&mut b, b"fstatvfs@openssh.com", &payload);
    let data = match reply {
        Packet::ExtendedReply { data, .. } => data,
        other => panic!("expected EXTENDED_REPLY, got {other:?}"),
    };
    assert_eq!(data.len(), 8 * 11);

    drop(b);
    h.join().unwrap();
}

#[test]
fn unknown_extended_request_returns_op_unsupported() {
    let tmp = TempDir::new("ext-unknown");
    let (a, mut b) = pair();
    let h = spawn_server(SftpServerOptions::new(tmp.path()), a);
    let _ = handshake(&mut b);

    let payload = ext_strings(&[b"whatever"]);
    let reply = ext_request(&mut b, b"bogus@example.com", &payload);
    match reply {
        Packet::Status { code, .. } => assert_eq!(code, FxpStatus::OpUnsupported),
        other => panic!("expected STATUS, got {other:?}"),
    }

    drop(b);
    h.join().unwrap();
}

#[test]
fn pipelined_write_from_and_read_to() {
    let tmp = TempDir::new("pipelined");
    let (a, b) = pair();
    let h = spawn_server(SftpServerOptions::new(tmp.path()), a);
    let mut client = SftpClient::new(b).unwrap();

    // Not a multiple of the chunk size, so the last request is short.
    let data: Vec<u8> = (0..1_000_003u32).map(|i| (i * 7 + i / 251) as u8).collect();
    let handle = client
        .open(
            b"big.bin",
            FXF_WRITE | FXF_CREAT | FXF_TRUNC,
            Attrs::default(),
        )
        .unwrap();
    let mut last = 0;
    let n = client
        .write_from(&handle, 0, 4096, 8, &mut &data[..], |p| last = p)
        .unwrap();
    client.close(&handle).unwrap();
    assert_eq!(n, data.len() as u64);
    assert_eq!(last, data.len() as u64);
    assert_eq!(fs::read(tmp.path().join("big.bin")).unwrap(), data);

    let handle = client.open(b"big.bin", FXF_READ, Attrs::default()).unwrap();
    let mut back = Vec::new();
    let n = client
        .read_to(&handle, 0, 4096, 8, &mut back, |_| {})
        .unwrap();
    assert_eq!(n, data.len() as u64);
    assert_eq!(back, data);
    // Resume from an offset (reget).
    let mut tail = Vec::new();
    client
        .read_to(&handle, 999_000, 4096, 8, &mut tail, |_| {})
        .unwrap();
    assert_eq!(tail, data[999_000..]);
    client.close(&handle).unwrap();

    // The session is still usable afterwards.
    assert!(client.stat(b"big.bin").is_ok());
    drop(client);
    h.join().unwrap();
}

#[test]
fn copy_data_and_limits() {
    let tmp = TempDir::new("copy-data");
    fs::write(tmp.path().join("src"), b"0123456789").unwrap();
    let (a, b) = pair();
    let h = spawn_server(SftpServerOptions::new(tmp.path()), a);
    let mut client = SftpClient::new(b).unwrap();
    assert!(client.has_extension("copy-data"));
    assert!(client.has_extension("limits@openssh.com"));

    let rh = client.open(b"src", FXF_READ, Attrs::default()).unwrap();
    let wh = client
        .open(b"dst", FXF_WRITE | FXF_CREAT | FXF_TRUNC, Attrs::default())
        .unwrap();
    // Whole file, then a slice appended at offset 10.
    client.copy_data(&rh, 0, 0, &wh, 0).unwrap();
    client.copy_data(&rh, 2, 3, &wh, 10).unwrap();
    // Not within one file.
    assert!(client.copy_data(&rh, 0, 0, &rh, 0).is_err());
    client.close(&rh).unwrap();
    client.close(&wh).unwrap();
    assert_eq!(fs::read(tmp.path().join("dst")).unwrap(), b"0123456789234");

    let limits = client.extended("limits@openssh.com", &[]).unwrap().unwrap();
    assert_eq!(limits.len(), 32);
    assert!(u64::from_be_bytes(limits[8..16].try_into().unwrap()) > 0);

    drop(client);
    h.join().unwrap();
}

#[test]
fn copy_data_refuses_aliased_and_unbounded_sources() {
    // XFER-3: the same inode under another name (hard link), or a source
    // with no end (`/dev/zero`), would otherwise copy forever.
    let tmp = TempDir::new("copy-data-alias");
    fs::write(tmp.path().join("src"), b"0123456789").unwrap();
    fs::hard_link(tmp.path().join("src"), tmp.path().join("alias")).unwrap();
    let (a, b) = pair();
    let h = spawn_server(SftpServerOptions::new(tmp.path()), a);
    let mut client = SftpClient::new(b).unwrap();

    let rh = client.open(b"src", FXF_READ, Attrs::default()).unwrap();
    let wh = client.open(b"alias", FXF_WRITE, Attrs::default()).unwrap();
    assert!(client.copy_data(&rh, 0, 0, &wh, 1).is_err());
    client.close(&rh).unwrap();

    let zero = client
        .open(b"/dev/zero", FXF_READ, Attrs::default())
        .unwrap();
    assert!(client.copy_data(&zero, 0, 0, &wh, 0).is_err());
    client.close(&zero).unwrap();
    client.close(&wh).unwrap();
    assert_eq!(fs::read(tmp.path().join("src")).unwrap(), b"0123456789");

    drop(client);
    h.join().unwrap();
}

#[test]
fn jailed_home_lookups_hide_outside_homes() {
    // XFER-5: a home outside the jail must look exactly like an unknown
    // user, and must never be echoed as a host path.
    let tmp = TempDir::new("home-jail");
    let jail = tmp.path().to_path_buf();
    let (a, mut b) = pair();
    let opts = SftpServerOptions::new(jail.clone()).with_root(jail);
    let h = spawn_server(opts, a);
    let _ = handshake(&mut b);
    let expect_nsf = |reply: Packet| match reply {
        Packet::Status { code, .. } => assert_eq!(code, FxpStatus::NoSuchFile),
        other => panic!("expected NoSuchFile, got {other:?}"),
    };
    for user in [&b""[..], b"root", b"no-such-user-puressh-xfer5"] {
        expect_nsf(ext_request(
            &mut b,
            b"home-directory",
            &ext_strings(&[user]),
        ));
        let mut p = b"~".to_vec();
        p.extend_from_slice(user);
        expect_nsf(ext_request(
            &mut b,
            b"expand-path@openssh.com",
            &ext_strings(&[&p]),
        ));
    }
    drop(b);
    h.join().unwrap();
}

#[test]
fn read_to_bounds_readahead_when_first_range_trickles() {
    // XFER-4: a server that answers the lowest range one byte at a time
    // while answering every later range in full must not make the client
    // run (and buffer) arbitrarily far ahead of what reached the sink.
    const CHUNK: u32 = 64;
    const DEPTH: usize = 4;
    const SIZE: u64 = 64 * 1000;
    let (a, mut b) = pair();
    let server = thread::spawn(move || {
        let _ = read_packet(&mut b).unwrap();
        write_packet(
            &mut b,
            &Packet::Version {
                version: 3,
                extensions: Vec::new(),
            },
        )
        .unwrap();
        // Highest offset requested before the first chunk was complete.
        let mut first_done = false;
        let mut max_ahead = 0u64;
        while let Ok(body) = read_packet(&mut b) {
            let Packet::Read {
                id, offset, len, ..
            } = Packet::decode(&body).unwrap()
            else {
                panic!("expected READ");
            };
            if !first_done {
                max_ahead = max_ahead.max(offset);
            }
            let reply = if offset >= SIZE {
                Packet::Status {
                    id,
                    code: FxpStatus::Eof,
                    message: Vec::new(),
                    lang: Vec::new(),
                }
            } else {
                let n = if offset < u64::from(CHUNK) {
                    first_done |= offset + 1 == u64::from(CHUNK);
                    1
                } else {
                    len as usize
                };
                Packet::Data {
                    id,
                    data: vec![b'x'; n],
                }
            };
            write_packet(&mut b, &reply).unwrap();
        }
        max_ahead
    });
    let mut client = SftpClient::new(a).unwrap();
    let mut sink = Vec::new();
    let n = client
        .read_to(b"h", 0, CHUNK, DEPTH, &mut sink, |_| {})
        .unwrap();
    assert_eq!(n, SIZE);
    drop(client);
    let max_ahead = server.join().unwrap();
    assert!(
        max_ahead <= (DEPTH as u64 + 1) * u64::from(CHUNK),
        "client read {max_ahead} bytes ahead of the sink"
    );
}