Compare commits

...

24 Commits

Author SHA1 Message Date
sigoden b69946df23 chore: release v0.46.0 (#675) 2026-05-07 09:44:15 +08:00
sigoden 82a8865b9f feat: skip directory walking in HEAD requests (#701) 2026-04-30 19:55:57 +08:00
sigoden 8e90ffa9c8 refactor: webui file size format (#698) 2026-04-27 08:12:35 +08:00
florinm03 4f2dee3916 fix: webui safari bug uploadspeed (#695) 2026-04-27 07:09:14 +08:00
florinm03 b87f87646a feat: webui confirm on exit while uploading (#693) 2026-04-25 21:59:23 +08:00
sigoden 30b2979d0a chore: update deps (#694) 2026-04-25 21:31:44 +08:00
sigoden 53ea692dd1 feat: enhence log format (#692) 2026-04-25 20:38:39 +08:00
sigoden 1af66d6744 fix: escape control chars in logged URI and headers (#691) 2026-04-25 18:51:21 +08:00
sigoden 19dc2c205a fix: http range underflow (#690) 2026-04-25 17:59:44 +08:00
sigoden 43c778182b fix: tweak auth logic (#689) 2026-04-25 17:28:28 +08:00
sigoden 0ccc2cf1e7 feat: support customizable 404 page (#688) 2026-04-24 08:20:19 +08:00
sigoden a88a4ee630 feat: support ?json on file path (#686) 2026-04-23 18:39:26 +08:00
sigoden a118c1348e fix: ensure symlink inside serve root (#670) 2026-02-05 22:08:04 +08:00
sigoden db7a0530a2 fix: escape filename in ?simple output (#669) 2026-02-05 19:13:10 +08:00
sigoden bc27c8c479 fix: some search results missing due to broken symlinks (#665) 2026-01-21 12:00:57 +08:00
sigoden 2b2c7bd5f7 feat: add option --allow-hash to allow/disallow file hashing (#657) 2026-01-09 16:43:18 +08:00
sigoden ca18df1a36 refactor: improve UI botton titles (#656) 2026-01-09 16:21:40 +08:00
sigoden 7cfb97dfdf refactor: update deps (#655) 2026-01-08 12:02:41 +08:00
sigoden 23619033ae chore: release v0.45.0 (#626) 2025-09-04 18:10:54 +08:00
sigoden db75ba4357 fix: verify token length (#627) 2025-09-02 18:48:17 +08:00
sigoden 4016715187 fix: login btn does not work for readonly annoymous (#620) 2025-08-19 08:58:59 +08:00
sigoden f8a7873582 fix: perms on dufs -A -a @/:ro (#619) 2025-08-19 07:51:52 +08:00
sigoden 7f8269881d feat: log decoded uri (#615) 2025-08-18 09:00:18 +08:00
sigoden b2f244a4cf feat: make dir urls inherit ?noscript params (#614) 2025-08-16 07:36:19 +08:00
27 changed files with 1591 additions and 748 deletions
+1 -1
View File
@@ -29,7 +29,7 @@ jobs:
RUSTFLAGS: --deny warnings
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- name: Install Rust Toolchain Components
uses: dtolnay/rust-toolchain@stable
+2 -11
View File
@@ -38,14 +38,6 @@ jobs:
os: ubuntu-latest
use-cross: true
cargo-flags: ""
- target: i686-unknown-linux-musl
os: ubuntu-latest
use-cross: true
cargo-flags: ""
- target: i686-pc-windows-msvc
os: windows-latest
use-cross: true
cargo-flags: ""
- target: armv7-unknown-linux-musleabihf
os: ubuntu-latest
use-cross: true
@@ -60,7 +52,7 @@ jobs:
BUILD_CMD: cargo
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- name: Check Tag
id: check-tag
@@ -170,7 +162,6 @@ jobs:
platforms: |
linux/amd64
linux/arm64
linux/386
linux/arm/v7
push: ${{ needs.release.outputs.rc == 'false' }}
tags: ${{ github.repository }}:latest, ${{ github.repository }}:${{ github.ref_name }}
@@ -181,7 +172,7 @@ jobs:
runs-on: ubuntu-latest
needs: release
steps:
- uses: actions/checkout@v4
- uses: actions/checkout@v6
- uses: dtolnay/rust-toolchain@stable
+40
View File
@@ -2,6 +2,46 @@
All notable changes to this project will be documented in this file.
## [0.46.0] - 2026-05-07
### Features
- Add option --allow-hash to allow/disallow file hashing ([#657](https://github.com/sigoden/dufs/issues/657))
- Support `?json` on file path ([#686](https://github.com/sigoden/dufs/issues/686))
- Support customizable 404 page ([#688](https://github.com/sigoden/dufs/issues/688))
- Enhance log format ([#692](https://github.com/sigoden/dufs/issues/692))
- Webui confirm on exit while uploading ([#693](https://github.com/sigoden/dufs/issues/693))
- Skip directory walking in HEAD requests ([#701](https://github.com/sigoden/dufs/issues/701))
### Bug Fixes
- Some search results missing due to broken symlinks ([#665](https://github.com/sigoden/dufs/issues/665))
- Escape filename in ?simple output ([#669](https://github.com/sigoden/dufs/issues/669))
- Ensure symlink inside serve root ([#670](https://github.com/sigoden/dufs/issues/670))
- Tweak auth logic ([#689](https://github.com/sigoden/dufs/issues/689))
- Http range underflow ([#690](https://github.com/sigoden/dufs/issues/690))
- Escape control chars in logged URI and headers ([#691](https://github.com/sigoden/dufs/issues/691))
- Webui safari bug uploadspeed ([#695](https://github.com/sigoden/dufs/issues/695))
### Refactor
- Update deps ([#655](https://github.com/sigoden/dufs/issues/655))
- Improve UI button titles ([#656](https://github.com/sigoden/dufs/issues/656))
- Webui file size format ([#698](https://github.com/sigoden/dufs/issues/698))
## [0.45.0] - 2025-09-03
### Bug Fixes
- Perms on `dufs -A -a @/:ro` ([#619](https://github.com/sigoden/dufs/issues/619))
- Login btn does not work for readonly anonymous ([#620](https://github.com/sigoden/dufs/issues/620))
- Verify token length ([#627](https://github.com/sigoden/dufs/issues/627))
### Features
- Make dir urls inherit `?noscript` params ([#614](https://github.com/sigoden/dufs/issues/614))
- Log decoded uri ([#615](https://github.com/sigoden/dufs/issues/615))
## [0.44.0] - 2025-08-02
### Bug Fixes
Generated
+1035 -576
View File
File diff suppressed because it is too large Load Diff
+9 -10
View File
@@ -1,6 +1,6 @@
[package]
name = "dufs"
version = "0.44.0"
version = "0.46.0"
edition = "2021"
authors = ["sigoden <sigoden@gmail.com>"]
description = "Dufs is a distinctive utility file server"
@@ -24,14 +24,13 @@ futures-util = { version = "0.3", default-features = false, features = ["alloc"]
async_zip = { version = "0.0.18", default-features = false, features = ["deflate", "bzip2", "xz", "chrono", "tokio"] }
headers = "0.4"
mime_guess = "2.0"
if-addrs = "0.14"
rustls-pemfile = { version = "2.0", optional = true }
tokio-rustls = { version = "0.26", optional = true, default-features = false, features = ["ring", "tls12"]}
if-addrs = "0.15"
tokio-rustls = { version = "0.26", optional = true }
md5 = "0.8"
lazy_static = "1.4"
uuid = { version = "1.7", features = ["v4", "fast-rng"] }
urlencoding = "2.1"
xml-rs = "0.8"
xml-rs = "1.0.0"
log = { version = "0.4", features = ["std"] }
socket2 = "0.6"
async-stream = "0.3"
@@ -40,11 +39,11 @@ form_urlencoded = "1.2"
alphanumeric-sort = "1.4"
content_inspector = "0.2"
anyhow = "1.0"
chardetng = "0.1"
chardetng = "1.0"
glob = "0.3"
indexmap = "2.2"
serde_yaml = "0.9"
sha-crypt = "0.5"
sha-crypt = "0.6"
base64 = "0.22"
smart-default = "0.7"
rustls-pki-types = "1.2"
@@ -52,17 +51,17 @@ hyper-util = { version = "0.1", features = ["server-auto", "tokio"] }
http-body-util = "0.1"
bytes = "1.5"
pin-project-lite = "0.2"
sha2 = "0.10.8"
sha2 = "0.11.0"
ed25519-dalek = "2.2.0"
hex = "0.4.3"
[features]
default = ["tls"]
tls = ["rustls-pemfile", "tokio-rustls"]
tls = ["tokio-rustls"]
[dev-dependencies]
assert_cmd = "2"
reqwest = { version = "0.12", features = ["blocking", "multipart", "rustls-tls"], default-features = false }
reqwest = { version = "0.13", features = ["blocking", "multipart", "rustls"], default-features = false }
assert_fs = "1"
port_check = "0.3"
rstest = "0.26.1"
-2
View File
@@ -4,8 +4,6 @@ RUN if [ "$TARGETPLATFORM" = "linux/amd64" ]; then \
TARGET="x86_64-unknown-linux-musl"; \
elif [ "$TARGETPLATFORM" = "linux/arm64" ]; then \
TARGET="aarch64-unknown-linux-musl"; \
elif [ "$TARGETPLATFORM" = "linux/386" ]; then \
TARGET="i686-unknown-linux-musl"; \
elif [ "$TARGETPLATFORM" = "linux/arm/v7" ]; then \
TARGET="armv7-unknown-linux-musleabihf"; \
fi && \
+13 -1
View File
@@ -67,6 +67,7 @@ Options:
--allow-search Allow search files/folders
--allow-symlink Allow symlink to files/folders outside root directory
--allow-archive Allow download folders as archive file
--allow-hash Allow ?hash query to get file sha256 hash
--enable-cors Enable CORS, sets `Access-Control-Allow-Origin: *`
--render-index Serve index.html when requesting a directory, returns 404 if not found index.html
--render-try-index Serve index.html when requesting a directory, returns directory listing if not found index.html
@@ -302,11 +303,18 @@ The log format can use following variables.
| $http_ | arbitrary request header field. examples: $http_user_agent, $http_referer |
The default log format is `'$remote_addr "$request" $status'`.
The default log format is `'$time_iso8601 $log_level - $remote_addr "$request" $status`.
```
2022-08-06T06:59:31+08:00 INFO - 127.0.0.1 "GET /" 200
```
A json log format is also supported.
```
dufs --log-format '{"time":"$time_local","addr":"$remote_addr","uri":"$request_uri", "method":"$request_method","status":$status}'
{"time":"2022-08-06T06:59:31+08:00","addr":"127.0.0.1","uri":"/", "method":"GET","status":200}
```
Disable http log
```
dufs --log-format=''
@@ -346,6 +354,7 @@ All options can be set using environment variables prefixed with `DUFS_`.
--allow-search DUFS_ALLOW_SEARCH=true
--allow-symlink DUFS_ALLOW_SYMLINK=true
--allow-archive DUFS_ALLOW_ARCHIVE=true
--allow-hash DUFS_ALLOW_HASH=true
--enable-cors DUFS_ENABLE_CORS=true
--render-index DUFS_RENDER_INDEX=true
--render-try-index DUFS_RENDER_TRY_INDEX=true
@@ -383,6 +392,7 @@ allow-delete: true
allow-search: true
allow-symlink: true
allow-archive: true
allow-hash: true
enable-cors: true
render-index: true
render-try-index: true
@@ -412,6 +422,8 @@ Your assets folder must contains a `index.html` file.
- `__INDEX_DATA__`: directory listing data
- `__ASSETS_PREFIX__`: assets url prefix
> A customized 404.html page is also supported.
</details>
## License
+3 -3
View File
@@ -23,7 +23,7 @@
d="M7.646 11.854a.5.5 0 0 0 .708 0l3-3a.5.5 0 0 0-.708-.708L8.5 10.293V1.5a.5.5 0 0 0-1 0v8.793L5.354 8.146a.5.5 0 1 0-.708.708l3 3z" />
</svg>
</a>
<div class="control move-file hidden" title="Move to new path">
<div class="control move-file hidden" title="Move & Rename">
<svg class="icon-move" width="16" height="16" viewBox="0 0 16 16">
<path fill-rule="evenodd"
d="M1.5 1.5A.5.5 0 0 0 1 2v4.8a2.5 2.5 0 0 0 2.5 2.5h9.793l-3.347 3.346a.5.5 0 0 0 .708.708l4.2-4.2a.5.5 0 0 0 0-.708l-4-4a.5.5 0 0 0-.708.708L13.293 8.3H3.5A1.5 1.5 0 0 1 2 6.8V2a.5.5 0 0 0-.5-.5z">
@@ -38,7 +38,7 @@
d="M14 14V4.5L9.5 0H4a2 2 0 0 0-2 2v12a2 2 0 0 0 2 2h8a2 2 0 0 0 2-2zM9.5 3A1.5 1.5 0 0 0 11 4.5h2V14a1 1 0 0 1-1 1H4a1 1 0 0 1-1-1V2a1 1 0 0 1 1-1h5.5v2z" />
</svg>
</div>
<div class="control upload-file hidden" title="Upload files">
<div class="control upload-file hidden" title="Upload files/folders">
<label for="file">
<svg width="16" height="16" viewBox="0 0 16 16">
<path
@@ -47,7 +47,7 @@
d="M7.646 1.146a.5.5 0 0 1 .708 0l3 3a.5.5 0 0 1-.708.708L8.5 2.707V11.5a.5.5 0 0 1-1 0V2.707L5.354 4.854a.5.5 0 1 1-.708-.708l3-3z" />
</svg>
</label>
<input type="file" id="file" title="Upload files" name="file" multiple>
<input type="file" id="file" title="Upload files/folders" name="file" multiple>
</div>
<div class="control new-folder hidden" title="New folder">
<svg width="16" height="16" viewBox="0 0 16 16">
+27 -10
View File
@@ -106,6 +106,15 @@ let $logoutBtn;
*/
let $userName;
// manage unload event to prevent leaving with uploads in progress
const beforeUnloadHandler = (event) => {
if (Uploader.queues.length > 0 || Uploader.runnings > 0) {
event.preventDefault();
event.returnValue = '';
return ''; // for some browsers
}
};
// Produce table when window loads
window.addEventListener("DOMContentLoaded", async () => {
const $indexData = document.getElementById('index-data');
@@ -131,6 +140,8 @@ async function ready() {
$logoutBtn = document.querySelector(".logout-btn");
$userName = document.querySelector(".user-name");
window.addEventListener('beforeunload', beforeUnloadHandler);
addBreadcrumb(DATA.href, DATA.uri_prefix);
if (DATA.kind === "Index") {
@@ -249,12 +260,14 @@ class Uploader {
progress(event) {
const now = Date.now();
const speed = (event.loaded - this.uploaded) / (now - this.lastUptime) * 1000;
const elapsed = now - this.lastUptime;
if (elapsed < 300) return; // throttle update for safari
const speed = (event.loaded - this.uploaded) / elapsed * 1000;
const [speedValue, speedUnit] = formatFileSize(speed);
const speedText = `${speedValue} ${speedUnit}/s`;
const progress = formatPercent(((event.loaded + this.uploadOffset) / this.file.size) * 100);
const duration = formatDuration((event.total - event.loaded) / speed);
this.$uploadStatus.innerHTML = `<span style="width: 80px;">${speedText}</span><span>${progress} ${duration}</span>`;
this.$uploadStatus.innerHTML = `<span style="width: 80px;">${speedText}</span><span style="margin-left: 5px;">${progress} ${duration}</span>`;
this.uploaded = event.loaded;
this.lastUptime = now;
}
@@ -465,7 +478,7 @@ function addPath(file, index) {
}
if (DATA.allow_delete) {
if (DATA.allow_upload) {
actionMove = `<div onclick="movePath(${index})" class="action-btn" id="moveBtn${index}" title="Move to new path">${ICONS.move}</div>`;
actionMove = `<div onclick="movePath(${index})" class="action-btn" id="moveBtn${index}" title="Move & Rename">${ICONS.move}</div>`;
if (!isDir) {
actionEdit = `<a class="action-btn" title="Edit file" target="_blank" href="${url}?edit">${ICONS.edit}</a>`;
}
@@ -534,7 +547,7 @@ async function setupAuth() {
$loginBtn.classList.remove("hidden");
$loginBtn.addEventListener("click", async () => {
try {
await checkAuth();
await checkAuth("login");
} catch { }
location.reload();
});
@@ -782,9 +795,10 @@ async function saveChange() {
}
}
async function checkAuth() {
async function checkAuth(variant) {
if (!DATA.auth) return;
const res = await fetch(baseUrl(), {
const qs = variant ? `?${variant}` : "";
const res = await fetch(baseUrl() + qs, {
method: "CHECKAUTH",
});
await assertResOK(res);
@@ -923,11 +937,14 @@ function formatFileSize(size) {
const sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
if (size == 0) return [0, "B"];
const i = parseInt(Math.floor(Math.log(size) / Math.log(1024)));
let ratio = 1;
if (i >= 3) {
ratio = 100;
const raw = size / Math.pow(1024, i);
let value;
if (i > 0 && raw < 999.95) {
value = Math.round(raw * 10) / 10;
} else {
value = Math.round(raw);
}
return [Math.round(size * ratio / Math.pow(1024, i), 2) / ratio, sizes[i]];
return [value, sizes[i]];
}
function formatDuration(seconds) {
+22 -7
View File
@@ -148,6 +148,14 @@ pub fn build_cli() -> Command {
.action(ArgAction::SetTrue)
.help("Allow download folders as archive file"),
)
.arg(
Arg::new("allow-hash")
.env("DUFS_ALLOW_HASH")
.hide_env(true)
.long("allow-hash")
.action(ArgAction::SetTrue)
.help("Allow ?hash query to get file sha256 hash"),
)
.arg(
Arg::new("enable-cors")
.env("DUFS_ENABLE_CORS")
@@ -281,11 +289,13 @@ pub struct Args {
pub allow_search: bool,
pub allow_symlink: bool,
pub allow_archive: bool,
pub allow_hash: bool,
pub render_index: bool,
pub render_spa: bool,
pub render_try_index: bool,
pub enable_cors: bool,
pub assets: Option<PathBuf>,
pub error_page: Option<PathBuf>,
#[serde(deserialize_with = "deserialize_log_http")]
#[serde(rename = "log-format")]
pub http_logger: HttpLogger,
@@ -375,6 +385,9 @@ impl Args {
if !args.allow_symlink {
args.allow_symlink = allow_all || matches.get_flag("allow-symlink");
}
if !args.allow_hash {
args.allow_hash = allow_all || matches.get_flag("allow-hash");
}
if !args.allow_archive {
args.allow_archive = allow_all || matches.get_flag("allow-archive");
}
@@ -398,6 +411,13 @@ impl Args {
args.assets = Some(Args::sanitize_assets_path(assets_path)?);
}
if let Some(assets_path) = &args.assets {
let p = assets_path.join("404.html");
if p.exists() {
args.error_page = Some(p);
}
}
if let Some(log_format) = matches.get_one::<String>("log-format") {
args.http_logger = log_format.parse()?;
}
@@ -492,21 +512,16 @@ impl BindAddr {
}
}
#[derive(Debug, Clone, Copy, PartialEq, Deserialize)]
#[derive(Debug, Clone, Copy, PartialEq, Deserialize, Default)]
#[serde(rename_all = "lowercase")]
pub enum Compress {
None,
#[default]
Low,
Medium,
High,
}
impl Default for Compress {
fn default() -> Self {
Self::Low
}
}
impl ValueEnum for Compress {
fn value_variants<'a>() -> &'a [Self] {
&[Self::None, Self::Low, Self::Medium, Self::High]
+61 -26
View File
@@ -9,6 +9,7 @@ use indexmap::IndexMap;
use lazy_static::lazy_static;
use md5::Context;
use sha2::{Digest, Sha256};
use sha_crypt::PasswordVerifier;
use std::{
collections::HashMap,
path::{Path, PathBuf},
@@ -30,6 +31,7 @@ lazy_static! {
#[derive(Debug, Clone, PartialEq)]
pub struct AccessControl {
empty: bool,
use_hashed_password: bool,
users: IndexMap<String, (String, AccessPaths)>,
anonymous: Option<AccessPaths>,
@@ -38,6 +40,7 @@ pub struct AccessControl {
impl Default for AccessControl {
fn default() -> Self {
AccessControl {
empty: true,
use_hashed_password: false,
users: IndexMap::new(),
anonymous: Some(AccessPaths::new(AccessPerm::ReadWrite)),
@@ -48,7 +51,7 @@ impl Default for AccessControl {
impl AccessControl {
pub fn new(raw_rules: &[&str]) -> Result<Self> {
if raw_rules.is_empty() {
return Ok(Default::default());
return Ok(Self::default());
}
let new_raw_rules = split_rules(raw_rules);
let mut use_hashed_password = false;
@@ -83,8 +86,14 @@ impl AccessControl {
access_paths
.merge(paths)
.ok_or_else(|| anyhow!("Invalid auth value `{user}:{pass}@{paths}"))?;
if let Some(paths) = annoy_paths {
access_paths.merge(paths);
if let Some(anon_ap) = &anonymous {
let orig_user = access_paths.clone();
access_paths.absorb_anon(
anon_ap,
&orig_user,
AccessPerm::IndexOnly,
AccessPerm::IndexOnly,
);
}
if pass.starts_with("$6$") {
use_hashed_password = true;
@@ -93,13 +102,14 @@ impl AccessControl {
}
Ok(Self {
empty: false,
use_hashed_password,
users,
anonymous,
})
}
pub fn exist(&self) -> bool {
pub fn has_users(&self) -> bool {
!self.users.is_empty()
}
@@ -111,7 +121,7 @@ impl AccessControl {
token: Option<&String>,
guard_options: bool,
) -> (Option<String>, Option<AccessPaths>) {
if self.users.is_empty() {
if self.empty {
return (None, Some(AccessPaths::new(AccessPerm::ReadWrite)));
}
@@ -170,6 +180,10 @@ impl AccessControl {
fn verify_token<'a>(&'a self, token: &str, path: &str) -> Result<(String, &'a AccessPaths)> {
let raw = hex::decode(token)?;
if raw.len() < 72 {
bail!("Invalid token");
}
let sig_bytes = &raw[..64];
let exp_bytes = &raw[64..72];
let user_bytes = &raw[72..];
@@ -212,9 +226,8 @@ impl AccessPaths {
}
pub fn set_perm(&mut self, perm: AccessPerm) {
if self.perm < perm {
if !perm.indexonly() {
self.perm = perm;
self.recursively_purge_children(perm);
}
}
@@ -239,17 +252,6 @@ impl AccessPaths {
Some(target)
}
fn recursively_purge_children(&mut self, perm: AccessPerm) {
self.children.retain(|_, child| {
if child.perm <= perm {
false
} else {
child.recursively_purge_children(perm);
true
}
});
}
fn add(&mut self, path: &str, perm: AccessPerm) {
let path = path.trim_matches('/');
if path.is_empty() {
@@ -261,18 +263,48 @@ impl AccessPaths {
}
fn add_impl(&mut self, parts: &[&str], perm: AccessPerm) {
let parts_len = parts.len();
if parts_len == 0 {
self.set_perm(perm);
return;
}
if self.perm >= perm {
if parts.is_empty() {
self.perm = perm;
return;
}
let child = self.children.entry(parts[0].to_string()).or_default();
child.add_impl(&parts[1..], perm)
}
/// Merge anonymous `AccessPaths` into `self` (a user's paths) with "higher perm wins" semantics.
/// `orig_user` is a snapshot of `self` before any anonymous merging begins, used so that
/// the user's own effective perm is measured against the pre-merge state.
fn absorb_anon(
&mut self,
anon: &AccessPaths,
orig_user: &AccessPaths,
user_inherited: AccessPerm,
anon_inherited: AccessPerm,
) {
let anon_eff = if !anon.perm.indexonly() {
anon.perm
} else {
anon_inherited
};
let orig_user_eff = if !orig_user.perm.indexonly() {
orig_user.perm
} else {
user_inherited
};
let combined = std::cmp::max(anon_eff, orig_user_eff);
if !combined.indexonly() && combined > self.perm {
self.perm = combined;
}
let default_ap = AccessPaths::default();
for (name, anon_child) in &anon.children {
let orig_user_child = orig_user.children.get(name).unwrap_or(&default_ap);
let user_child = self.children.entry(name.clone()).or_default();
user_child.absorb_anon(anon_child, orig_user_child, orig_user_eff, anon_eff);
}
}
pub fn find(&self, path: &str) -> Option<AccessPaths> {
let parts: Vec<&str> = path
.trim_matches('/')
@@ -396,7 +428,10 @@ pub fn check_auth(
}
if auth_pass.starts_with("$6$") {
if let Ok(()) = sha_crypt::sha512_check(pass, auth_pass) {
if sha_crypt::ShaCrypt::SHA512
.verify_password(pass.as_bytes(), auth_pass)
.is_ok()
{
return Some(());
}
} else if pass == auth_pass {
@@ -699,7 +734,7 @@ mod tests {
);
assert_eq!(
paths.find("dir2/dir21/dir211/file"),
Some(AccessPaths::new(AccessPerm::ReadWrite))
Some(AccessPaths::new(AccessPerm::ReadOnly))
);
assert_eq!(
paths.find("dir2/dir22/file"),
+78 -10
View File
@@ -1,8 +1,15 @@
use std::{collections::HashMap, str::FromStr};
use std::{
collections::HashMap,
str::FromStr,
time::{SystemTime, UNIX_EPOCH},
};
use crate::{auth::get_auth_user, server::Request};
use chrono::{Local, SecondsFormat};
pub const DEFAULT_LOG_FORMAT: &str = r#"$remote_addr "$request" $status"#;
use crate::{auth::get_auth_user, server::Request, utils::decode_uri};
pub const DEFAULT_LOG_FORMAT: &str =
r#"$time_iso8601 $log_level - $remote_addr "$request" $status"#;
#[derive(Debug, Clone, PartialEq)]
pub struct HttpLogger {
@@ -28,8 +35,17 @@ impl HttpLogger {
for element in self.elements.iter() {
match element {
LogElement::Variable(name) => match name.as_str() {
"request" => {
data.insert(name.to_string(), format!("{} {}", req.method(), req.uri()));
"request" | "request_method" | "request_uri" => {
let uri = req.uri().to_string();
let decoded_uri = decode_uri(&uri)
.map(|s| sanitize_log_value(&s))
.unwrap_or_else(|| uri.clone());
data.entry("request".to_string())
.or_insert_with(|| format!("{} {decoded_uri}", req.method()));
data.entry("request_method".to_string())
.or_insert_with(|| req.method().to_string());
data.entry("request_uri".to_string())
.or_insert_with(|| decoded_uri);
}
"remote_user" => {
if let Some(user) =
@@ -42,7 +58,7 @@ impl HttpLogger {
},
LogElement::Header(name) => {
if let Some(value) = req.headers().get(name).and_then(|v| v.to_str().ok()) {
data.insert(name.to_string(), value.to_string());
data.insert(name.to_string(), sanitize_log_value(value));
}
}
LogElement::Literal(_) => {}
@@ -50,26 +66,67 @@ impl HttpLogger {
}
data
}
pub fn log(&self, data: &HashMap<String, String>, err: Option<String>) {
if self.elements.is_empty() {
return;
}
let is_error = err.is_some();
let now = Local::now();
let time_local = now.to_rfc3339_opts(SecondsFormat::Secs, false);
let time_iso8601 = now.to_rfc3339_opts(SecondsFormat::Secs, true);
let msec = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| format!("{:.3}", d.as_secs_f64()))
.unwrap_or_default();
let log_level = if is_error { "ERROR" } else { "INFO" };
let mut output = String::new();
for element in self.elements.iter() {
match element {
LogElement::Literal(value) => output.push_str(value.as_str()),
LogElement::Header(name) | LogElement::Variable(name) => {
output.push_str(data.get(name).map(|v| v.as_str()).unwrap_or("-"))
LogElement::Variable(name) => {
let resolved = match name.as_str() {
"time_local" => Some(time_local.as_str()),
"time_iso8601" => Some(time_iso8601.as_str()),
"msec" => Some(msec.as_str()),
"log_level" => Some(log_level),
_ => None,
};
let val = resolved
.or_else(|| data.get(name.as_str()).map(|v| v.as_str()))
.unwrap_or("-");
output.push_str(val);
}
LogElement::Header(name) => {
output.push_str(data.get(name.as_str()).map(|v| v.as_str()).unwrap_or("-"))
}
}
}
match err {
Some(err) => error!("{output} {err}"),
None => info!("{output}"),
Some(err) => emit_http_access(&format!("{output} {err}"), true),
None => emit_http_access(&output, false),
}
}
}
/// Emit via the `log` crate with target `http_access` so the system logger
/// prints the line verbatim (no extra timestamp/level prefix).
fn emit_http_access(msg: &str, is_error: bool) {
let level = if is_error {
log::Level::Error
} else {
log::Level::Info
};
log::logger().log(
&log::Record::builder()
.args(format_args!("{}", msg))
.level(level)
.target("http_access")
.build(),
);
}
impl FromStr for HttpLogger {
type Err = anyhow::Error;
fn from_str(s: &str) -> Result<Self, Self::Err> {
@@ -101,3 +158,14 @@ impl FromStr for HttpLogger {
Ok(Self { elements })
}
}
fn sanitize_log_value(s: &str) -> String {
s.chars()
.flat_map(|c| match c {
'\\' => vec!['\\', '\\'],
'"' => vec!['\\', '"'],
c if c.is_control() => format!("\\x{:02x}", c as u32).chars().collect::<Vec<_>>(),
c => vec![c],
})
.collect()
}
+1 -3
View File
@@ -1,5 +1,4 @@
use anyhow::{Context, Result};
use chrono::{Local, SecondsFormat};
use log::{Level, LevelFilter, Metadata, Record};
use std::fs::{File, OpenOptions};
use std::io::Write;
@@ -17,8 +16,7 @@ impl log::Log for SimpleLogger {
fn log(&self, record: &Record) {
if self.enabled(record.metadata()) {
let timestamp = Local::now().to_rfc3339_opts(SecondsFormat::Secs, true);
let text = format!("{} {} - {}", timestamp, record.level(), record.args());
let text = record.args().to_string();
match &self.file {
Some(file) => {
if let Ok(mut file) = file.lock() {
+8 -5
View File
@@ -55,17 +55,20 @@ pub fn generate_noscript_html(data: &IndexData) -> Result<String> {
fn render_parent() -> String {
let value = "../";
format!("<tr><td><a href=\"{value}\">{value}</a></td><td></td><td></td></tr>")
format!("<tr><td><a href=\"{value}?noscript\">{value}</a></td><td></td><td></td></tr>")
}
fn render_path_item(path: &PathItem) -> String {
let href = encode_uri(&path.name);
let suffix = if path.path_type.is_dir() { "/" } else { "" };
let name = escape_str_pcdata(&path.name);
let mut href = encode_uri(&path.name);
let mut name = escape_str_pcdata(&path.name).to_string();
if path.path_type.is_dir() {
href.push_str("/?noscript");
name.push('/');
};
let mtime = format_mtime(path.mtime).unwrap_or_default();
let size = format_size(path.size, path.path_type);
format!("<tr><td><a href=\"{href}{suffix}\">{name}{suffix}</a></td><td>{mtime}</td><td>{size}</td></tr>")
format!("<tr><td><a href=\"{href}\">{name}</a></td><td>{mtime}</td><td>{size}</td></tr>")
}
fn format_mtime(mtime: u64) -> Option<String> {
+123 -28
View File
@@ -211,7 +211,18 @@ impl Server {
}
if method.as_str() == "CHECKAUTH" {
*res.body_mut() = body_full(user.clone().unwrap_or_default());
match user.clone() {
Some(user) => {
*res.body_mut() = body_full(user);
}
None => {
if has_query_flag(&query_params, "login") || !access_paths.perm().readwrite() {
self.auth_reject(&mut res)?
} else {
*res.body_mut() = body_full("");
}
}
}
return Ok(res);
} else if method.as_str() == "LOGOUT" {
self.auth_reject(&mut res)?;
@@ -234,7 +245,8 @@ impl Server {
self.handle_send_file(&self.args.serve_path, headers, head_only, &mut res)
.await?;
} else {
status_not_found(&mut res);
self.handle_not_found(&query_params, headers, head_only, &mut res)
.await?;
}
return Ok(res);
}
@@ -261,8 +273,9 @@ impl Server {
let render_spa = self.args.render_spa;
let render_try_index = self.args.render_try_index;
if !self.args.allow_symlink && !is_miss && !self.is_root_contained(path).await {
status_not_found(&mut res);
if self.guard_root_contained(path).await {
self.handle_not_found(&query_params, headers, head_only, &mut res)
.await?;
return Ok(res);
}
@@ -272,7 +285,8 @@ impl Server {
if render_try_index {
if allow_archive && has_query_flag(&query_params, "zip") {
if !allow_archive {
status_not_found(&mut res);
self.handle_not_found(&query_params, headers, head_only, &mut res)
.await?;
return Ok(res);
}
self.handle_zip_dir(path, head_only, access_paths, &mut res)
@@ -340,20 +354,26 @@ impl Server {
.await?;
}
} else if is_file {
if has_query_flag(&query_params, "edit") {
if has_query_flag(&query_params, "json") {
self.handle_file_json(path, head_only, &mut res).await?;
} else if has_query_flag(&query_params, "edit") {
self.handle_edit_file(path, DataKind::Edit, head_only, user, &mut res)
.await?;
} else if has_query_flag(&query_params, "view") {
self.handle_edit_file(path, DataKind::View, head_only, user, &mut res)
.await?;
} else if has_query_flag(&query_params, "hash") {
self.handle_hash_file(path, head_only, &mut res).await?;
if self.args.allow_hash {
self.handle_hash_file(path, head_only, &mut res).await?;
} else {
status_forbid(&mut res);
}
} else {
self.handle_send_file(path, headers, head_only, &mut res)
.await?;
}
} else if render_spa {
self.handle_render_spa(path, headers, head_only, &mut res)
self.handle_render_spa(path, &query_params, headers, head_only, &mut res)
.await?;
} else if allow_upload && req_path.ends_with('/') {
self.handle_ls_dir(
@@ -367,7 +387,8 @@ impl Server {
)
.await?;
} else {
status_not_found(&mut res);
self.handle_not_found(&query_params, headers, head_only, &mut res)
.await?;
}
}
Method::OPTIONS => {
@@ -558,7 +579,7 @@ impl Server {
res: &mut Response,
) -> Result<()> {
let mut paths = vec![];
if exist {
if !head_only && exist {
paths = match self.list_dir(path, path, access_paths.clone()).await {
Ok(paths) => paths,
Err(_) => {
@@ -597,14 +618,15 @@ impl Server {
return self
.handle_ls_dir(path, true, query_params, head_only, user, access_paths, res)
.await;
} else {
}
if !head_only {
let path_buf = path.to_path_buf();
let hidden = Arc::new(self.args.hidden.to_vec());
let search = search.clone();
let access_paths = access_paths.clone();
let search_paths = tokio::spawn(collect_dir_entries(
access_paths,
access_paths.clone(),
self.running.clone(),
path_buf,
hidden,
@@ -703,14 +725,41 @@ impl Server {
self.handle_ls_dir(path, true, query_params, head_only, user, access_paths, res)
.await?;
} else {
status_not_found(res)
self.handle_not_found(query_params, headers, head_only, res)
.await?;
}
Ok(())
}
async fn handle_file_json(
&self,
path: &Path,
head_only: bool,
res: &mut Response,
) -> Result<()> {
let pathitem = match self.to_pathitem(path, &self.args.serve_path).await? {
Some(v) => v,
None => {
status_not_found(res);
return Ok(());
}
};
let output = serde_json::to_string_pretty(&pathitem)?;
res.headers_mut()
.typed_insert(ContentType::from(mime_guess::mime::APPLICATION_JSON));
res.headers_mut()
.typed_insert(ContentLength(output.len() as u64));
if head_only {
return Ok(());
}
*res.body_mut() = body_full(output);
Ok(())
}
async fn handle_render_spa(
&self,
path: &Path,
query_params: &HashMap<String, String>,
headers: &HeaderMap<HeaderValue>,
head_only: bool,
res: &mut Response,
@@ -720,11 +769,31 @@ impl Server {
self.handle_send_file(&path, headers, head_only, res)
.await?;
} else {
status_not_found(res)
self.handle_not_found(query_params, headers, head_only, res)
.await?;
}
Ok(())
}
async fn handle_not_found(
&self,
query_params: &HashMap<String, String>,
headers: &HeaderMap<HeaderValue>,
head_only: bool,
res: &mut Response,
) -> Result<()> {
if let Some(error_page) = &self.args.error_page {
if !has_query_flag(query_params, "noscript") {
self.handle_send_file(error_page, headers, head_only, res)
.await?;
*res.status_mut() = StatusCode::NOT_FOUND;
return Ok(());
}
}
status_not_found(res);
Ok(())
}
async fn handle_internal(
&self,
req_path: &str,
@@ -962,7 +1031,7 @@ impl Server {
uri_prefix: self.args.uri_prefix.clone(),
allow_upload: self.args.allow_upload,
allow_delete: self.args.allow_delete,
auth: self.args.auth.exist(),
auth: self.args.auth.has_users(),
user,
editable,
};
@@ -1099,6 +1168,11 @@ impl Server {
ensure_path_parent(&dest).await?;
if self.guard_root_contained(&dest).await {
status_bad_request(res, "Invalid Destination");
return Ok(());
}
fs::copy(path, &dest).await?;
status_no_content(res);
@@ -1115,6 +1189,11 @@ impl Server {
ensure_path_parent(&dest).await?;
if self.guard_root_contained(&dest).await {
status_bad_request(res, "Invalid Destination");
return Ok(());
}
fs::rename(path, &dest).await?;
status_no_content(res);
@@ -1194,10 +1273,11 @@ impl Server {
let output = paths
.into_iter()
.map(|v| {
let displayname = escape_str_pcdata(&v.name);
if v.is_dir() {
format!("{}/\n", v.name)
format!("{}/\n", displayname)
} else {
format!("{}\n", v.name)
format!("{}\n", displayname)
}
})
.collect::<Vec<String>>()
@@ -1226,7 +1306,7 @@ impl Server {
allow_search: self.args.allow_search,
allow_archive: self.args.allow_archive,
dir_exists: exist,
auth: self.args.auth.exist(),
auth: self.args.auth.has_users(),
user,
paths,
};
@@ -1273,6 +1353,21 @@ impl Server {
Ok(())
}
async fn guard_root_contained(&self, path: &Path) -> bool {
if self.args.allow_symlink {
return false;
}
let path = if !fs::try_exists(path).await.unwrap_or_default() {
match path.parent() {
Some(parent) => parent.to_path_buf(),
None => return true,
}
} else {
path.to_path_buf()
};
!self.is_root_contained(path.as_path()).await
}
async fn is_root_contained(&self, path: &Path) -> bool {
fs::canonicalize(path)
.await
@@ -1789,14 +1884,10 @@ async fn get_content_type(path: &Path) -> Result<String> {
let mime = mime_guess::from_path(path).first();
let is_text = content_inspector::inspect(&buffer).is_text();
let content_type = if is_text {
let mut detector = chardetng::EncodingDetector::new();
let mut detector = chardetng::EncodingDetector::new(chardetng::Iso2022JpDetection::Allow);
detector.feed(&buffer, buffer.len() < 1024);
let (enc, confident) = detector.guess_assess(None, true);
let charset = if confident {
format!("; charset={}", enc.name())
} else {
"".into()
};
let enc = detector.guess(None, chardetng::Utf8Detection::Allow);
let charset = format!("; charset={}", enc.name());
match mime {
Some(m) => format!("{m}{charset}"),
None => format!("text/plain{charset}"),
@@ -1840,7 +1931,7 @@ async fn sha256_file(path: &Path) -> Result<String> {
}
let result = hasher.finalize();
Ok(format!("{result:x}"))
Ok(hex::encode(result))
}
fn has_query_flag(query_params: &HashMap<String, String>, name: &str) -> bool {
@@ -1866,10 +1957,14 @@ where
for dir in access_paths.entry_paths(&path) {
let mut it = WalkDir::new(&dir).follow_links(true).into_iter();
it.next();
while let Some(Ok(entry)) = it.next() {
while let Some(entry) = it.next() {
if !running.load(atomic::Ordering::SeqCst) {
break;
}
let entry = match entry {
Ok(v) => v,
Err(_) => continue,
};
let entry_path = entry.path();
let base_name = get_file_name(entry_path);
let is_dir = entry.file_type().is_dir();
+26 -28
View File
@@ -1,7 +1,7 @@
use anyhow::{anyhow, Context, Result};
use chrono::{DateTime, Utc};
#[cfg(feature = "tls")]
use rustls_pki_types::{CertificateDer, PrivateKeyDer};
use rustls_pki_types::{pem::PemObject, CertificateDer, PrivateKeyDer};
use std::{
borrow::Cow,
path::Path,
@@ -62,42 +62,40 @@ pub fn glob(pattern: &str, target: &str) -> bool {
// Load public certificate from file.
#[cfg(feature = "tls")]
pub fn load_certs<T: AsRef<Path>>(filename: T) -> Result<Vec<CertificateDer<'static>>> {
// Open certificate file.
let cert_file = std::fs::File::open(filename.as_ref())
.with_context(|| format!("Failed to access `{}`", filename.as_ref().display()))?;
let mut reader = std::io::BufReader::new(cert_file);
// Load and return certificate.
pub fn load_certs<T: AsRef<Path>>(file_name: T) -> Result<Vec<CertificateDer<'static>>> {
let mut certs = vec![];
for cert in rustls_pemfile::certs(&mut reader) {
let cert = cert.with_context(|| "Failed to load certificate")?;
for cert in CertificateDer::pem_file_iter(file_name.as_ref()).with_context(|| {
format!(
"Failed to load cert file at `{}`",
file_name.as_ref().display()
)
})? {
let cert = cert.with_context(|| {
format!(
"Invalid certificate data in file `{}`",
file_name.as_ref().display()
)
})?;
certs.push(cert)
}
if certs.is_empty() {
anyhow::bail!("No supported certificate in file");
anyhow::bail!(
"No supported certificate in file `{}`",
file_name.as_ref().display()
);
}
Ok(certs)
}
// Load private key from file.
#[cfg(feature = "tls")]
pub fn load_private_key<T: AsRef<Path>>(filename: T) -> Result<PrivateKeyDer<'static>> {
let key_file = std::fs::File::open(filename.as_ref())
.with_context(|| format!("Failed to access `{}`", filename.as_ref().display()))?;
let mut reader = std::io::BufReader::new(key_file);
// Load and return a single private key.
for key in rustls_pemfile::read_all(&mut reader) {
let key = key.with_context(|| "There was a problem with reading private key")?;
match key {
rustls_pemfile::Item::Pkcs1Key(key) => return Ok(PrivateKeyDer::Pkcs1(key)),
rustls_pemfile::Item::Pkcs8Key(key) => return Ok(PrivateKeyDer::Pkcs8(key)),
rustls_pemfile::Item::Sec1Key(key) => return Ok(PrivateKeyDer::Sec1(key)),
_ => {}
}
}
anyhow::bail!("No supported private key in file");
pub fn load_private_key<T: AsRef<Path>>(file_name: T) -> Result<PrivateKeyDer<'static>> {
PrivateKeyDer::from_pem_file(file_name.as_ref()).with_context(|| {
format!(
"Failed to load key file at `{}`",
file_name.as_ref().display()
)
})
}
pub fn parse_range(range: &str, size: u64) -> Option<Vec<(u64, u64)>> {
@@ -123,7 +121,7 @@ pub fn parse_range(range: &str, size: u64) -> Option<Vec<(u64, u64)>> {
result.push((start, size - 1));
} else {
let end = end.parse::<u64>().ok()?;
if end < size {
if end < size && start <= end {
result.push((start, end));
} else {
return None;
+34 -2
View File
@@ -1,7 +1,6 @@
mod fixtures;
mod utils;
use assert_cmd::prelude::*;
use assert_fs::fixture::TempDir;
use fixtures::{port, server, tmpdir, wait_for_port, Error, TestServer, DIR_ASSETS};
use rstest::rstest;
@@ -101,7 +100,7 @@ fn asset_js_with_prefix(
#[rstest]
fn assets_override(tmpdir: TempDir, port: u16) -> Result<(), Error> {
let mut child = Command::cargo_bin("dufs")?
let mut child = Command::new(assert_cmd::cargo::cargo_bin!())
.arg(tmpdir.path())
.arg("-p")
.arg(port.to_string())
@@ -124,3 +123,36 @@ fn assets_override(tmpdir: TempDir, port: u16) -> Result<(), Error> {
child.kill()?;
Ok(())
}
#[rstest]
fn assets_override_not_found_page(tmpdir: TempDir, port: u16) -> Result<(), Error> {
let not_found_html = "<html><body>custom 404 page</body></html>";
std::fs::write(
tmpdir.join(format!("{}404.html", DIR_ASSETS)),
not_found_html,
)?;
let mut child = Command::new(assert_cmd::cargo::cargo_bin!())
.arg(tmpdir.path())
.arg("-p")
.arg(port.to_string())
.arg("--assets")
.arg(tmpdir.join(DIR_ASSETS))
.stdout(Stdio::piped())
.spawn()?;
wait_for_port(port);
let url = format!("http://localhost:{port}/missing-path");
let resp = reqwest::blocking::get(&url)?;
assert_eq!(resp.status(), 404);
assert_eq!(resp.text()?, not_found_html);
let url = format!("http://localhost:{port}/missing-path?noscript");
let resp = reqwest::blocking::get(&url)?;
assert_eq!(resp.status(), 404);
assert_eq!(resp.text()?, "Not Found");
child.kill()?;
Ok(())
}
+44 -3
View File
@@ -125,11 +125,29 @@ fn auth_skip_if_no_auth_user(server: TestServer) -> Result<(), Error> {
Ok(())
}
#[rstest]
fn auth_no_skip_if_anonymous(
#[with(&["--auth", "@/:ro"])] server: TestServer,
) -> Result<(), Error> {
let url = format!("{}index.html", server.url());
let resp = fetch!(b"GET", &url)
.basic_auth("user", Some("pass"))
.send()?;
assert_eq!(resp.status(), 401);
let resp = fetch!(b"GET", &url).send()?;
assert_eq!(resp.status(), 200);
let resp = fetch!(b"DELETE", &url)
.basic_auth("user", Some("pass"))
.send()?;
assert_eq!(resp.status(), 401);
Ok(())
}
#[rstest]
fn auth_check(
#[with(&["--auth", "user:pass@/:rw", "--auth", "user2:pass2@/", "-A"])] server: TestServer,
) -> Result<(), Error> {
let url = format!("{}index.html", server.url());
let url = format!("{}", server.url());
let resp = fetch!(b"CHECKAUTH", &url).send()?;
assert_eq!(resp.status(), 401);
let resp = send_with_digest_auth(fetch!(b"CHECKAUTH", &url), "user", "pass")?;
@@ -143,7 +161,7 @@ fn auth_check(
fn auth_check2(
#[with(&["--auth", "user:pass@/:rw|user2:pass2@/", "-A"])] server: TestServer,
) -> Result<(), Error> {
let url = format!("{}index.html", server.url());
let url = format!("{}", server.url());
let resp = fetch!(b"CHECKAUTH", &url).send()?;
assert_eq!(resp.status(), 401);
let resp = send_with_digest_auth(fetch!(b"CHECKAUTH", &url), "user", "pass")?;
@@ -153,6 +171,18 @@ fn auth_check2(
Ok(())
}
#[rstest]
fn auth_check3(
#[with(&["--auth", "user:pass@/:rw", "--auth", "@/dir1:rw", "-A"])] server: TestServer,
) -> Result<(), Error> {
let url = format!("{}dir1/", server.url());
let resp = fetch!(b"CHECKAUTH", &url).send()?;
assert_eq!(resp.status(), 200);
let resp = fetch!(b"CHECKAUTH", format!("{url}?login")).send()?;
assert_eq!(resp.status(), 401);
Ok(())
}
#[rstest]
fn auth_logout(
#[with(&["--auth", "user:pass@/:rw", "-A"])] server: TestServer,
@@ -336,7 +366,18 @@ fn auth_data(
}
#[rstest]
fn auth_shadow(
fn auth_precedence(
#[with(&["--auth", "user:pass@/dir1:rw,/dir1/test.txt", "-A"])] server: TestServer,
) -> Result<(), Error> {
let url = format!("{}dir1/test.txt", server.url());
let resp = send_with_digest_auth(fetch!(b"PUT", &url).body(b"abc".to_vec()), "user", "pass")?;
assert_eq!(resp.status(), 403);
Ok(())
}
#[rstest]
fn auth_anonymous_no_precedence(
#[with(&["--auth", "user:pass@/:rw", "-a", "@/dir1", "-A"])] server: TestServer,
) -> Result<(), Error> {
let url = format!("{}dir1/test.txt", server.url());
+2 -2
View File
@@ -12,7 +12,7 @@ use std::process::{Command, Stdio};
#[rstest]
#[case(&["-b", "20.205.243.166"])]
fn bind_fails(tmpdir: TempDir, port: u16, #[case] args: &[&str]) -> Result<(), Error> {
Command::cargo_bin("dufs")?
Command::new(assert_cmd::cargo::cargo_bin!())
.arg(tmpdir.path())
.arg("-p")
.arg(port.to_string())
@@ -49,7 +49,7 @@ fn bind_ipv4_ipv6(
#[case(&[] as &[&str])]
#[case(&["--path-prefix", "/prefix"])]
fn validate_printed_urls(tmpdir: TempDir, port: u16, #[case] args: &[&str]) -> Result<(), Error> {
let mut child = Command::cargo_bin("dufs")?
let mut child = Command::new(assert_cmd::cargo::cargo_bin!())
.arg(tmpdir.path())
.arg("-p")
.arg(port.to_string())
+5 -2
View File
@@ -11,7 +11,10 @@ use std::process::Command;
#[test]
/// Show help and exit.
fn help_shows() -> Result<(), Error> {
Command::cargo_bin("dufs")?.arg("-h").assert().success();
Command::new(assert_cmd::cargo::cargo_bin!())
.arg("-h")
.assert()
.success();
Ok(())
}
@@ -21,7 +24,7 @@ fn help_shows() -> Result<(), Error> {
fn print_completions() -> Result<(), Error> {
// let shell_enums = EnumValueParser::<Shell>::new();
for shell in Shell::value_variants() {
Command::cargo_bin("dufs")?
Command::new(assert_cmd::cargo::cargo_bin!())
.arg("--completions")
.arg(shell.to_string())
.assert()
+1 -2
View File
@@ -2,7 +2,6 @@ mod digest_auth_util;
mod fixtures;
mod utils;
use assert_cmd::prelude::*;
use assert_fs::TempDir;
use digest_auth_util::send_with_digest_auth;
use fixtures::{port, tmpdir, wait_for_port, Error};
@@ -13,7 +12,7 @@ use std::process::{Command, Stdio};
#[rstest]
fn use_config_file(tmpdir: TempDir, port: u16) -> Result<(), Error> {
let config_path = get_config_path().display().to_string();
let mut child = Command::cargo_bin("dufs")?
let mut child = Command::new(assert_cmd::cargo::cargo_bin!())
.arg(tmpdir.path())
.arg("-p")
.arg(port.to_string())
+1 -3
View File
@@ -1,4 +1,3 @@
use assert_cmd::prelude::*;
use assert_fs::fixture::TempDir;
use assert_fs::prelude::*;
use port_check::free_local_port;
@@ -129,8 +128,7 @@ where
{
let port = port();
let tmpdir = tmpdir();
let child = Command::cargo_bin("dufs")
.expect("Couldn't find test binary")
let child = Command::new(assert_cmd::cargo::cargo_bin!())
.arg(tmpdir.path())
.arg("-p")
.arg(port.to_string())
+24 -1
View File
@@ -185,6 +185,22 @@ fn get_file(server: TestServer) -> Result<(), Error> {
Ok(())
}
#[rstest]
fn get_file_json(server: TestServer) -> Result<(), Error> {
let resp = reqwest::blocking::get(format!("{}index.html?json", server.url()))?;
assert_eq!(resp.status(), 200);
assert_eq!(
resp.headers().get("content-type").unwrap(),
"application/json"
);
let json: Value = serde_json::from_str(&resp.text()?).unwrap();
assert_eq!(json["name"], "index.html");
assert_eq!(json["path_type"], "File");
assert!(json["size"].as_u64().is_some());
assert!(json["mtime"].as_u64().is_some());
Ok(())
}
#[rstest]
fn head_file(server: TestServer) -> Result<(), Error> {
let resp = fetch!(b"HEAD", format!("{}index.html", server.url())).send()?;
@@ -203,7 +219,7 @@ fn head_file(server: TestServer) -> Result<(), Error> {
}
#[rstest]
fn hash_file(server: TestServer) -> Result<(), Error> {
fn hash_file(#[with(&["--allow-hash"])] server: TestServer) -> Result<(), Error> {
let resp = reqwest::blocking::get(format!("{}index.html?hash", server.url()))?;
assert_eq!(
resp.headers().get("content-type").unwrap(),
@@ -217,6 +233,13 @@ fn hash_file(server: TestServer) -> Result<(), Error> {
Ok(())
}
#[rstest]
fn no_hash_file(server: TestServer) -> Result<(), Error> {
let resp = reqwest::blocking::get(format!("{}index.html?hash", server.url()))?;
assert_eq!(resp.status(), 403);
Ok(())
}
#[rstest]
fn get_file_404(server: TestServer) -> Result<(), Error> {
let resp = reqwest::blocking::get(format!("{}404", server.url()))?;
+2 -3
View File
@@ -5,7 +5,6 @@ mod utils;
use digest_auth_util::send_with_digest_auth;
use fixtures::{port, tmpdir, wait_for_port, Error};
use assert_cmd::prelude::*;
use assert_fs::fixture::TempDir;
use rstest::rstest;
use std::io::Read;
@@ -20,7 +19,7 @@ fn log_remote_user(
#[case] args: &[&str],
#[case] is_basic: bool,
) -> Result<(), Error> {
let mut child = Command::cargo_bin("dufs")?
let mut child = Command::new(assert_cmd::cargo::cargo_bin!())
.arg(tmpdir.path())
.arg("-p")
.arg(port.to_string())
@@ -55,7 +54,7 @@ fn log_remote_user(
#[rstest]
#[case(&["--log-format", ""])]
fn no_log(tmpdir: TempDir, port: u16, #[case] args: &[&str]) -> Result<(), Error> {
let mut child = Command::cargo_bin("dufs")?
let mut child = Command::new(assert_cmd::cargo::cargo_bin!())
.arg(tmpdir.path())
.arg("-p")
.arg(port.to_string())
+22
View File
@@ -104,3 +104,25 @@ fn get_file_multipart_range_invalid(server: TestServer) -> Result<(), Error> {
assert_eq!(resp.headers().get("content-length").unwrap(), "0");
Ok(())
}
#[rstest]
fn get_file_range_reversed(server: TestServer) -> Result<(), Error> {
let resp = fetch!(b"GET", format!("{}index.html", server.url()))
.header("range", HeaderValue::from_static("bytes=10-1"))
.send()?;
assert_eq!(resp.status(), 416);
assert_eq!(resp.headers().get("content-range").unwrap(), "bytes */18");
assert_eq!(resp.headers().get("accept-ranges").unwrap(), "bytes");
Ok(())
}
#[rstest]
fn get_file_multipart_range_reversed(server: TestServer) -> Result<(), Error> {
let resp = fetch!(b"GET", format!("{}index.html", server.url()))
.header("range", HeaderValue::from_static("bytes=10-1,20-2"))
.send()?;
assert_eq!(resp.status(), 416);
assert_eq!(resp.headers().get("content-range").unwrap(), "bytes */18");
assert_eq!(resp.headers().get("accept-ranges").unwrap(), "bytes");
Ok(())
}
+2 -3
View File
@@ -3,7 +3,6 @@
mod fixtures;
mod utils;
use assert_cmd::prelude::*;
use assert_fs::fixture::TempDir;
use fixtures::{port, tmpdir, wait_for_port, Error};
use rstest::rstest;
@@ -12,7 +11,7 @@ use std::process::{Command, Stdio};
#[rstest]
#[case("index.html")]
fn single_file(tmpdir: TempDir, port: u16, #[case] file: &str) -> Result<(), Error> {
let mut child = Command::cargo_bin("dufs")?
let mut child = Command::new(assert_cmd::cargo::cargo_bin!())
.arg(tmpdir.path().join(file))
.arg("-p")
.arg(port.to_string())
@@ -35,7 +34,7 @@ fn single_file(tmpdir: TempDir, port: u16, #[case] file: &str) -> Result<(), Err
#[rstest]
#[case("index.html")]
fn path_prefix_single_file(tmpdir: TempDir, port: u16, #[case] file: &str) -> Result<(), Error> {
let mut child = Command::cargo_bin("dufs")?
let mut child = Command::new(assert_cmd::cargo::cargo_bin!())
.arg(tmpdir.path().join(file))
.arg("-p")
.arg(port.to_string())
+5 -6
View File
@@ -1,7 +1,6 @@
mod fixtures;
mod utils;
use assert_cmd::Command;
use fixtures::{server, Error, TestServer};
use predicates::str::contains;
use reqwest::blocking::ClientBuilder;
@@ -25,7 +24,7 @@ use crate::fixtures::port;
]))]
fn tls_works(#[case] server: TestServer) -> Result<(), Error> {
let client = ClientBuilder::new()
.danger_accept_invalid_certs(true)
.tls_danger_accept_invalid_certs(true)
.build()?;
let resp = client.get(server.url()).send()?.error_for_status()?;
assert_resp_paths!(resp);
@@ -36,7 +35,7 @@ fn tls_works(#[case] server: TestServer) -> Result<(), Error> {
#[rstest]
fn wrong_path_cert() -> Result<(), Error> {
let port = port().to_string();
Command::cargo_bin("dufs")?
assert_cmd::cargo::cargo_bin_cmd!()
.args([
"--tls-cert",
"wrong",
@@ -47,7 +46,7 @@ fn wrong_path_cert() -> Result<(), Error> {
])
.assert()
.failure()
.stderr(contains("Failed to access `wrong`"));
.stderr(contains("Failed to load cert file at `wrong`"));
Ok(())
}
@@ -56,7 +55,7 @@ fn wrong_path_cert() -> Result<(), Error> {
#[rstest]
fn wrong_path_key() -> Result<(), Error> {
let port = port().to_string();
Command::cargo_bin("dufs")?
assert_cmd::cargo::cargo_bin_cmd!()
.args([
"--tls-cert",
"tests/data/cert.pem",
@@ -67,7 +66,7 @@ fn wrong_path_key() -> Result<(), Error> {
])
.assert()
.failure()
.stderr(contains("Failed to access `wrong`"));
.stderr(contains("Failed to load key file at `wrong`"));
Ok(())
}