bssh 2.4.3

Parallel SSH command execution tool for cluster management
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
// Copyright 2025 Lablup Inc. and Jeongkyu Shin
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

//! Integration tests for the SCP/SFTP path-resolution and chroot-mode fixes
//! introduced for issue #186.
//!
//! These tests validate the public API of `ScpHandler` and `SftpHandler`
//! against the acceptance criteria in the issue:
//!
//! - Without chroot, absolute client paths are honored verbatim and relative
//!   paths resolve from the user's home directory (OpenSSH-compatible).
//! - With chroot, the client's `/` is the chroot root, so both absolute and
//!   relative client paths are re-anchored under it (SFTP and SCP alike), with
//!   `..` clamped and host-looking paths confined inside the root (#214).
//! - Path-traversal and symlink-escape protections continue to hold under
//!   the new logic.
//!
//! End-to-end tests with a running `bssh-server` and a real `scp` or
//! `bssh upload` client are out of scope for this file (they require host
//! key generation and process spawning), but the path-resolution layer
//! covered here is the one the issue identifies as defective. Bug-fix
//! coverage starts here and is supplemented by the unit tests inside the
//! `scp` and `sftp` modules.

use std::path::{Path, PathBuf};

use bssh::server::scp::{ScpHandler, ScpMode};
use bssh::server::sftp::SftpHandler;
use bssh::shared::auth_types::UserInfo;
use tempfile::tempdir;

fn user() -> UserInfo {
    UserInfo::new("work")
}

// ---------------------------------------------------------------------------
// SCP path resolution
// ---------------------------------------------------------------------------

#[test]
fn scp_no_chroot_accepts_absolute_client_path() {
    // Reproduction of the Backend.AI bug: client sends `/home/work/file.bin`
    // and the server must write to exactly `/home/work/file.bin`. Previously
    // the path got doubled to `/home/work/home/work/file.bin`.
    let handler = ScpHandler::new(
        ScpMode::Sink,
        PathBuf::from("/home/work/file.bin"),
        user(),
        None, // no chroot — the recommended default after this fix.
        PathBuf::from("/home/work"),
    );
    let resolved = handler
        .resolve_path(Path::new("/home/work/file.bin"))
        .expect("absolute path inside home dir should resolve");
    assert_eq!(resolved, PathBuf::from("/home/work/file.bin"));
}

#[test]
fn scp_no_chroot_accepts_path_outside_home() {
    // Without chroot, `/tmp/foo` is just `/tmp/foo`. Filesystem permissions
    // are the only access boundary, matching OpenSSH `scp`.
    let handler = ScpHandler::new(
        ScpMode::Sink,
        PathBuf::from("/tmp/foo.bin"),
        user(),
        None,
        PathBuf::from("/home/work"),
    );
    let resolved = handler
        .resolve_path(Path::new("/tmp/foo.bin"))
        .expect("absolute path should resolve");
    assert_eq!(resolved, PathBuf::from("/tmp/foo.bin"));
}

#[test]
fn scp_no_chroot_relative_path_lands_in_home() {
    let handler = ScpHandler::new(
        ScpMode::Sink,
        PathBuf::from("file.bin"),
        user(),
        None,
        PathBuf::from("/home/work"),
    );
    let resolved = handler
        .resolve_path(Path::new("file.bin"))
        .expect("relative path should resolve");
    assert_eq!(resolved, PathBuf::from("/home/work/file.bin"));
}

#[test]
fn scp_chroot_absolute_path_reanchored_under_root() {
    // Under chroot the client's "/" IS the chroot root (matching sftp.root), so
    // an absolute client path is re-anchored under the root: "/file.bin" means
    // "<root>/file.bin". The client sends chroot-relative paths, not host paths.
    let handler = ScpHandler::new(
        ScpMode::Sink,
        PathBuf::from("/file.bin"),
        user(),
        Some(PathBuf::from("/home/work")),
        PathBuf::from("/home/work"),
    );
    let resolved = handler
        .resolve_path(Path::new("/file.bin"))
        .expect("absolute chroot-relative path should resolve");
    assert_eq!(resolved, PathBuf::from("/home/work/file.bin"));
}

#[test]
fn scp_chroot_absolute_host_path_confined_under_root() {
    // A client "/etc/passwd" is confined under the chroot, mapping to
    // <root>/etc/passwd, never the host's /etc/passwd. (Rejecting absolute
    // paths outright, as before, also broke every legitimate path and diverged
    // from sftp.root; #214.)
    let handler = ScpHandler::new(
        ScpMode::Sink,
        PathBuf::from("/etc/passwd"),
        user(),
        Some(PathBuf::from("/home/work")),
        PathBuf::from("/home/work"),
    );
    let resolved = handler
        .resolve_path(Path::new("/etc/passwd"))
        .expect("absolute host-looking path should be confined, not rejected");
    assert_eq!(resolved, PathBuf::from("/home/work/etc/passwd"));
}

#[test]
fn scp_chroot_relative_traversal_clamped() {
    let handler = ScpHandler::new(
        ScpMode::Sink,
        PathBuf::from("../etc/passwd"),
        user(),
        Some(PathBuf::from("/home/work")),
        PathBuf::from("/home/work"),
    );
    // The traversal-protection invariant: `..` cannot escape the chroot.
    let resolved = handler
        .resolve_path(Path::new("../etc/passwd"))
        .expect("relative traversal should be clamped, not rejected");
    assert!(resolved.starts_with("/home/work"));
    assert_eq!(resolved, PathBuf::from("/home/work/etc/passwd"));
}

// ---------------------------------------------------------------------------
// SFTP path resolution
// ---------------------------------------------------------------------------

#[test]
fn sftp_no_chroot_accepts_absolute_client_path() {
    // Reproduction of the SFTP variant of the Backend.AI bug: `bssh upload`
    // sending an absolute path to `bssh-server` previously failed with
    // "No such file" because of path doubling.
    let handler = SftpHandler::new(user(), None, PathBuf::from("/home/work"));
    let resolved = handler
        .resolve_path("/home/work/file.bin")
        .expect("absolute path inside home dir should resolve");
    assert_eq!(resolved, PathBuf::from("/home/work/file.bin"));
}

#[test]
fn sftp_no_chroot_accepts_path_outside_home() {
    let handler = SftpHandler::new(user(), None, PathBuf::from("/home/work"));
    let resolved = handler
        .resolve_path("/tmp/foo.bin")
        .expect("absolute path should resolve");
    assert_eq!(resolved, PathBuf::from("/tmp/foo.bin"));
}

#[test]
fn sftp_no_chroot_relative_path_lands_in_home() {
    let handler = SftpHandler::new(user(), None, PathBuf::from("/home/work"));
    let resolved = handler.resolve_path("file.bin").unwrap();
    assert_eq!(resolved, PathBuf::from("/home/work/file.bin"));
}

#[test]
fn sftp_chroot_absolute_path_reanchored_under_root() {
    // Under chroot the client's "/" IS the chroot root, so an absolute client
    // path is re-anchored under the root, not treated as a host path. The
    // client sends "/file.bin" meaning "<root>/file.bin". (#214)
    let handler = SftpHandler::new(
        user(),
        Some(PathBuf::from("/home/work")),
        PathBuf::from("/home/work"),
    );
    let resolved = handler.resolve_path("/file.bin").unwrap();
    assert_eq!(resolved, PathBuf::from("/home/work/file.bin"));
}

#[test]
fn sftp_chroot_absolute_host_path_confined_under_root() {
    // A client "/etc/passwd" is confined under the chroot, mapping to
    // <root>/etc/passwd — never the host's /etc/passwd. (Rejecting absolute
    // paths outright, as before, also broke every legitimate path; #214.)
    let handler = SftpHandler::new(
        user(),
        Some(PathBuf::from("/home/work")),
        PathBuf::from("/home/work"),
    );
    let resolved = handler.resolve_path("/etc/passwd").unwrap();
    assert_eq!(resolved, PathBuf::from("/home/work/etc/passwd"));
}

#[test]
fn sftp_chroot_relative_traversal_clamped() {
    let handler = SftpHandler::new(
        user(),
        Some(PathBuf::from("/home/work")),
        PathBuf::from("/home/work"),
    );
    let resolved = handler.resolve_path("../../etc/passwd").unwrap();
    assert!(resolved.starts_with("/home/work"));
    assert_eq!(resolved, PathBuf::from("/home/work/etc/passwd"));
}

#[test]
fn sftp_chroot_root_path_returns_chroot() {
    // The realpath roundtrip: `realpath(".")` returns "/" to the client, and
    // a subsequent client request for "/" must resolve back to the chroot
    // directory, not get rejected as "outside root".
    let handler = SftpHandler::new(
        user(),
        Some(PathBuf::from("/home/work")),
        PathBuf::from("/home/work"),
    );
    let resolved = handler.resolve_path("/").unwrap();
    assert_eq!(resolved, PathBuf::from("/home/work"));
}

// ---------------------------------------------------------------------------
// Symlink-escape protection
// ---------------------------------------------------------------------------

/// Create a symlink pointing outside the chroot and ensure the SCP resolver
/// blocks it via canonicalization.
#[test]
#[cfg(unix)]
fn scp_chroot_blocks_symlink_escape() {
    let dir = tempdir().expect("tempdir");
    let chroot = dir.path().join("chroot");
    std::fs::create_dir(&chroot).unwrap();

    // Create a target file outside the chroot and a symlink inside that
    // points at it. Resolving the symlink path must canonicalize and reject.
    let outside_target = dir.path().join("outside.txt");
    std::fs::write(&outside_target, b"secret").unwrap();
    let escape_link = chroot.join("escape");
    std::os::unix::fs::symlink(&outside_target, &escape_link).unwrap();

    let handler = ScpHandler::new(
        ScpMode::Source,
        escape_link.clone(),
        user(),
        Some(chroot.clone()),
        chroot.clone(),
    );
    // The client sends the chroot-relative path "/escape"; canonicalizing the
    // symlink must detect the target lands outside the chroot.
    let err = handler
        .resolve_path(Path::new("/escape"))
        .expect_err("symlink escape must be blocked");
    assert!(
        err.to_string().contains("symlink target outside root"),
        "expected symlink-escape error, got: {err}"
    );
}

/// Verify that the SCP resolver still rejects a symlink-escape attempt when
/// the user supplies a path *inside* the chroot but the resolved canonical
/// path lands outside, even if the symlink is reached through a relative
/// client path.
#[test]
#[cfg(unix)]
fn scp_chroot_blocks_relative_symlink_escape() {
    let dir = tempdir().unwrap();
    let chroot = dir.path().join("chroot");
    std::fs::create_dir(&chroot).unwrap();

    let outside_target = dir.path().join("outside.txt");
    std::fs::write(&outside_target, b"secret").unwrap();
    std::os::unix::fs::symlink(&outside_target, chroot.join("link")).unwrap();

    let handler = ScpHandler::new(
        ScpMode::Source,
        PathBuf::from("link"),
        user(),
        Some(chroot.clone()),
        chroot.clone(),
    );
    let err = handler
        .resolve_path(Path::new("link"))
        .expect_err("relative symlink escape must be blocked");
    assert!(err.to_string().contains("symlink target outside root"));
}

// ---------------------------------------------------------------------------
// Parent-directory symlink escape (issue #186 review-time finding)
// ---------------------------------------------------------------------------
//
// An attacker who can place a symlink inside the chroot pointing to a
// directory outside the chroot must not be able to create files outside the
// chroot by writing through the symlink. Lexical `starts_with(root)` alone
// cannot detect this — the chroot resolver also has to canonicalize the
// closest existing ancestor and compare it against the canonicalized chroot.

#[test]
#[cfg(unix)]
fn scp_chroot_blocks_parent_symlink_create() {
    let dir = tempdir().unwrap();
    let chroot = dir.path().join("chroot");
    std::fs::create_dir(&chroot).unwrap();
    let outside = dir.path().join("outside");
    std::fs::create_dir(&outside).unwrap();
    std::os::unix::fs::symlink(&outside, chroot.join("escape")).unwrap();

    let target = chroot.join("escape").join("newfile.txt");
    let handler = ScpHandler::new(
        ScpMode::Sink,
        target.clone(),
        user(),
        Some(chroot.clone()),
        chroot.clone(),
    );

    // The client sends a chroot-relative path traversing the `escape` parent
    // symlink; canonicalization of the closest existing ancestor must still
    // detect that it lands outside the chroot.
    let err = handler
        .resolve_path(Path::new("/escape/newfile.txt"))
        .expect_err("parent-symlink escape must be blocked");
    assert!(
        err.to_string().contains("outside root"),
        "expected access-denied error, got: {err}"
    );
}

#[test]
#[cfg(unix)]
fn sftp_chroot_blocks_parent_symlink_create() {
    let dir = tempdir().unwrap();
    let chroot = dir.path().join("chroot");
    std::fs::create_dir(&chroot).unwrap();
    let outside = dir.path().join("outside");
    std::fs::create_dir(&outside).unwrap();
    std::os::unix::fs::symlink(&outside, chroot.join("escape")).unwrap();

    let handler = SftpHandler::new(user(), Some(chroot.clone()), chroot.clone());

    // The client sends a chroot-relative path that traverses the `escape`
    // parent symlink; canonicalization of the closest existing ancestor must
    // still detect that it lands outside the chroot.
    let err = handler
        .resolve_path("/escape/newfile.txt")
        .expect_err("parent-symlink escape must be blocked");
    assert!(
        err.to_string().contains("outside root"),
        "expected permission-denied, got: {err}"
    );
}

#[test]
#[cfg(unix)]
fn sftp_chroot_blocks_parent_symlink_mkdir() {
    let dir = tempdir().unwrap();
    let chroot = dir.path().join("chroot");
    std::fs::create_dir(&chroot).unwrap();
    let outside = dir.path().join("outside");
    std::fs::create_dir(&outside).unwrap();
    std::os::unix::fs::symlink(&outside, chroot.join("escape")).unwrap();

    let handler = SftpHandler::new(user(), Some(chroot.clone()), chroot.clone());

    // Chroot-relative mkdir target traversing the `escape` parent symlink.
    let err = handler
        .resolve_path("/escape/newdir")
        .expect_err("parent-symlink mkdir-target must be blocked");
    assert!(err.to_string().contains("outside root"));
}

#[test]
#[cfg(unix)]
fn scp_chroot_blocks_relative_through_parent_symlink() {
    let dir = tempdir().unwrap();
    let chroot = dir.path().join("chroot");
    std::fs::create_dir(&chroot).unwrap();
    let outside = dir.path().join("outside");
    std::fs::create_dir(&outside).unwrap();
    std::os::unix::fs::symlink(&outside, chroot.join("escape")).unwrap();

    let handler = ScpHandler::new(
        ScpMode::Sink,
        PathBuf::from("escape/newfile.txt"),
        user(),
        Some(chroot.clone()),
        chroot.clone(),
    );

    let err = handler
        .resolve_path(Path::new("escape/newfile.txt"))
        .expect_err("relative parent-symlink escape must be blocked");
    assert!(err.to_string().contains("outside root"));
}

#[test]
#[cfg(unix)]
fn scp_chroot_allows_legitimate_nested_create() {
    // Sanity: ensure the new check does not over-reject normal nested writes
    // through legitimate (in-chroot) directories.
    let dir = tempdir().unwrap();
    let chroot = dir.path().join("chroot");
    std::fs::create_dir(&chroot).unwrap();
    std::fs::create_dir(chroot.join("subdir")).unwrap();

    let target = chroot.join("subdir").join("legit.txt");
    let handler = ScpHandler::new(
        ScpMode::Sink,
        target.clone(),
        user(),
        Some(chroot.clone()),
        chroot.clone(),
    );

    let resolved = handler
        .resolve_path(&target)
        .expect("legitimate nested create should resolve");
    assert!(resolved.starts_with(&chroot));
}

#[test]
#[cfg(unix)]
fn sftp_chroot_allows_create_in_nonexistent_subdir() {
    // The intermediate-symlink check must NOT reject paths whose parents
    // simply don't exist (legitimate mkdir-then-create flow).
    let dir = tempdir().unwrap();
    let chroot = dir.path().join("chroot");
    std::fs::create_dir(&chroot).unwrap();

    let handler = SftpHandler::new(user(), Some(chroot.clone()), chroot.clone());

    let target_str = format!("{}/will-be-created/newfile.txt", chroot.display());
    let resolved = handler
        .resolve_path(&target_str)
        .expect("nested non-existent subdir should resolve");
    assert!(resolved.starts_with(&chroot));
}