mirror of
https://github.com/hacdias/webdav.git
synced 2026-09-22 03:20:41 +08:00
Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3ddd9182f9 | ||
|
|
71fce1a29e | ||
|
|
db385c76b2 | ||
|
|
f9c771fdad | ||
|
|
7cc3f8b4ae | ||
|
|
36063ce391 | ||
|
|
6c3258a469 | ||
|
|
3ef6dd5ba5 | ||
|
|
d57f57f3a0 | ||
|
|
c3cfaf18f5 | ||
|
|
0128eed63d | ||
|
|
f051809a5f | ||
|
|
f13c884b75 | ||
|
|
cef2e3b673 | ||
|
|
4fe4703e02 | ||
|
|
882c2200eb | ||
|
|
4f4045dbca | ||
|
|
20606cd795 | ||
|
|
c9ca42d89a | ||
|
|
8217bc0816 | ||
|
|
98f8f93ebb | ||
|
|
66049d9c08 | ||
|
|
0406449b05 | ||
|
|
d7745cff34 | ||
|
|
d8558a77ff | ||
|
|
ab5cf175ad | ||
|
|
f225b0418f | ||
|
|
d9600ee82d | ||
|
|
6359115c2d | ||
|
|
8574b461a9 | ||
|
|
1196ad506d | ||
|
|
4ac9a1041c | ||
|
|
27aad9d403 | ||
|
|
e06f26b095 | ||
|
|
04070a8ae8 | ||
|
|
bd0667aac1 | ||
|
|
b620cd5c88 | ||
|
|
c4c58fe420 | ||
|
|
0ff71ca067 | ||
|
|
efdaa784b9 | ||
|
|
7662d629e3 | ||
|
|
010ca576fb | ||
|
|
7b8aa1c422 | ||
|
|
2f98af7d1e | ||
|
|
50e1828b60 | ||
|
|
e78d59e374 | ||
|
|
de0a102ed8 | ||
|
|
bdfa98d00d | ||
|
|
f0e7e23ea8 | ||
|
|
065991a195 | ||
|
|
bb85514c8f | ||
|
|
c0af549a1f | ||
|
|
685d89162a | ||
|
|
a5496c9516 | ||
|
|
24abd52e23 | ||
|
|
1af4c723f4 | ||
|
|
2406836223 | ||
|
|
7ca822bcaf | ||
|
|
a98d0c2616 | ||
|
|
98e92d0c13 | ||
|
|
53416e57da | ||
|
|
ff6637f396 | ||
|
|
15fbcd391b | ||
|
|
70b3630d08 | ||
|
|
aa014b092b | ||
|
|
b4553710eb | ||
|
|
e07e55d97a | ||
|
|
cfee0f9f0b | ||
|
|
79eb02aba4 | ||
|
|
7bbe36e4c1 | ||
|
|
520b7df04d | ||
|
|
8f3a3298a8 | ||
|
|
1753aa2945 | ||
|
|
4645f6f46f | ||
|
|
e998e2a838 | ||
|
|
3b3dedc4eb | ||
|
|
8706802dac | ||
|
|
5676a1c382 | ||
|
|
c938367dc0 | ||
|
|
758410ba64 | ||
|
|
1bbf52e475 | ||
|
|
2c2a325215 | ||
|
|
f7e006b449 | ||
|
|
49f61eab79 | ||
|
|
5d1a68c4f2 | ||
|
|
04cee682fb | ||
|
|
19d128cfbd | ||
|
|
118a0dda88 | ||
|
|
aad8e563a7 | ||
|
|
8446f9bdae | ||
|
|
5226853fca | ||
|
|
e350dc989a | ||
|
|
65de8e8578 | ||
|
|
f0b5a39d80 | ||
|
|
dbd708a76e | ||
|
|
f61b7cab3b | ||
|
|
3cfaa0da3e | ||
|
|
f7b78cd834 | ||
|
|
4b4e555ed5 | ||
|
|
6aeb3f8a30 | ||
|
|
59c5f1343f | ||
|
|
617496c019 | ||
|
|
3790d7de08 | ||
|
|
eaf42b03e9 | ||
|
|
dce6010b61 | ||
|
|
88863d7242 | ||
|
|
2c96db92aa | ||
|
|
79bc17afab | ||
|
|
51b101d3d8 | ||
|
|
ca7f3374d5 | ||
|
|
64bbdc7b15 | ||
|
|
d418bd2661 | ||
|
|
d500716f29 | ||
|
|
8c49af0b68 | ||
|
|
a5777e18ee | ||
|
|
49a6e935c3 | ||
|
|
a698e31cb4 | ||
|
|
74b514c877 | ||
|
|
ca0bdb1cfa | ||
|
|
a056e1ba18 | ||
|
|
189af88bc8 | ||
|
|
4e87e6a613 |
@@ -12,8 +12,10 @@ jobs:
|
||||
build:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version: "1.23.x"
|
||||
go-version: "1.26.x"
|
||||
- run: go build .
|
||||
env:
|
||||
CGO_ENABLED: '0'
|
||||
|
||||
@@ -18,22 +18,22 @@ jobs:
|
||||
id-token: write
|
||||
steps:
|
||||
- name: Check out the repo
|
||||
uses: actions/checkout@v4
|
||||
uses: actions/checkout@v7
|
||||
|
||||
- name: Set up QEMU
|
||||
uses: docker/setup-qemu-action@v3
|
||||
uses: docker/setup-qemu-action@v4
|
||||
|
||||
- name: Set up Docker Buildx
|
||||
uses: docker/setup-buildx-action@v3
|
||||
uses: docker/setup-buildx-action@v4
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
|
||||
- name: Login to GitHub Container Registry
|
||||
uses: docker/login-action@v3
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
registry: ghcr.io
|
||||
username: ${{ github.actor }}
|
||||
@@ -41,7 +41,7 @@ jobs:
|
||||
|
||||
- name: Extract metadata (tags, labels) for Docker
|
||||
id: meta
|
||||
uses: docker/metadata-action@v5
|
||||
uses: docker/metadata-action@v6
|
||||
with:
|
||||
images: |
|
||||
hacdias/webdav
|
||||
@@ -55,7 +55,7 @@ jobs:
|
||||
|
||||
- name: Build and push Docker image
|
||||
id: push
|
||||
uses: docker/build-push-action@v6
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
file: ./Dockerfile
|
||||
|
||||
@@ -12,10 +12,10 @@ jobs:
|
||||
lint:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version: "1.23.x"
|
||||
- uses: golangci/golangci-lint-action@v6
|
||||
go-version: "1.26.x"
|
||||
- uses: golangci/golangci-lint-action@v9
|
||||
with:
|
||||
version: "v1.60"
|
||||
version: "latest"
|
||||
|
||||
@@ -12,11 +12,13 @@ jobs:
|
||||
goreleaser:
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/checkout@v7
|
||||
with:
|
||||
fetch-depth: 0
|
||||
- uses: actions/setup-go@v5
|
||||
- uses: goreleaser/goreleaser-action@v6
|
||||
- uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version: "1.26.x"
|
||||
- uses: goreleaser/goreleaser-action@v7
|
||||
with:
|
||||
distribution: goreleaser
|
||||
version: '~> v2'
|
||||
|
||||
@@ -13,9 +13,9 @@ jobs:
|
||||
name: test
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
- uses: actions/setup-go@v5
|
||||
- uses: actions/checkout@v7
|
||||
- uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version: "1.23.x"
|
||||
go-version: "1.26.x"
|
||||
- name: Run test with coverage
|
||||
run: go test -race -coverprofile=coverage.txt -covermode=atomic ./...
|
||||
|
||||
+1
-1
@@ -1,2 +1,2 @@
|
||||
dist/
|
||||
webdav
|
||||
webdav
|
||||
|
||||
+10
-4
@@ -8,10 +8,12 @@ before:
|
||||
builds:
|
||||
- main: main.go
|
||||
binary: webdav
|
||||
env:
|
||||
- CGO_ENABLED=0
|
||||
flags:
|
||||
- '-trimpath'
|
||||
ldflags:
|
||||
- '-X github.com/hacdias/webdav/v5/cmd.version={{.Version}}'
|
||||
- '-s -w -X github.com/hacdias/webdav/v5/cmd.version={{.Version}}'
|
||||
goos:
|
||||
- darwin
|
||||
- linux
|
||||
@@ -36,16 +38,20 @@ builds:
|
||||
- goos: openbsd
|
||||
goarch: arm
|
||||
goarm: 6
|
||||
# Broken as of Go 1.24, deprecated as of Go 1.26
|
||||
- goos: freebsd
|
||||
goarch: arm
|
||||
goarm: 6
|
||||
- goos: windows
|
||||
goarch: arm
|
||||
|
||||
archives:
|
||||
- name_template: "{{.Os}}-{{.Arch}}{{if .Arm}}v{{.Arm}}{{end}}-{{ .ProjectName }}"
|
||||
format: tar.gz
|
||||
formats:
|
||||
- tar.gz
|
||||
format_overrides:
|
||||
- goos: windows
|
||||
format: zip
|
||||
formats:
|
||||
- zip
|
||||
|
||||
release:
|
||||
github:
|
||||
|
||||
+2
-5
@@ -1,9 +1,7 @@
|
||||
FROM golang:1.23-alpine3.20 AS build
|
||||
FROM golang:1.26-alpine3.22 AS build
|
||||
|
||||
ARG VERSION="untracked"
|
||||
|
||||
RUN apk --update add ca-certificates
|
||||
|
||||
WORKDIR /webdav/
|
||||
|
||||
COPY ./go.mod ./
|
||||
@@ -11,11 +9,10 @@ COPY ./go.sum ./
|
||||
RUN go mod download
|
||||
|
||||
COPY . /webdav/
|
||||
RUN go build -o main -ldflags="-X 'github.com/hacdias/webdav/v5/cmd.version=$VERSION'" .
|
||||
RUN go build -o main -trimpath -ldflags="-s -w -X 'github.com/hacdias/webdav/v5/cmd.version=$VERSION'" .
|
||||
|
||||
FROM scratch
|
||||
|
||||
COPY --from=build /etc/ssl/certs/ca-certificates.crt /etc/ssl/certs/ca-certificates.crt
|
||||
COPY --from=build /webdav/main /bin/webdav
|
||||
|
||||
EXPOSE 6065
|
||||
|
||||
@@ -14,6 +14,14 @@ For a manual install, please refer to the [releases](https://github.com/hacdias/
|
||||
go install github.com/hacdias/webdav/v5@latest
|
||||
```
|
||||
|
||||
### Homebrew
|
||||
|
||||
If you have Homebrew available on your system, you can also install `webdav` using it:
|
||||
|
||||
```
|
||||
brew install webdav
|
||||
```
|
||||
|
||||
### Docker
|
||||
|
||||
Docker images are provided on both [GitHub's registry](https://github.com/hacdias/webdav/pkgs/container/webdav) and [Docker Hub](https://hub.docker.com/r/hacdias/webdav). You can pull the images using one of the following two commands. Note that this commands pull the latest released version. You can use specific tags to pin specific versions, or use `main` for the development branch.
|
||||
@@ -30,28 +38,45 @@ docker pull hacdias/webdav:latest
|
||||
|
||||
For usage information regarding the CLI, run `webdav --help`.
|
||||
|
||||
### Docker
|
||||
### Container
|
||||
|
||||
To use with Docker, you need to provide a configuration file and mount the data directories. For example, let's take the following configuration file that simply sets the port to `6060` and the directory to `/data`.
|
||||
To run the container, you can refer to the `compose.yml` file which provides a minimal setup. Additionally, you also need to create a configuration file, as [explained below](#configuration).
|
||||
|
||||
```yaml
|
||||
port: 6060
|
||||
directory: /data
|
||||
```
|
||||
|
||||
You can now run with the following Docker command, where you mount the configuration file inside the container, and the data directory too, as well as forwarding the port 6060. You will need to change this to match your own configuration.
|
||||
The equivalent Docker command to the aforementioned compose file would be as follows:
|
||||
|
||||
```bash
|
||||
docker run \
|
||||
-p 6060:6060 \
|
||||
-v $(pwd)/config.yml:/config.yml:ro \
|
||||
-v $(pwd)/data:/data \
|
||||
-p 6065:6065 \
|
||||
-v ./config.yml:/config.yml:ro \
|
||||
-v ./data:/data \
|
||||
ghcr.io/hacdias/webdav -c /config.yml
|
||||
```
|
||||
|
||||
If you are using [fail2ban](#fail2ban-setup), it would be helpful to add the parameters listed below. They will assist in analyzing
|
||||
the log.
|
||||
|
||||
```bash
|
||||
--log-driver journald \
|
||||
--name webdav \
|
||||
```
|
||||
|
||||
### Partial updates
|
||||
|
||||
This server supports partial file updates compatible with SabreDAV's `PATCH` extension. This is not an official WebDAV specification. Requests must use the `application/x-sabredav-partialupdate` content type, include `Content-Length`, and provide the target range in `X-Update-Range`.
|
||||
|
||||
Supported `X-Update-Range` values are:
|
||||
|
||||
- `bytes=start-end`
|
||||
- `bytes=start-`
|
||||
- `bytes=-N`
|
||||
- `append`
|
||||
|
||||
For clients that use it, the server also supports partial `PUT` requests with `Content-Range`, for example `Content-Range: bytes 6-8/*`. This is an extra compatibility path and should be treated as a client/server agreement.
|
||||
|
||||
## Configuration
|
||||
|
||||
The configuration can be provided as a YAML, JSON or TOML file. Below is an example of a YAML configuration file with all the options available, as well as what they mean.
|
||||
The configuration can be provided as a YAML, JSON or TOML file. Below is an example of a YAML configuration file with
|
||||
all the options available, as well as what they mean.
|
||||
|
||||
```yaml
|
||||
address: 0.0.0.0
|
||||
@@ -71,19 +96,38 @@ debug: false
|
||||
# Disable sniffing the files to detect their content type. Default is 'false'.
|
||||
noSniff: false
|
||||
|
||||
# Whether the server runs behind a trusted proxy or not. When this is true,
|
||||
# the header X-Forwarded-For will be used for logging the remote addresses
|
||||
# of logging attempts (if available).
|
||||
behindProxy: false
|
||||
|
||||
# The directory that will be able to be accessed by the users when connecting.
|
||||
# This directory will be used by users unless they have their own 'directory' defined.
|
||||
# Default is '.' (current directory).
|
||||
directory: .
|
||||
# By default it points to the working directory. In the case of the compose file above,
|
||||
# that is /data.
|
||||
directory: /data
|
||||
|
||||
# The default permissions for users. This is a case insensitive option. Possible
|
||||
# permissions: C (Create), R (Read), U (Update), D (Delete). You can combine multiple
|
||||
# permissions. For example, to allow to read and create, set "RC". Default is "R".
|
||||
permissions: R
|
||||
|
||||
# The default permissions rules for users. Default is none.
|
||||
# The default permissions rules for users. Default is none. Rules are applied
|
||||
# from last to first, that is, the first rule that matches the request, starting
|
||||
# from the end, will be applied to the request. Rule paths are always relative to
|
||||
# the user's directory.
|
||||
rules: []
|
||||
|
||||
# The behavior of redefining the rules for users. It can be:
|
||||
# - overwrite: when a user has rules defined, these will overwrite any global
|
||||
# rules already defined. That is, the global rules are not applicable to the
|
||||
# user.
|
||||
# - append: when a user has rules defined, these will be appended to the global
|
||||
# rules already defined. That is, for this user, their own specific rules will
|
||||
# be checked first, and then the global rules.
|
||||
# Default is 'overwrite'.
|
||||
rulesBehavior: overwrite
|
||||
|
||||
# Logging configuration
|
||||
log:
|
||||
# Logging format ('console', 'json'). Default is 'console'.
|
||||
@@ -92,57 +136,89 @@ log:
|
||||
colors: true
|
||||
# Logging outputs. You can have more than one output. Default is only 'stderr'.
|
||||
outputs:
|
||||
- stderr
|
||||
- stderr
|
||||
|
||||
# CORS configuration
|
||||
cors:
|
||||
# Whether or not CORS configuration should be applied. Default is 'false'.
|
||||
enabled: true
|
||||
credentials: true
|
||||
allowed_headers:
|
||||
- Depth
|
||||
# The following are the default CORS settings when it is enabled.
|
||||
allowed_hosts:
|
||||
- http://localhost:8080
|
||||
allowed_methods:
|
||||
- GET
|
||||
exposed_headers:
|
||||
- Content-Length
|
||||
- '*'
|
||||
allowed_headers:
|
||||
- Authorization
|
||||
- Content-Type
|
||||
- Content-Range
|
||||
- Depth
|
||||
- Destination
|
||||
- If
|
||||
- Lock-Token
|
||||
- Overwrite
|
||||
- TimeOut
|
||||
- Translate
|
||||
- X-Update-Range
|
||||
allowed_methods:
|
||||
- COPY
|
||||
- DELETE
|
||||
- GET
|
||||
- HEAD
|
||||
- LOCK
|
||||
- UNLOCK
|
||||
- MKCOL
|
||||
- MOVE
|
||||
- OPTIONS
|
||||
- PATCH
|
||||
- POST
|
||||
- PROPFIND
|
||||
- PROPPATCH
|
||||
- PUT
|
||||
exposed_headers: []
|
||||
|
||||
# The list of users. If the list is empty, then there will be no authentication.
|
||||
# Otherwise, basic authentication will automatically be configured.
|
||||
#
|
||||
# If you're delegating the authentication to a different service, you can proxy
|
||||
# the username using basic authentication, and then disable webdav's password
|
||||
# check using the option:
|
||||
#
|
||||
# noPassword: true
|
||||
# You define here the list of users.
|
||||
# Basic authentication is automatically be configured when users are detected
|
||||
# below, else there will be no authentication.
|
||||
# Customize to your needs and don't forget to comment out the users you don't need.
|
||||
users:
|
||||
# Example 'admin' user with plaintext password.
|
||||
- username: admin
|
||||
password: admin
|
||||
|
||||
# Example 'john' user with bcrypt encrypted password, with custom directory.
|
||||
# Tip: you can generate a bcrypt-encrypted password by using the 'webdav bcrypt'
|
||||
# command lint utility, or htpasswd on Linux.
|
||||
- username: john
|
||||
password: "{bcrypt}$2y$10$zEP6oofmXFeHaeMfBNLnP.DO8m.H.Mwhd24/TOX2MWLxAExXi4qgi"
|
||||
directory: /another/path
|
||||
directory: /data/john
|
||||
# Example user whose details will be picked up from the environment.
|
||||
- username: "{env}ENV_USERNAME"
|
||||
password: "{env}ENV_PASSWORD"
|
||||
# Example user with advanced control over his permissions
|
||||
- username: basic
|
||||
password: basic
|
||||
# Override default permissions.
|
||||
permissions: CRUD
|
||||
permissions: CRUD # Override default permissions.
|
||||
rules:
|
||||
# With this rule, the user CANNOT access /some/files.
|
||||
# With this rule, the user CANNOT access {user directory}/some/files.
|
||||
- path: /some/file
|
||||
permissions: none
|
||||
# With this rule, the user CAN create, read, update and delete within /public/access.
|
||||
# With this rule, the user CAN create, read, update and delete within
|
||||
# {user directory}/public/access.
|
||||
- path: /public/access/
|
||||
permissions: CRUD
|
||||
# With this rule, the user CAN read and update all files ending with .js. It uses
|
||||
# a regular expression.
|
||||
# With this rule, the user CAN read and update all files ending with .js.
|
||||
# It uses a regular expression.
|
||||
- regex: "^.+.js$"
|
||||
permissions: RU
|
||||
# Example user for android SeedVault backuping
|
||||
- username: android
|
||||
password: "{bcrypt}$2y$10$zEP6oofmXFeHaeMfBNLnP.DO8m.H.Mwhd24/TOX2MWLxAExXi4qgi"
|
||||
directory: /data/android
|
||||
permissions: CRUD
|
||||
|
||||
# If you're delegating the authentication to a different service, you can proxy
|
||||
# the username using basic authentication, and then disable webdav's password
|
||||
# check using the option:
|
||||
# noPassword: true
|
||||
```
|
||||
|
||||
### CORS
|
||||
@@ -156,7 +232,9 @@ The `allowed_*` properties are optional, the default value for each of them will
|
||||
|
||||
### Reverse Proxy Service
|
||||
|
||||
When using a reverse proxy implementation, like Caddy, Nginx, or Apache, note that you need to forward the correct headers in order to avoid 502 errors. Here's a Nginx configuration example:
|
||||
When using a reverse proxy implementation, like Caddy, Nginx, or Apache, note that you need to forward the correct headers in order to avoid 502 errors.
|
||||
|
||||
#### Nginx Configuration Example
|
||||
|
||||
```nginx
|
||||
location / {
|
||||
@@ -166,6 +244,33 @@ location / {
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header Host $host;
|
||||
proxy_redirect off;
|
||||
|
||||
# Ensure COPY and MOVE commands work. Change https://example.com to the
|
||||
# correct address where the WebDAV server will be deployed at.
|
||||
set $dest $http_destination;
|
||||
if ($http_destination ~ "^https://example.com(?<path>(.+))") {
|
||||
set $dest /$path;
|
||||
}
|
||||
proxy_set_header Destination $dest;
|
||||
}
|
||||
```
|
||||
|
||||
#### Caddy Configuration Example
|
||||
|
||||
```Caddyfile
|
||||
example.com {
|
||||
tls internal # for local development
|
||||
# tls [email protected] # so that Caddy gets certs for you via Letsencrypt
|
||||
|
||||
# Rewrites destination to remove host and include only the path e.g. /test.txt
|
||||
@hasDest header_regexp dest ^https?://[^/]+(.*)$
|
||||
header @hasDest Destination {re.dest.1}
|
||||
|
||||
# if running on the same network in docker you can just point to the service name e.g. webdav:6065
|
||||
reverse_proxy 127.0.0.1:6065 {
|
||||
header_up X-Real-IP {remote_host}
|
||||
header_up REMOTE-HOST {remote_host}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
@@ -190,6 +295,64 @@ Restart=on-failure
|
||||
WantedBy=multi-user.target
|
||||
```
|
||||
|
||||
### Fail2Ban Setup
|
||||
|
||||
To add security against brute-force attacks in your WebDAV server, you can configure Fail2Ban to ban IP addresses after a set number of failed login attempts.
|
||||
|
||||
#### Filter Configuration
|
||||
|
||||
Create a new filter rule under `filter.d/webdav.conf`:
|
||||
|
||||
```ini
|
||||
[INCLUDES]
|
||||
before = common.conf
|
||||
|
||||
[Definition]
|
||||
# Failregex to match "invalid password" and extract remote_address only
|
||||
failregex = ^.*invalid password\s*\{.*"remote_address":\s*"<HOST>:\d+"\s*\}
|
||||
^.*invalid username\s*\{.*"remote_address":\s*"<HOST>:\d+"\s*\}
|
||||
|
||||
ignoreregex =
|
||||
```
|
||||
|
||||
This configuration will capture invalid login attempts and extract the IP address to ban.
|
||||
|
||||
#### Jail Configuration
|
||||
|
||||
In `jail.d/webdav.conf`, define the jail that monitors your WebDAV log for failed login attempts:
|
||||
|
||||
```ini
|
||||
[webdav]
|
||||
|
||||
enabled = true
|
||||
port = [your_port]
|
||||
filter = webdav
|
||||
logpath = [your_log_path]
|
||||
banaction = iptables-allports
|
||||
ignoreself = false
|
||||
```
|
||||
|
||||
- Replace `[your_port]` with the port your WebDAV server is running on.
|
||||
- Replace `[your_log_path]` with the path to your WebDAV log file.
|
||||
|
||||
If you use it with Docker and `--log-driver journald`, replace `logpath` with `journalmatch = CONTAINER_NAME=[your_container_name]`
|
||||
|
||||
#### Final Steps
|
||||
|
||||
1. Restart Fail2Ban to apply these configurations:
|
||||
|
||||
```bash
|
||||
sudo systemctl restart fail2ban
|
||||
```
|
||||
|
||||
2. Verify that Fail2Ban is running and monitoring your WebDAV logs:
|
||||
|
||||
```bash
|
||||
sudo fail2ban-client status webdav
|
||||
```
|
||||
|
||||
With this setup, Fail2Ban will automatically block IP addresses that exceed the allowed number of failed login attempts.
|
||||
|
||||
## Contributing
|
||||
|
||||
Feel free to open an issue or a pull request.
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/spf13/cobra"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
func init() {
|
||||
flags := bcryptCmd.Flags()
|
||||
flags.IntP("cost", "c", bcrypt.DefaultCost, "cost used to generate password, higher cost leads to slower verification times")
|
||||
|
||||
rootCmd.AddCommand(bcryptCmd)
|
||||
}
|
||||
|
||||
var bcryptCmd = &cobra.Command{
|
||||
Use: "bcrypt",
|
||||
Short: "Generate a bcrypt encrypted password",
|
||||
Args: cobra.ExactArgs(1),
|
||||
RunE: func(cmd *cobra.Command, args []string) error {
|
||||
cost, err := cmd.Flags().GetInt("cost")
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
if cost < bcrypt.MinCost {
|
||||
return fmt.Errorf("given cost cannot be under minimum cost of %d", bcrypt.MinCost)
|
||||
}
|
||||
|
||||
if cost > bcrypt.MaxCost {
|
||||
return fmt.Errorf("given cost cannot be over maximum cost of %d", bcrypt.MaxCost)
|
||||
}
|
||||
|
||||
pwd := args[0]
|
||||
if pwd == "" {
|
||||
return errors.New("password argument must not be empty")
|
||||
}
|
||||
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(pwd), cost)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
fmt.Println(string(hash))
|
||||
return nil
|
||||
},
|
||||
}
|
||||
+22
-4
@@ -1,6 +1,7 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
@@ -10,6 +11,7 @@ import (
|
||||
"strings"
|
||||
"syscall"
|
||||
|
||||
"github.com/coreos/go-systemd/v22/activation"
|
||||
"github.com/hacdias/webdav/v5/lib"
|
||||
"github.com/spf13/cobra"
|
||||
"go.uber.org/zap"
|
||||
@@ -79,6 +81,8 @@ set WD_CERT.`,
|
||||
return err
|
||||
}
|
||||
|
||||
server := &http.Server{Handler: handler}
|
||||
|
||||
// Trap exiting signals
|
||||
quit := make(chan os.Signal, 1)
|
||||
|
||||
@@ -87,9 +91,9 @@ set WD_CERT.`,
|
||||
|
||||
var err error
|
||||
if cfg.TLS {
|
||||
err = http.ServeTLS(listener, handler, cfg.Cert, cfg.Key)
|
||||
err = server.ServeTLS(listener, cfg.Cert, cfg.Key)
|
||||
} else {
|
||||
err = http.Serve(listener, handler)
|
||||
err = server.Serve(listener)
|
||||
}
|
||||
|
||||
if err != nil && !errors.Is(err, http.ErrServerClosed) {
|
||||
@@ -103,7 +107,7 @@ set WD_CERT.`,
|
||||
signal := <-quit
|
||||
|
||||
zap.L().Info("caught signal, shutting down", zap.Stringer("signal", signal))
|
||||
_ = listener.Close()
|
||||
_ = server.Shutdown(context.Background())
|
||||
|
||||
return nil
|
||||
},
|
||||
@@ -115,7 +119,21 @@ func getListener(cfg *lib.Config) (net.Listener, error) {
|
||||
network string
|
||||
)
|
||||
|
||||
if strings.HasPrefix(cfg.Address, "unix:") {
|
||||
if strings.HasPrefix(cfg.Address, "sd-listen-fd:") {
|
||||
listeners, err := activation.ListenersWithNames()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
address := cfg.Address[13:]
|
||||
listener, ok := listeners[address]
|
||||
|
||||
if !ok || len(listener) < 1 {
|
||||
return nil, errors.New("unknown sd-listen-fd address '" + address + "'")
|
||||
}
|
||||
|
||||
return listener[0], nil
|
||||
} else if strings.HasPrefix(cfg.Address, "unix:") {
|
||||
address = cfg.Address[5:]
|
||||
network = "unix"
|
||||
} else {
|
||||
|
||||
+14
@@ -0,0 +1,14 @@
|
||||
name: webdav
|
||||
|
||||
services:
|
||||
app:
|
||||
container_name: webdav
|
||||
image: 'webdav:test'
|
||||
ports:
|
||||
- '6065:6065'
|
||||
security_opt:
|
||||
- label=type:container_runtime_t
|
||||
restart: always
|
||||
volumes:
|
||||
- ./data:/data
|
||||
- ./config.yml:/config.yml:ro
|
||||
@@ -1,39 +1,36 @@
|
||||
module github.com/hacdias/webdav/v5
|
||||
|
||||
go 1.23
|
||||
go 1.25.0
|
||||
|
||||
require (
|
||||
github.com/go-viper/mapstructure/v2 v2.1.0
|
||||
github.com/rs/cors v1.11.0
|
||||
github.com/spf13/cobra v1.8.1
|
||||
github.com/spf13/pflag v1.0.5
|
||||
github.com/spf13/viper v1.19.0
|
||||
github.com/stretchr/testify v1.9.0
|
||||
github.com/studio-b12/gowebdav v0.9.0
|
||||
go.uber.org/zap v1.27.0
|
||||
golang.org/x/crypto v0.26.0
|
||||
golang.org/x/net v0.28.0
|
||||
github.com/coreos/go-systemd/v22 v22.7.0
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0
|
||||
github.com/rs/cors v1.11.1
|
||||
github.com/spf13/cobra v1.10.2
|
||||
github.com/spf13/pflag v1.0.10
|
||||
github.com/spf13/viper v1.21.0
|
||||
github.com/stretchr/testify v1.11.1
|
||||
github.com/studio-b12/gowebdav v0.12.0
|
||||
go.uber.org/zap v1.28.0
|
||||
golang.org/x/crypto v0.53.0
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20260626155920-5b7f84159940
|
||||
golang.org/x/net v0.56.0
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/fsnotify/fsnotify v1.7.0 // indirect
|
||||
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||
github.com/fsnotify/fsnotify v1.9.0 // indirect
|
||||
github.com/inconshreveable/mousetrap v1.1.0 // indirect
|
||||
github.com/magiconair/properties v1.8.7 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||
github.com/sagikazarmark/locafero v0.6.0 // indirect
|
||||
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
|
||||
github.com/sourcegraph/conc v0.3.0 // indirect
|
||||
github.com/spf13/afero v1.11.0 // indirect
|
||||
github.com/spf13/cast v1.7.0 // indirect
|
||||
github.com/sagikazarmark/locafero v0.11.0 // indirect
|
||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 // indirect
|
||||
github.com/spf13/afero v1.15.0 // indirect
|
||||
github.com/spf13/cast v1.10.0 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20240808152545-0cdaa3abc0fa // indirect
|
||||
golang.org/x/sys v0.24.0 // indirect
|
||||
golang.org/x/text v0.17.0 // indirect
|
||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||
go.yaml.in/yaml/v3 v3.0.4 // indirect
|
||||
golang.org/x/sys v0.46.0 // indirect
|
||||
golang.org/x/text v0.38.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
|
||||
@@ -1,88 +1,72 @@
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.4/go.mod h1:tgQtvFlXSQOSOSIRvRPT7W67SCa46tRHOmNcaadrF8o=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/coreos/go-systemd/v22 v22.7.0 h1:LAEzFkke61DFROc7zNLX/WA2i5J8gYqe0rSj9KI28KA=
|
||||
github.com/coreos/go-systemd/v22 v22.7.0/go.mod h1:xNUYtjHu2EDXbsxz1i41wouACIwT7Ybq9o0BQhMwD0w=
|
||||
github.com/cpuguy83/go-md2man/v2 v2.0.6/go.mod h1:oOW0eioCTA6cOiMLiUPZOpcVxMig6NIQQ7OS05n1F4g=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/frankban/quicktest v1.14.6 h1:7Xjx+VpznH+oBnejlPUj8oUpdxnVs4f8XU8WnHkI4W8=
|
||||
github.com/frankban/quicktest v1.14.6/go.mod h1:4ptaffx2x8+WTWXmUCuVU6aPUX1/Mz7zb5vbUoiM6w0=
|
||||
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
|
||||
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
|
||||
github.com/go-viper/mapstructure/v2 v2.1.0 h1:gHnMa2Y/pIxElCH2GlZZ1lZSsn6XMtufpGyP1XxdC/w=
|
||||
github.com/go-viper/mapstructure/v2 v2.1.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/fsnotify/fsnotify v1.9.0 h1:2Ml+OJNzbYCTzsxtv8vKSFD9PbJjmhYF14k/jKC7S9k=
|
||||
github.com/fsnotify/fsnotify v1.9.0/go.mod h1:8jBTzvmWwFyi3Pb8djgCCO5IBqzKJ/Jwo8TRcHyHii0=
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0 h1:vM5IJoUAy3d7zRSVtIwQgBj7BiWtMPfmPEgAXnvj1Ro=
|
||||
github.com/go-viper/mapstructure/v2 v2.5.0/go.mod h1:oJDH3BJKyqBA2TXFhDsKDGDTlndYOZ6rGS0BRZIxGhM=
|
||||
github.com/google/go-cmp v0.6.0 h1:ofyhxvXcZhMsU5ulbFiLKl/XBFqE1GSq7atu8tAmTRI=
|
||||
github.com/google/go-cmp v0.6.0/go.mod h1:17dUlkBOakJ0+DkrSSNjCkIjxS6bF9zb3elmeNGIjoY=
|
||||
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
|
||||
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE=
|
||||
github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk=
|
||||
github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY=
|
||||
github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE=
|
||||
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
|
||||
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
|
||||
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
||||
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
|
||||
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
|
||||
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4 h1:mye9XuhQ6gvn5h28+VilKrrPoQVanw5PMw/TB0t5Ec4=
|
||||
github.com/pelletier/go-toml/v2 v2.2.4/go.mod h1:2gIqNv+qfxSVS7cM2xJQKtLSTLUE9V8t9Stt+h56mCY=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/rogpeppe/go-internal v1.9.0 h1:73kH8U+JUqXU8lRuOHeVHaa/SZPifC7BkcraZVejAe8=
|
||||
github.com/rogpeppe/go-internal v1.9.0/go.mod h1:WtVeX8xhTBvf0smdhujwtBcq4Qrzq/fJaraNFVN+nFs=
|
||||
github.com/rs/cors v1.11.0 h1:0B9GE/r9Bc2UxRMMtymBkHTenPkHDv0CW4Y98GBY+po=
|
||||
github.com/rs/cors v1.11.0/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
|
||||
github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=
|
||||
github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
|
||||
github.com/russross/blackfriday/v2 v2.1.0/go.mod h1:+Rmxgy9KzJVeS9/2gXHxylqXiyQDYRxCVz55jmeOWTM=
|
||||
github.com/sagikazarmark/locafero v0.6.0 h1:ON7AQg37yzcRPU69mt7gwhFEBwxI6P9T4Qu3N51bwOk=
|
||||
github.com/sagikazarmark/locafero v0.6.0/go.mod h1:77OmuIc6VTraTXKXIs/uvUxKGUXjE1GbemJYHqdNjX0=
|
||||
github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
|
||||
github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ=
|
||||
github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
|
||||
github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
|
||||
github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8=
|
||||
github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY=
|
||||
github.com/spf13/cast v1.7.0 h1:ntdiHjuueXFgm5nzDRdOS4yfT43P5Fnud6DH50rz/7w=
|
||||
github.com/spf13/cast v1.7.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
|
||||
github.com/spf13/cobra v1.8.1 h1:e5/vxKd/rZsfSJMUX1agtjeTDf+qv1/JdBF8gg5k9ZM=
|
||||
github.com/spf13/cobra v1.8.1/go.mod h1:wHxEcudfqmLYa8iTfL+OuZPbBZkmvliBWKIezN3kD9Y=
|
||||
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/viper v1.19.0 h1:RWq5SEjt8o25SROyN3z2OrDB9l7RPd3lwTWU8EcEdcI=
|
||||
github.com/spf13/viper v1.19.0/go.mod h1:GQUN9bilAbhU/jgc1bKs99f/suXKeUMct8Adx5+Ntkg=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/studio-b12/gowebdav v0.9.0 h1:1j1sc9gQnNxbXXM4M/CebPOX4aXYtr7MojAVcN4dHjU=
|
||||
github.com/studio-b12/gowebdav v0.9.0/go.mod h1:bHA7t77X/QFExdeAnDzK6vKM34kEZAcE1OX4MfiwjkE=
|
||||
github.com/sagikazarmark/locafero v0.11.0 h1:1iurJgmM9G3PA/I+wWYIOw/5SyBtxapeHDcg+AAIFXc=
|
||||
github.com/sagikazarmark/locafero v0.11.0/go.mod h1:nVIGvgyzw595SUSUE6tvCp3YYTeHs15MvlmU87WwIik=
|
||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8 h1:+jumHNA0Wrelhe64i8F6HNlS8pkoyMv5sreGx2Ry5Rw=
|
||||
github.com/sourcegraph/conc v0.3.1-0.20240121214520-5f936abd7ae8/go.mod h1:3n1Cwaq1E1/1lhQhtRK2ts/ZwZEhjcQeJQ1RuC6Q/8U=
|
||||
github.com/spf13/afero v1.15.0 h1:b/YBCLWAJdFWJTN9cLhiXXcD7mzKn9Dm86dNnfyQw1I=
|
||||
github.com/spf13/afero v1.15.0/go.mod h1:NC2ByUVxtQs4b3sIUphxK0NioZnmxgyCrfzeuq8lxMg=
|
||||
github.com/spf13/cast v1.10.0 h1:h2x0u2shc1QuLHfxi+cTJvs30+ZAHOGRic8uyGTDWxY=
|
||||
github.com/spf13/cast v1.10.0/go.mod h1:jNfB8QC9IA6ZuY2ZjDp0KtFO2LZZlg4S/7bzP6qqeHo=
|
||||
github.com/spf13/cobra v1.10.2 h1:DMTTonx5m65Ic0GOoRY2c16WCbHxOOw6xxezuLaBpcU=
|
||||
github.com/spf13/cobra v1.10.2/go.mod h1:7C1pvHqHw5A4vrJfjNwvOdzYu0Gml16OCs2GRiTUUS4=
|
||||
github.com/spf13/pflag v1.0.9/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/pflag v1.0.10 h1:4EBh2KAYBwaONj6b2Ye1GiHfwjqyROoF4RwYO+vPwFk=
|
||||
github.com/spf13/pflag v1.0.10/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/viper v1.21.0 h1:x5S+0EU27Lbphp4UKm1C+1oQO+rKx36vfCoaVebLFSU=
|
||||
github.com/spf13/viper v1.21.0/go.mod h1:P0lhsswPGWD/1lZJ9ny3fYnVqxiegrlNrEmgLjbTCAY=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/studio-b12/gowebdav v0.12.0 h1:kFRtQECt8jmVAvA6RHBz3geXUGJHUZA6/IKpOVUs5kM=
|
||||
github.com/studio-b12/gowebdav v0.12.0/go.mod h1:bHA7t77X/QFExdeAnDzK6vKM34kEZAcE1OX4MfiwjkE=
|
||||
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
||||
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.uber.org/multierr v1.11.0 h1:blXXJkSxSSfBVBlC76pxqeO+LN3aDfLQo+309xJstO0=
|
||||
go.uber.org/multierr v1.11.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
|
||||
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||
golang.org/x/crypto v0.26.0 h1:RrRspgV4mU+YwB4FYnuBoKsUapNIL5cohGAmSH3azsw=
|
||||
golang.org/x/crypto v0.26.0/go.mod h1:GY7jblb9wI+FOo5y8/S2oY4zWP07AkOJ4+jxCqdqn54=
|
||||
golang.org/x/exp v0.0.0-20240808152545-0cdaa3abc0fa h1:ELnwvuAXPNtPk1TJRuGkI9fDTwym6AYBu0qzT8AcHdI=
|
||||
golang.org/x/exp v0.0.0-20240808152545-0cdaa3abc0fa/go.mod h1:akd2r19cwCdwSwWeIdzYQGa/EZZyqcOdwWiwj5L5eKQ=
|
||||
golang.org/x/net v0.28.0 h1:a9JDOJc5GMUJ0+UDqmLT86WiEy7iWyIhz8gz8E4e5hE=
|
||||
golang.org/x/net v0.28.0/go.mod h1:yqtgsTWOOnlGLG9GFRrK3++bGOUEkNBoHZc8MEDWPNg=
|
||||
golang.org/x/sys v0.24.0 h1:Twjiwq9dn6R1fQcyiK+wQyHWfaz/BJB+YIpzU/Cv3Xg=
|
||||
golang.org/x/sys v0.24.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.17.0 h1:XtiM5bkSOt+ewxlOE/aE/AKEHibwj/6gvWMl9Rsh0Qc=
|
||||
golang.org/x/text v0.17.0/go.mod h1:BuEKDfySbSR4drPmRPG/7iBdf8hvFMuRexcpahXilzY=
|
||||
go.uber.org/zap v1.28.0 h1:IZzaP1Fv73/T/pBMLk4VutPl36uNC+OSUh3JLG3FIjo=
|
||||
go.uber.org/zap v1.28.0/go.mod h1:rDLpOi171uODNm/mxFcuYWxDsqWSAVkFdX4XojSKg/Q=
|
||||
go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=
|
||||
go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=
|
||||
golang.org/x/crypto v0.53.0 h1:QZ4Muo8THX6CizN2vPPd5fBGHyogrdK9fG4wLPFUsto=
|
||||
golang.org/x/crypto v0.53.0/go.mod h1:DNLU434OwVakk9PzuwV8w62mAJpRJL3vsgcfp4Qnsio=
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20260626155920-5b7f84159940 h1:WD+hrfJy2TRwCU7dnWiqw/dGb9jNdEzy2uR+jtpYJYk=
|
||||
golang.org/x/crypto/x509roots/fallback v0.0.0-20260626155920-5b7f84159940/go.mod h1:+UoQFNBq2p2wO+Q6ddVtYc25GZ6VNdOMyyrd4nrqrKs=
|
||||
golang.org/x/net v0.56.0 h1:Rw8j/hFzGvJUZwNBXnAtf5sVDVt+65SK2C7IxCxZt5o=
|
||||
golang.org/x/net v0.56.0/go.mod h1:D3Ku6r+V6JROoZK144D2XfMHFcMq/0zSfLelVTCFKec=
|
||||
golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
|
||||
golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
|
||||
golang.org/x/text v0.38.0 h1:sXmwo9DwP3OK9EZ7PqAdaooSGozfl/3a6/xJcbzPRhE=
|
||||
golang.org/x/text v0.38.0/go.mod h1:YXZt3QhHUKYT53r2lLKFIVi6Ao1jdzrTR/KQ09qyxF4=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15 h1:YR8cESwS4TdDjEe65xsg0ogRM/Nc3DYOhEAlW+xobZo=
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
|
||||
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
|
||||
+27
-9
@@ -3,6 +3,7 @@ package lib
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
|
||||
@@ -33,13 +34,14 @@ type Config struct {
|
||||
Prefix string
|
||||
NoSniff bool
|
||||
NoPassword bool
|
||||
BehindProxy bool
|
||||
Log Log
|
||||
CORS CORS
|
||||
Users []User
|
||||
}
|
||||
|
||||
func ParseConfig(filename string, flags *pflag.FlagSet) (*Config, error) {
|
||||
v := viper.New()
|
||||
v := viper.NewWithOptions(viper.ExperimentalBindStruct())
|
||||
|
||||
// Configure flags bindings
|
||||
if flags != nil {
|
||||
@@ -52,6 +54,10 @@ func ParseConfig(filename string, flags *pflag.FlagSet) (*Config, error) {
|
||||
// Configuration file settings
|
||||
v.AddConfigPath(".")
|
||||
v.AddConfigPath("/etc/webdav/")
|
||||
if path, err := os.Executable(); err == nil {
|
||||
v.AddConfigPath(filepath.Dir(path))
|
||||
}
|
||||
|
||||
v.SetConfigName("config")
|
||||
if filename != "" {
|
||||
v.SetConfigFile(filename)
|
||||
@@ -61,9 +67,6 @@ func ParseConfig(filename string, flags *pflag.FlagSet) (*Config, error) {
|
||||
v.SetEnvPrefix("wd")
|
||||
v.SetEnvKeyReplacer(strings.NewReplacer(".", "_"))
|
||||
v.AutomaticEnv()
|
||||
// TODO: use new env struct bind feature when it's released in viper.
|
||||
// This should make it redundant to set defaults for things that are
|
||||
// empty or false.
|
||||
|
||||
// Defaults shared with flags
|
||||
v.SetDefault("TLS", DefaultTLS)
|
||||
@@ -74,6 +77,7 @@ func ParseConfig(filename string, flags *pflag.FlagSet) (*Config, error) {
|
||||
v.SetDefault("Prefix", DefaultPrefix)
|
||||
|
||||
// Other defaults
|
||||
v.SetDefault("RulesBehavior", RulesOverwrite)
|
||||
v.SetDefault("Directory", ".")
|
||||
v.SetDefault("Permissions", "R")
|
||||
v.SetDefault("Debug", false)
|
||||
@@ -82,9 +86,9 @@ func ParseConfig(filename string, flags *pflag.FlagSet) (*Config, error) {
|
||||
v.SetDefault("Log.Format", "console")
|
||||
v.SetDefault("Log.Outputs", []string{"stderr"})
|
||||
v.SetDefault("Log.Colors", true)
|
||||
v.SetDefault("CORS.Allowed_Headers", []string{"*"})
|
||||
v.SetDefault("CORS.Allowed_Hosts", []string{"*"})
|
||||
v.SetDefault("CORS.Allowed_Methods", []string{"*"})
|
||||
v.SetDefault("CORS.Allowed_Headers", []string{"Authorization", "Content-Type", "Content-Range", "Depth", "Destination", "If", "Lock-Token", "Overwrite", "X-Update-Range"})
|
||||
v.SetDefault("CORS.Allowed_Methods", []string{"COPY", "DELETE", "GET", "HEAD", "LOCK", "MKCOL", "MOVE", "OPTIONS", "PATCH", "POST", "PROPFIND", "PROPPATCH", "PUT", "UNLOCK"})
|
||||
|
||||
// Read and unmarshal configuration
|
||||
err := v.ReadInConfig()
|
||||
@@ -114,7 +118,21 @@ func ParseConfig(filename string, flags *pflag.FlagSet) (*Config, error) {
|
||||
cfg.Users[i].Permissions = cfg.Permissions
|
||||
}
|
||||
|
||||
if !v.IsSet(fmt.Sprintf("Users.%d.Rules", i)) {
|
||||
if !v.IsSet(fmt.Sprintf("Users.%d.RulesBehavior", i)) {
|
||||
cfg.Users[i].RulesBehavior = cfg.RulesBehavior
|
||||
}
|
||||
|
||||
if v.IsSet(fmt.Sprintf("Users.%d.Rules", i)) {
|
||||
switch cfg.Users[i].RulesBehavior {
|
||||
case RulesOverwrite:
|
||||
// Do nothing
|
||||
case RulesAppend:
|
||||
rules := append([]*Rule{}, cfg.Rules...)
|
||||
rules = append(rules, cfg.Users[i].Rules...)
|
||||
|
||||
cfg.Users[i].Rules = rules
|
||||
}
|
||||
} else {
|
||||
cfg.Users[i].Rules = cfg.Rules
|
||||
}
|
||||
}
|
||||
@@ -160,8 +178,8 @@ func (c *Config) Validate() error {
|
||||
return fmt.Errorf("invalid config: %w", err)
|
||||
}
|
||||
|
||||
for _, u := range c.Users {
|
||||
err := u.Validate(c.NoPassword)
|
||||
for i := range c.Users {
|
||||
err := c.Users[i].Validate(c.NoPassword)
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid config: %w", err)
|
||||
}
|
||||
|
||||
+140
-12
@@ -22,6 +22,17 @@ func writeAndParseConfig(t *testing.T, content, extension string) *Config {
|
||||
return cfg
|
||||
}
|
||||
|
||||
func writeAndParseConfigWithError(t *testing.T, content, extension, error string) {
|
||||
tmpDir := t.TempDir()
|
||||
tmpFile := filepath.Join(tmpDir, "config"+extension)
|
||||
|
||||
err := os.WriteFile(tmpFile, []byte(content), 0666)
|
||||
require.NoError(t, err)
|
||||
|
||||
_, err = ParseConfig(tmpFile, nil)
|
||||
require.ErrorContains(t, err, error)
|
||||
}
|
||||
|
||||
func TestConfigDefaults(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -40,9 +51,9 @@ func TestConfigDefaults(t *testing.T) {
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, dir, cfg.Directory)
|
||||
|
||||
require.EqualValues(t, []string{"*"}, cfg.CORS.AllowedHeaders)
|
||||
require.EqualValues(t, []string{"*"}, cfg.CORS.AllowedHosts)
|
||||
require.EqualValues(t, []string{"*"}, cfg.CORS.AllowedMethods)
|
||||
require.EqualValues(t, []string{"Authorization", "Content-Type", "Content-Range", "Depth", "Destination", "If", "Lock-Token", "Overwrite", "X-Update-Range"}, cfg.CORS.AllowedHeaders)
|
||||
require.EqualValues(t, []string{"COPY", "DELETE", "GET", "HEAD", "LOCK", "MKCOL", "MOVE", "OPTIONS", "PATCH", "POST", "PROPFIND", "PROPPATCH", "PUT", "UNLOCK"}, cfg.CORS.AllowedMethods)
|
||||
}
|
||||
|
||||
func TestConfigCascade(t *testing.T) {
|
||||
@@ -181,24 +192,111 @@ cors:
|
||||
}
|
||||
|
||||
func TestConfigRules(t *testing.T) {
|
||||
content := `
|
||||
t.Run("Only Regex or Path", func(t *testing.T) {
|
||||
content := `
|
||||
directory: /
|
||||
rules:
|
||||
- regex: '^.+\.js$'
|
||||
path: /public/access/`
|
||||
|
||||
writeAndParseConfigWithError(t, content, ".yaml", "cannot define both regex and path")
|
||||
})
|
||||
|
||||
t.Run("Regex or Path Required", func(t *testing.T) {
|
||||
content := `
|
||||
directory: /
|
||||
rules:
|
||||
- permissions: CRUD`
|
||||
|
||||
writeAndParseConfigWithError(t, content, ".yaml", "must either define a path of a regex")
|
||||
})
|
||||
|
||||
t.Run("Parse", func(t *testing.T) {
|
||||
content := `
|
||||
directory: /
|
||||
rules:
|
||||
- regex: '^.+\.js$'
|
||||
- path: /public/access/`
|
||||
|
||||
cfg := writeAndParseConfig(t, content, ".yaml")
|
||||
require.NoError(t, cfg.Validate())
|
||||
cfg := writeAndParseConfig(t, content, ".yaml")
|
||||
require.NoError(t, cfg.Validate())
|
||||
|
||||
require.Len(t, cfg.Rules, 2)
|
||||
require.Len(t, cfg.Rules, 2)
|
||||
|
||||
require.Empty(t, cfg.Rules[0].Path)
|
||||
require.NotNil(t, cfg.Rules[0].Regex)
|
||||
require.True(t, cfg.Rules[0].Regex.MatchString("/my/path/to/file.js"))
|
||||
require.False(t, cfg.Rules[0].Regex.MatchString("/my/path/to/file.ts"))
|
||||
require.Empty(t, cfg.Rules[0].Path)
|
||||
require.NotNil(t, cfg.Rules[0].Regex)
|
||||
require.True(t, cfg.Rules[0].Regex.MatchString("/my/path/to/file.js"))
|
||||
require.False(t, cfg.Rules[0].Regex.MatchString("/my/path/to/file.ts"))
|
||||
|
||||
require.NotEmpty(t, cfg.Rules[1].Path)
|
||||
require.Nil(t, cfg.Rules[1].Regex)
|
||||
require.NotEmpty(t, cfg.Rules[1].Path)
|
||||
require.Nil(t, cfg.Rules[1].Regex)
|
||||
})
|
||||
|
||||
t.Run("Rules Behavior (Default: Overwrite)", func(t *testing.T) {
|
||||
content := `
|
||||
directory: /
|
||||
rules:
|
||||
- regex: '^.+\.js$'
|
||||
- path: /public/access/
|
||||
|
||||
users:
|
||||
- username: foo
|
||||
password: bar
|
||||
rules:
|
||||
- path: /private/access/`
|
||||
|
||||
cfg := writeAndParseConfig(t, content, ".yaml")
|
||||
require.NoError(t, cfg.Validate())
|
||||
|
||||
require.Len(t, cfg.Rules, 2)
|
||||
|
||||
require.Empty(t, cfg.Rules[0].Path)
|
||||
require.NotNil(t, cfg.Rules[0].Regex)
|
||||
require.True(t, cfg.Rules[0].Regex.MatchString("/my/path/to/file.js"))
|
||||
require.False(t, cfg.Rules[0].Regex.MatchString("/my/path/to/file.ts"))
|
||||
|
||||
require.EqualValues(t, "/public/access/", cfg.Rules[1].Path)
|
||||
require.Nil(t, cfg.Rules[1].Regex)
|
||||
|
||||
require.Len(t, cfg.Users, 1)
|
||||
require.Len(t, cfg.Users[0].Rules, 1)
|
||||
require.EqualValues(t, "/private/access/", cfg.Users[0].Rules[0].Path)
|
||||
})
|
||||
|
||||
t.Run("Rules Behavior (Append)", func(t *testing.T) {
|
||||
content := `
|
||||
directory: /
|
||||
rules:
|
||||
- regex: '^.+\.js$'
|
||||
- path: /public/access/
|
||||
rulesBehavior: append
|
||||
|
||||
users:
|
||||
- username: foo
|
||||
password: bar
|
||||
rules:
|
||||
- path: /private/access/`
|
||||
|
||||
cfg := writeAndParseConfig(t, content, ".yaml")
|
||||
require.NoError(t, cfg.Validate())
|
||||
|
||||
require.Len(t, cfg.Rules, 2)
|
||||
|
||||
require.Empty(t, cfg.Rules[0].Path)
|
||||
require.NotNil(t, cfg.Rules[0].Regex)
|
||||
require.True(t, cfg.Rules[0].Regex.MatchString("/my/path/to/file.js"))
|
||||
require.False(t, cfg.Rules[0].Regex.MatchString("/my/path/to/file.ts"))
|
||||
|
||||
require.EqualValues(t, "/public/access/", cfg.Rules[1].Path)
|
||||
require.Nil(t, cfg.Rules[1].Regex)
|
||||
|
||||
require.Len(t, cfg.Users, 1)
|
||||
require.Len(t, cfg.Users[0].Rules, 3)
|
||||
|
||||
require.EqualValues(t, cfg.Rules[0], cfg.Users[0].Rules[0])
|
||||
require.EqualValues(t, cfg.Rules[1], cfg.Users[0].Rules[1])
|
||||
require.EqualValues(t, "/private/access/", cfg.Users[0].Rules[2].Path)
|
||||
})
|
||||
}
|
||||
|
||||
func TestConfigEnv(t *testing.T) {
|
||||
@@ -224,3 +322,33 @@ func TestConfigEnv(t *testing.T) {
|
||||
require.NoError(t, os.Setenv("WD_PERMISSIONS", ""))
|
||||
require.NoError(t, os.Setenv("WD_DIRECTORY", ""))
|
||||
}
|
||||
|
||||
func TestConfigParseUserPasswordEnvironment(t *testing.T) {
|
||||
content := `
|
||||
directory: /
|
||||
users:
|
||||
- username: '{env}USER1_USERNAME'
|
||||
password: '{env}USER1_PASSWORD'
|
||||
- username: basic
|
||||
password: basic
|
||||
`
|
||||
|
||||
writeAndParseConfigWithError(t, content, ".yml", "username environment variable is empty")
|
||||
|
||||
err := os.Setenv("USER1_USERNAME", "admin")
|
||||
require.NoError(t, err)
|
||||
|
||||
writeAndParseConfigWithError(t, content, ".yml", "password environment variable is empty")
|
||||
|
||||
err = os.Setenv("USER1_PASSWORD", "admin")
|
||||
require.NoError(t, err)
|
||||
|
||||
cfg := writeAndParseConfig(t, content, ".yaml")
|
||||
require.NoError(t, cfg.Validate())
|
||||
|
||||
require.Equal(t, "admin", cfg.Users[0].Username)
|
||||
require.Equal(t, "basic", cfg.Users[1].Username)
|
||||
|
||||
require.True(t, cfg.Users[0].checkPassword("admin"))
|
||||
require.True(t, cfg.Users[1].checkPassword("basic"))
|
||||
}
|
||||
|
||||
+1
-1
@@ -47,7 +47,7 @@ type noSniffFileInfo struct {
|
||||
}
|
||||
|
||||
func (w noSniffFileInfo) ContentType(ctx context.Context) (contentType string, err error) {
|
||||
if mimeType := mime.TypeByExtension(path.Ext(w.FileInfo.Name())); mimeType != "" {
|
||||
if mimeType := mime.TypeByExtension(path.Ext(w.Name())); mimeType != "" {
|
||||
// We can figure out the mime from the extension.
|
||||
return mimeType, nil
|
||||
} else {
|
||||
|
||||
+75
-26
@@ -2,7 +2,6 @@ package lib
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
|
||||
@@ -17,14 +16,23 @@ type handlerUser struct {
|
||||
}
|
||||
|
||||
type Handler struct {
|
||||
noPassword bool
|
||||
user *handlerUser
|
||||
users map[string]*handlerUser
|
||||
noPassword bool
|
||||
behindProxy bool
|
||||
user *handlerUser
|
||||
users map[string]*handlerUser
|
||||
}
|
||||
|
||||
func NewHandler(c *Config) (http.Handler, error) {
|
||||
ls := webdav.NewMemLS()
|
||||
|
||||
logFunc := func(r *http.Request, err error) {
|
||||
lZap := getRequestLogger(r, c.BehindProxy)
|
||||
lZap.Debug("handle webdav request", zap.String("method", r.Method), zap.String("path", r.URL.Path), zap.Error(err))
|
||||
}
|
||||
|
||||
h := &Handler{
|
||||
noPassword: c.NoPassword,
|
||||
noPassword: c.NoPassword,
|
||||
behindProxy: c.BehindProxy,
|
||||
user: &handlerUser{
|
||||
User: User{
|
||||
UserPermissions: c.UserPermissions,
|
||||
@@ -35,7 +43,11 @@ func NewHandler(c *Config) (http.Handler, error) {
|
||||
Dir: webdav.Dir(c.Directory),
|
||||
noSniff: c.NoSniff,
|
||||
},
|
||||
LockSystem: webdav.NewMemLS(),
|
||||
LockSystem: &lockSystem{
|
||||
LockSystem: ls,
|
||||
directory: c.Directory,
|
||||
},
|
||||
Logger: logFunc,
|
||||
},
|
||||
},
|
||||
users: map[string]*handlerUser{},
|
||||
@@ -50,7 +62,11 @@ func NewHandler(c *Config) (http.Handler, error) {
|
||||
Dir: webdav.Dir(u.Directory),
|
||||
noSniff: c.NoSniff,
|
||||
},
|
||||
LockSystem: webdav.NewMemLS(),
|
||||
LockSystem: &lockSystem{
|
||||
LockSystem: ls,
|
||||
directory: u.Directory,
|
||||
},
|
||||
Logger: logFunc,
|
||||
},
|
||||
}
|
||||
}
|
||||
@@ -61,6 +77,7 @@ func NewHandler(c *Config) (http.Handler, error) {
|
||||
AllowedOrigins: c.CORS.AllowedHosts,
|
||||
AllowedMethods: c.CORS.AllowedMethods,
|
||||
AllowedHeaders: c.CORS.AllowedHeaders,
|
||||
ExposedHeaders: c.CORS.ExposedHeaders,
|
||||
OptionsPassthrough: false,
|
||||
}).Handler(h), nil
|
||||
}
|
||||
@@ -80,13 +97,14 @@ func NewHandler(c *Config) (http.Handler, error) {
|
||||
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
user := h.user
|
||||
|
||||
lZap := getRequestLogger(r, h.behindProxy)
|
||||
|
||||
// Authentication
|
||||
if len(h.users) > 0 {
|
||||
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
|
||||
|
||||
// Gets the correct user for this request.
|
||||
username, password, ok := r.BasicAuth()
|
||||
zap.L().Info("login attempt", zap.String("username", username), zap.String("remote_address", r.RemoteAddr))
|
||||
if !ok {
|
||||
http.Error(w, "Not authorized", http.StatusUnauthorized)
|
||||
return
|
||||
@@ -94,39 +112,38 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
|
||||
user, ok = h.users[username]
|
||||
if !ok {
|
||||
// Log invalid username
|
||||
lZap.Info("invalid username", zap.String("username", username))
|
||||
http.Error(w, "Not authorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
if !h.noPassword && !user.checkPassword(password) {
|
||||
zap.L().Info("invalid password", zap.String("username", username), zap.String("remote_address", r.RemoteAddr))
|
||||
// Log invalid password
|
||||
lZap.Info("invalid password", zap.String("username", username))
|
||||
http.Error(w, "Not authorized", http.StatusUnauthorized)
|
||||
return
|
||||
}
|
||||
|
||||
zap.L().Info("user authorized", zap.String("username", username))
|
||||
// Log successful authorization
|
||||
lZap.Info("user authorized", zap.String("username", username))
|
||||
}
|
||||
|
||||
// Cleanup destination header if it's present by stripping out the prefix
|
||||
// and only keeping the path.
|
||||
if destination := r.Header.Get("Destination"); destination != "" {
|
||||
u, err := url.Parse(destination)
|
||||
if err == nil {
|
||||
destination = strings.TrimPrefix(u.Path, user.Prefix)
|
||||
if !strings.HasPrefix(destination, "/") {
|
||||
destination = "/" + destination
|
||||
}
|
||||
r.Header.Set("Destination", destination)
|
||||
}
|
||||
// Convert the HTTP request into an internal request type
|
||||
req, err := newRequest(r, h.user.Prefix)
|
||||
if err != nil {
|
||||
lZap.Info("invalid request path or destination", zap.Error(err))
|
||||
http.Error(w, "Invalid request path or destination", http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
|
||||
// Checks for user permissions relatively to this PATH.
|
||||
allowed := user.Allowed(r, func(filename string) bool {
|
||||
allowed := user.Allowed(req, func(filename string) bool {
|
||||
_, err := user.FileSystem.Stat(r.Context(), filename)
|
||||
return !os.IsNotExist(err)
|
||||
})
|
||||
|
||||
zap.L().Debug("allowed & method & path", zap.Bool("allowed", allowed), zap.String("method", r.Method), zap.String("path", r.URL.Path))
|
||||
lZap.Debug("allowed & method & path", zap.Bool("allowed", allowed), zap.String("method", r.Method), zap.String("path", r.URL.Path))
|
||||
|
||||
if !allowed {
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
@@ -143,8 +160,12 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
// "index.html" resource, a human-readable view of the contents of
|
||||
// the collection, or something else altogether.
|
||||
//
|
||||
// Get, when applied to collection, will return the same as PROPFIND method.
|
||||
if r.Method == "GET" && strings.HasPrefix(r.URL.Path, user.Prefix) {
|
||||
// Similarly, since the definition of HEAD is a GET without a response
|
||||
// message body, the semantics of HEAD are unmodified when applied to
|
||||
// collection resources.
|
||||
//
|
||||
// GET (or HEAD), when applied to collection, will return the same as PROPFIND method.
|
||||
if (r.Method == "GET" || r.Method == "HEAD") && strings.HasPrefix(r.URL.Path, user.Prefix) {
|
||||
info, err := user.FileSystem.Stat(r.Context(), strings.TrimPrefix(r.URL.Path, user.Prefix))
|
||||
if err == nil && info.IsDir() {
|
||||
r.Method = "PROPFIND"
|
||||
@@ -155,14 +176,42 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
if r.Method == "OPTIONS" {
|
||||
user.handleOptions(w, r, req.path)
|
||||
return
|
||||
}
|
||||
|
||||
if r.Method == "PATCH" || (r.Method == "PUT" && r.Header.Get("Content-Range") != "") {
|
||||
user.handlePartialUpdate(w, r, req.path)
|
||||
return
|
||||
}
|
||||
|
||||
// Runs the WebDAV.
|
||||
user.ServeHTTP(w, r)
|
||||
}
|
||||
|
||||
// getRequestLogger creates a zap.Logger using the request remote ip.
|
||||
func getRequestLogger(r *http.Request, behindProxy bool) *zap.Logger {
|
||||
// Retrieve the real client IP address using the updated helper function
|
||||
remoteAddr := getRealRemoteIP(r, behindProxy)
|
||||
|
||||
return zap.L().With(zap.String("remote_address", remoteAddr))
|
||||
}
|
||||
|
||||
// getRealRemoteIP retrieves the client's actual IP address, considering reverse proxies.
|
||||
func getRealRemoteIP(r *http.Request, behindProxy bool) string {
|
||||
if behindProxy {
|
||||
if ip := r.Header.Get("X-Forwarded-For"); ip != "" {
|
||||
return ip
|
||||
}
|
||||
}
|
||||
return r.RemoteAddr
|
||||
}
|
||||
|
||||
type responseWriterNoBody struct {
|
||||
http.ResponseWriter
|
||||
}
|
||||
|
||||
func (w responseWriterNoBody) Write(data []byte) (int, error) {
|
||||
return 0, nil
|
||||
return len(data), nil
|
||||
}
|
||||
|
||||
+529
-1
@@ -2,10 +2,13 @@ package lib
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"sort"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -82,6 +85,404 @@ func TestServerDefaults(t *testing.T) {
|
||||
require.ErrorContains(t, client.Write("/foo.txt", []byte("hello world 2"), 0666), "403")
|
||||
}
|
||||
|
||||
func TestServerPartialUpdateOptions(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := makeTestDirectory(t, map[string][]byte{
|
||||
"foo.txt": []byte("hello world"),
|
||||
})
|
||||
srv := makeTestServer(t, "directory: "+dir+"\npermissions: CRUD")
|
||||
defer srv.Close()
|
||||
|
||||
req, err := http.NewRequest(http.MethodOptions, srv.URL+"/foo.txt", nil)
|
||||
require.NoError(t, err)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
require.Contains(t, resp.Header.Get("DAV"), "sabredav-partialupdate")
|
||||
require.Contains(t, resp.Header.Get("Allow"), "PATCH")
|
||||
require.Equal(t, partialUpdateContentType, resp.Header.Get("Accept-Patch"))
|
||||
}
|
||||
|
||||
func TestServerPatchPartialUpdate(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
initialData string
|
||||
body string
|
||||
updateRange string
|
||||
wantData string
|
||||
}{{
|
||||
name: "start",
|
||||
initialData: "hello world",
|
||||
body: "DAV",
|
||||
updateRange: "bytes=6-",
|
||||
wantData: "hello DAVld",
|
||||
}, {
|
||||
name: "suffix",
|
||||
initialData: "hello world",
|
||||
body: "DAV",
|
||||
updateRange: "bytes=-5",
|
||||
wantData: "hello DAVld",
|
||||
}, {
|
||||
name: "append",
|
||||
initialData: "hello",
|
||||
body: " world",
|
||||
updateRange: "append",
|
||||
wantData: "hello world",
|
||||
}, {
|
||||
name: "suffix_zero",
|
||||
initialData: "hello",
|
||||
body: " world",
|
||||
updateRange: "bytes=-0",
|
||||
wantData: "hello world",
|
||||
}}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := makeTestDirectory(t, map[string][]byte{
|
||||
"foo.txt": []byte(tc.initialData),
|
||||
})
|
||||
srv := makeTestServer(t, "directory: "+dir+"\npermissions: CRUD")
|
||||
defer srv.Close()
|
||||
|
||||
req, err := http.NewRequest("PATCH", srv.URL+"/foo.txt", strings.NewReader(tc.body))
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Content-Type", partialUpdateContentType)
|
||||
req.Header.Set("X-Update-Range", tc.updateRange)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
require.Equal(t, http.StatusNoContent, resp.StatusCode)
|
||||
data, err := os.ReadFile(filepath.Join(dir, "foo.txt"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tc.wantData, string(data))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerPatchPartialUpdateCreatesSparseFile(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := makeTestDirectory(t, nil)
|
||||
srv := makeTestServer(t, "directory: "+dir+"\npermissions: CRUD")
|
||||
defer srv.Close()
|
||||
|
||||
req, err := http.NewRequest("PATCH", srv.URL+"/new.bin", strings.NewReader("x"))
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Content-Type", partialUpdateContentType)
|
||||
req.Header.Set("X-Update-Range", "bytes=3-")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
require.Equal(t, http.StatusCreated, resp.StatusCode)
|
||||
data, err := os.ReadFile(filepath.Join(dir, "new.bin"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, []byte{0, 0, 0, 'x'}, data)
|
||||
}
|
||||
|
||||
func TestServerPutContentRangePartialUpdate(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := makeTestDirectory(t, map[string][]byte{
|
||||
"foo.txt": []byte("hello world"),
|
||||
})
|
||||
srv := makeTestServer(t, "directory: "+dir+"\npermissions: CRUD")
|
||||
defer srv.Close()
|
||||
|
||||
req, err := http.NewRequest(http.MethodPut, srv.URL+"/foo.txt", strings.NewReader("DAV"))
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Content-Range", "bytes 6-8/*")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
_, _ = io.Copy(io.Discard, resp.Body)
|
||||
|
||||
require.Equal(t, http.StatusNoContent, resp.StatusCode)
|
||||
data, err := os.ReadFile(filepath.Join(dir, "foo.txt"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "hello DAVld", string(data))
|
||||
}
|
||||
|
||||
func TestServerPartialUpdateErrors(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
method string
|
||||
body string
|
||||
contentLength int64
|
||||
path string
|
||||
headerName string
|
||||
updateRange string
|
||||
contentRange string
|
||||
wantStatus int
|
||||
}{{
|
||||
name: "patch_missing_content_length",
|
||||
method: "PATCH",
|
||||
body: "DAV",
|
||||
contentLength: -1,
|
||||
updateRange: "bytes=6-8",
|
||||
wantStatus: http.StatusLengthRequired,
|
||||
}, {
|
||||
name: "patch_invalid_range",
|
||||
method: "PATCH",
|
||||
body: "DAV",
|
||||
updateRange: "bytes=8-6",
|
||||
wantStatus: http.StatusRequestedRangeNotSatisfiable,
|
||||
}, {
|
||||
name: "patch_length_mismatch",
|
||||
method: "PATCH",
|
||||
body: "TOOLONG",
|
||||
updateRange: "bytes=6-8",
|
||||
wantStatus: http.StatusRequestedRangeNotSatisfiable,
|
||||
}, {
|
||||
name: "put_content_range_length_mismatch",
|
||||
method: http.MethodPut,
|
||||
body: "TOOLONG",
|
||||
contentLength: -1,
|
||||
contentRange: "bytes 6-8/*",
|
||||
wantStatus: http.StatusRequestedRangeNotSatisfiable,
|
||||
}, {
|
||||
name: "if_none_match",
|
||||
method: "PATCH",
|
||||
body: "DAV",
|
||||
headerName: "If-None-Match",
|
||||
updateRange: "bytes=0-2",
|
||||
wantStatus: http.StatusPreconditionFailed,
|
||||
}, {
|
||||
name: "if_match",
|
||||
method: "PATCH",
|
||||
path: "/missing.txt",
|
||||
body: "DAV",
|
||||
headerName: "If-Match",
|
||||
updateRange: "bytes=0-2",
|
||||
wantStatus: http.StatusPreconditionFailed,
|
||||
}}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := makeTestDirectory(t, map[string][]byte{
|
||||
"foo.txt": []byte("hello world"),
|
||||
})
|
||||
srv := makeTestServer(t, "directory: "+dir+"\npermissions: CRUD")
|
||||
defer srv.Close()
|
||||
|
||||
var body io.Reader = strings.NewReader(tc.body)
|
||||
if tc.contentLength < 0 {
|
||||
body = io.NopCloser(strings.NewReader(tc.body))
|
||||
}
|
||||
path := tc.path
|
||||
if path == "" {
|
||||
path = "/foo.txt"
|
||||
}
|
||||
req, err := http.NewRequest(tc.method, srv.URL+path, body)
|
||||
require.NoError(t, err)
|
||||
if tc.contentLength < 0 {
|
||||
req.ContentLength = tc.contentLength
|
||||
}
|
||||
if tc.method == "PATCH" {
|
||||
req.Header.Set("Content-Type", partialUpdateContentType)
|
||||
req.Header.Set("X-Update-Range", tc.updateRange)
|
||||
}
|
||||
if tc.contentRange != "" {
|
||||
req.Header.Set("Content-Range", tc.contentRange)
|
||||
}
|
||||
if tc.headerName != "" {
|
||||
req.Header.Set(tc.headerName, "*")
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
require.Equal(t, tc.wantStatus, resp.StatusCode)
|
||||
data, err := os.ReadFile(filepath.Join(dir, "foo.txt"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "hello world", string(data))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerPartialUpdateETagPreconditions(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
method string
|
||||
headerName string
|
||||
headerValue func(string) string
|
||||
contentRange string
|
||||
wantStatus int
|
||||
wantData string
|
||||
}{{
|
||||
name: "if_match_matches",
|
||||
method: "PATCH",
|
||||
headerName: "If-Match",
|
||||
headerValue: func(etag string) string { return etag },
|
||||
wantStatus: http.StatusNoContent,
|
||||
wantData: "hello DAVld",
|
||||
}, {
|
||||
name: "if_match_mismatch",
|
||||
method: "PATCH",
|
||||
headerName: "If-Match",
|
||||
headerValue: func(string) string { return `"definitely-wrong"` },
|
||||
wantStatus: http.StatusPreconditionFailed,
|
||||
wantData: "hello world",
|
||||
}, {
|
||||
name: "if_match_list_matches",
|
||||
method: "PATCH",
|
||||
headerName: "If-Match",
|
||||
headerValue: func(etag string) string { return `"definitely-wrong", ` + etag },
|
||||
wantStatus: http.StatusNoContent,
|
||||
wantData: "hello DAVld",
|
||||
}, {
|
||||
name: "if_none_match_matches",
|
||||
method: "PATCH",
|
||||
headerName: "If-None-Match",
|
||||
headerValue: func(etag string) string { return etag },
|
||||
wantStatus: http.StatusPreconditionFailed,
|
||||
wantData: "hello world",
|
||||
}, {
|
||||
name: "if_none_match_mismatch",
|
||||
method: "PATCH",
|
||||
headerName: "If-None-Match",
|
||||
headerValue: func(string) string { return `"definitely-wrong"` },
|
||||
wantStatus: http.StatusNoContent,
|
||||
wantData: "hello DAVld",
|
||||
}, {
|
||||
name: "put_content_range_if_match_mismatch",
|
||||
method: http.MethodPut,
|
||||
headerName: "If-Match",
|
||||
headerValue: func(string) string { return `"definitely-wrong"` },
|
||||
contentRange: "bytes 6-8/*",
|
||||
wantStatus: http.StatusPreconditionFailed,
|
||||
wantData: "hello world",
|
||||
}}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := makeTestDirectory(t, map[string][]byte{
|
||||
"foo.txt": []byte("hello world"),
|
||||
})
|
||||
srv := makeTestServer(t, "directory: "+dir+"\npermissions: CRUD")
|
||||
defer srv.Close()
|
||||
|
||||
req, err := http.NewRequest(http.MethodHead, srv.URL+"/foo.txt", nil)
|
||||
require.NoError(t, err)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
_ = resp.Body.Close()
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
etag := resp.Header.Get("ETag")
|
||||
require.NotEmpty(t, etag)
|
||||
|
||||
req, err = http.NewRequest(tc.method, srv.URL+"/foo.txt", strings.NewReader("DAV"))
|
||||
require.NoError(t, err)
|
||||
if tc.method == "PATCH" {
|
||||
req.Header.Set("Content-Type", partialUpdateContentType)
|
||||
req.Header.Set("X-Update-Range", "bytes=6-8")
|
||||
}
|
||||
if tc.contentRange != "" {
|
||||
req.Header.Set("Content-Range", tc.contentRange)
|
||||
}
|
||||
req.Header.Set(tc.headerName, tc.headerValue(etag))
|
||||
resp, err = http.DefaultClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
|
||||
require.Equal(t, tc.wantStatus, resp.StatusCode)
|
||||
data, err := os.ReadFile(filepath.Join(dir, "foo.txt"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, tc.wantData, string(data))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerPartialUpdateHonorsLocks(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
const createLockBody = `<?xml version="1.0" encoding="utf-8" ?>
|
||||
<D:lockinfo xmlns:D='DAV:'>
|
||||
<D:lockscope><D:exclusive/></D:lockscope>
|
||||
<D:locktype><D:write/></D:locktype>
|
||||
<D:owner>test</D:owner>
|
||||
</D:lockinfo>`
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
lockPath string
|
||||
depth string
|
||||
ifPath string
|
||||
}{{
|
||||
name: "file",
|
||||
lockPath: "/foo.txt",
|
||||
depth: "0",
|
||||
ifPath: "/foo.txt",
|
||||
}, {
|
||||
name: "root",
|
||||
lockPath: "/",
|
||||
depth: "infinity",
|
||||
ifPath: "/",
|
||||
}}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := makeTestDirectory(t, map[string][]byte{
|
||||
"foo.txt": []byte("hello world"),
|
||||
})
|
||||
srv := makeTestServer(t, "directory: "+dir+"\npermissions: CRUD")
|
||||
defer srv.Close()
|
||||
|
||||
req, err := http.NewRequest("LOCK", srv.URL+tc.lockPath, strings.NewReader(createLockBody))
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Content-Type", "application/xml")
|
||||
req.Header.Set("Depth", tc.depth)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
_, _ = io.Copy(io.Discard, resp.Body)
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode)
|
||||
lockToken := resp.Header.Get("Lock-Token")
|
||||
|
||||
req, err = http.NewRequest("PATCH", srv.URL+"/foo.txt", strings.NewReader("DAV"))
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Content-Type", partialUpdateContentType)
|
||||
req.Header.Set("X-Update-Range", "bytes=6-8")
|
||||
resp, err = http.DefaultClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
require.Equal(t, 423, resp.StatusCode)
|
||||
|
||||
req, err = http.NewRequest("PATCH", srv.URL+"/foo.txt", strings.NewReader("DAV"))
|
||||
require.NoError(t, err)
|
||||
req.Header.Set("Content-Type", partialUpdateContentType)
|
||||
req.Header.Set("X-Update-Range", "bytes=6-8")
|
||||
req.Header.Set("If", fmt.Sprintf("<%s%s> (%s)", srv.URL, tc.ifPath, lockToken))
|
||||
resp, err = http.DefaultClient.Do(req)
|
||||
require.NoError(t, err)
|
||||
defer func() { _ = resp.Body.Close() }()
|
||||
require.Equal(t, http.StatusNoContent, resp.StatusCode)
|
||||
|
||||
data, err := os.ReadFile(filepath.Join(dir, "foo.txt"))
|
||||
require.NoError(t, err)
|
||||
require.Equal(t, "hello DAVld", string(data))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerListingCharacters(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
@@ -217,7 +618,7 @@ users:
|
||||
})
|
||||
}
|
||||
|
||||
func TestServerRules(t *testing.T) {
|
||||
func TestServerRulesRestrictive(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := makeTestDirectory(t, map[string][]byte{
|
||||
@@ -290,6 +691,133 @@ users:
|
||||
|
||||
err = client.Write("/c/b.txt", []byte("new"), 0666)
|
||||
require.ErrorContains(t, err, "403")
|
||||
|
||||
err = client.MkdirAll("/d/foo/bar", 0666)
|
||||
require.NoError(t, err)
|
||||
|
||||
err = client.Write("/d/foo/bar/test.txt", []byte("test"), 0666)
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestServerRulesAdditive(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := makeTestDirectory(t, map[string][]byte{
|
||||
"foo.txt": []byte("foo"),
|
||||
"bar.js": []byte("foo js"),
|
||||
"a/foo.js": []byte("foo js"),
|
||||
"a/foo.txt": []byte("foo txt"),
|
||||
"b/foo.txt": []byte("foo b"),
|
||||
})
|
||||
|
||||
srv := makeTestServer(t, fmt.Sprintf(`
|
||||
directory: %s
|
||||
permissions: none
|
||||
|
||||
users:
|
||||
- username: basic
|
||||
password: basic
|
||||
rules:
|
||||
- regex: "^.+.js$"
|
||||
permissions: R
|
||||
- path: "/a/foo.txt"
|
||||
permissions: CRU
|
||||
- path: "/b/"
|
||||
permissions: D
|
||||
`, dir))
|
||||
|
||||
client := gowebdav.NewClient(srv.URL, "basic", "basic")
|
||||
|
||||
_, err := client.ReadDir("/")
|
||||
require.ErrorContains(t, err, "403")
|
||||
|
||||
err = client.Write("/foo.txt", []byte("new"), 0666)
|
||||
require.ErrorContains(t, err, "403")
|
||||
|
||||
err = client.Write("/new.txt", []byte("new"), 0666)
|
||||
require.ErrorContains(t, err, "403")
|
||||
|
||||
err = client.Copy("/bar.js", "/a/foo.txt", true)
|
||||
require.NoError(t, err)
|
||||
|
||||
err = client.Remove("/b/foo.txt")
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
func TestServerRulesPrefix(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
dir := makeTestDirectory(t, map[string][]byte{
|
||||
"foo.txt": []byte("foo"),
|
||||
"bar.js": []byte("foo js"),
|
||||
"a/foo.js": []byte("foo js"),
|
||||
"a/foo.txt": []byte("foo txt"),
|
||||
"b/foo.txt": []byte("foo b"),
|
||||
"c/a.txt": []byte("b"),
|
||||
"c/b.txt": []byte("b"),
|
||||
"c/c.txt": []byte("b"),
|
||||
})
|
||||
|
||||
srv := makeTestServer(t, fmt.Sprintf(`
|
||||
directory: %s
|
||||
permissions: CRUD
|
||||
prefix: /prefix
|
||||
|
||||
users:
|
||||
- username: basic
|
||||
password: basic
|
||||
rules:
|
||||
- regex: "^.+.js$"
|
||||
permissions: R
|
||||
- path: "/b/"
|
||||
permissions: R
|
||||
- path: "/a/foo.txt"
|
||||
permissions: none
|
||||
- path: "/c/"
|
||||
permissions: none
|
||||
`, dir))
|
||||
|
||||
client := gowebdav.NewClient(srv.URL, "basic", "basic")
|
||||
|
||||
files, err := client.ReadDir("/prefix")
|
||||
require.NoError(t, err)
|
||||
require.Len(t, files, 5)
|
||||
|
||||
err = client.Write("/prefix/foo.txt", []byte("new"), 0666)
|
||||
require.NoError(t, err)
|
||||
|
||||
err = client.Write("/prefix/new.txt", []byte("new"), 0666)
|
||||
require.NoError(t, err)
|
||||
|
||||
err = client.Copy("/prefix/bar.js", "/prefix/b/bar.js", false)
|
||||
require.ErrorContains(t, err, "403")
|
||||
|
||||
err = client.Copy("/prefix/bar.js", "/prefix/bar.jsx", false)
|
||||
require.NoError(t, err)
|
||||
|
||||
err = client.Copy("/prefix/b/foo.txt", "/prefix/foo1.txt", false)
|
||||
require.NoError(t, err)
|
||||
|
||||
err = client.Rename("/prefix/b/foo.txt", "/prefix/foo2.txt", false)
|
||||
require.ErrorContains(t, err, "403")
|
||||
|
||||
_, err = client.Read("/prefix/a/foo.txt")
|
||||
require.ErrorContains(t, err, "403")
|
||||
|
||||
err = client.Write("/prefix/a/foo.js", []byte("new"), 0666)
|
||||
require.ErrorContains(t, err, "403")
|
||||
|
||||
err = client.Write("/prefix/b/foo.txt", []byte("new"), 0666)
|
||||
require.ErrorContains(t, err, "403")
|
||||
|
||||
_, err = client.ReadDir("/prefix/c")
|
||||
require.ErrorContains(t, err, "403")
|
||||
|
||||
_, err = client.Read("/prefix/c/a.txt")
|
||||
require.ErrorContains(t, err, "403")
|
||||
|
||||
err = client.Write("/prefix/c/b.txt", []byte("new"), 0666)
|
||||
require.ErrorContains(t, err, "403")
|
||||
}
|
||||
|
||||
func TestServerPermissions(t *testing.T) {
|
||||
|
||||
@@ -0,0 +1,35 @@
|
||||
package lib
|
||||
|
||||
import (
|
||||
"path/filepath"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/webdav"
|
||||
)
|
||||
|
||||
var _ webdav.LockSystem = &lockSystem{}
|
||||
|
||||
// LockSystem wraps a [webdav.LockSystem] with a root directory, allowing
|
||||
// to reuse the same [webdav.LockSystem] for multiple users with different base
|
||||
// directories, meaning we can correctly lock the files across different users.
|
||||
type lockSystem struct {
|
||||
webdav.LockSystem
|
||||
directory string
|
||||
}
|
||||
|
||||
func (l *lockSystem) Confirm(now time.Time, name0, name1 string, conditions ...webdav.Condition) (release func(), err error) {
|
||||
if name0 != "" {
|
||||
name0 = filepath.Join(l.directory, name0)
|
||||
}
|
||||
|
||||
if name1 != "" {
|
||||
name1 = filepath.Join(l.directory, name1)
|
||||
}
|
||||
|
||||
return l.LockSystem.Confirm(now, name0, name1, conditions...)
|
||||
}
|
||||
|
||||
func (l *lockSystem) Create(now time.Time, details webdav.LockDetails) (token string, err error) {
|
||||
details.Root = filepath.Join(l.directory, details.Root)
|
||||
return l.LockSystem.Create(now, details)
|
||||
}
|
||||
@@ -0,0 +1,526 @@
|
||||
package lib
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"golang.org/x/net/webdav"
|
||||
)
|
||||
|
||||
const partialUpdateContentType = "application/x-sabredav-partialupdate"
|
||||
|
||||
type updateRange struct {
|
||||
offset int64
|
||||
end int64
|
||||
hasEnd bool
|
||||
append bool
|
||||
}
|
||||
|
||||
type partialUpdateError struct {
|
||||
status int
|
||||
err error
|
||||
}
|
||||
|
||||
func (e partialUpdateError) Error() string {
|
||||
return e.err.Error()
|
||||
}
|
||||
|
||||
func newPartialUpdateError(status int, message string) error {
|
||||
return partialUpdateError{status: status, err: errors.New(message)}
|
||||
}
|
||||
|
||||
func writePartialUpdateError(w http.ResponseWriter, err error, fallbackStatus int) {
|
||||
var httpErr partialUpdateError
|
||||
if errors.As(err, &httpErr) {
|
||||
fallbackStatus = httpErr.status
|
||||
}
|
||||
http.Error(w, err.Error(), fallbackStatus)
|
||||
}
|
||||
|
||||
func (u *handlerUser) handleOptions(w http.ResponseWriter, r *http.Request, reqPath string) {
|
||||
allow := "OPTIONS, LOCK, PUT, MKCOL, PATCH"
|
||||
if fi, err := u.FileSystem.Stat(r.Context(), reqPath); err == nil {
|
||||
if fi.IsDir() {
|
||||
allow = "OPTIONS, LOCK, DELETE, PROPPATCH, COPY, MOVE, UNLOCK, PROPFIND"
|
||||
} else {
|
||||
allow = "OPTIONS, LOCK, GET, HEAD, POST, DELETE, PROPPATCH, COPY, MOVE, UNLOCK, PROPFIND, PUT, PATCH"
|
||||
}
|
||||
}
|
||||
|
||||
w.Header().Set("Allow", allow)
|
||||
w.Header().Set("DAV", "1, 2, sabredav-partialupdate")
|
||||
w.Header().Set("MS-Author-Via", "DAV")
|
||||
w.Header().Set("Accept-Patch", partialUpdateContentType)
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
|
||||
func (u *handlerUser) handlePartialUpdate(w http.ResponseWriter, r *http.Request, reqPath string) {
|
||||
contentRange := r.Header.Get("Content-Range")
|
||||
isContentRangePut := r.Method == "PUT" && contentRange != ""
|
||||
|
||||
var (
|
||||
updateRange updateRange
|
||||
err error
|
||||
)
|
||||
if isContentRangePut {
|
||||
updateRange, err = parseContentRange(contentRange)
|
||||
} else {
|
||||
if err := checkPartialUpdateContentType(r.Header.Get("Content-Type")); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusUnsupportedMediaType)
|
||||
return
|
||||
}
|
||||
updateRange, err = parseUpdateRange(r.Header.Get("X-Update-Range"))
|
||||
}
|
||||
if err != nil {
|
||||
writePartialUpdateError(w, err, http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
if r.Method == "PATCH" && r.ContentLength < 0 {
|
||||
http.Error(w, "missing content length", http.StatusLengthRequired)
|
||||
return
|
||||
}
|
||||
|
||||
release, status, err := u.confirmPartialUpdateLocks(r, reqPath)
|
||||
if err != nil {
|
||||
http.Error(w, err.Error(), status)
|
||||
return
|
||||
}
|
||||
defer release()
|
||||
|
||||
ctx := r.Context()
|
||||
fi, statErr := u.FileSystem.Stat(ctx, reqPath)
|
||||
exists := statErr == nil
|
||||
if statErr != nil && !os.IsNotExist(statErr) {
|
||||
http.Error(w, statErr.Error(), http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
if exists && fi.IsDir() {
|
||||
http.Error(w, "cannot update a collection", http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
etag, status, err := u.checkPartialUpdatePreconditions(r, exists, fi)
|
||||
if err != nil {
|
||||
if etag != "" {
|
||||
w.Header().Set("ETag", etag)
|
||||
}
|
||||
http.Error(w, err.Error(), status)
|
||||
return
|
||||
}
|
||||
|
||||
currentSize := int64(0)
|
||||
if exists {
|
||||
currentSize = fi.Size()
|
||||
}
|
||||
if updateRange.append {
|
||||
updateRange.offset = currentSize
|
||||
} else if updateRange.offset < 0 {
|
||||
updateRange.offset += currentSize
|
||||
if updateRange.offset < 0 {
|
||||
updateRange.offset = 0
|
||||
}
|
||||
}
|
||||
|
||||
if updateRange.hasEnd {
|
||||
expected := updateRange.end - updateRange.offset + 1
|
||||
if expected < 0 {
|
||||
http.Error(w, "invalid byte range", http.StatusRequestedRangeNotSatisfiable)
|
||||
return
|
||||
}
|
||||
if r.ContentLength >= 0 && r.ContentLength != expected {
|
||||
http.Error(w, "content length does not match byte range", http.StatusRequestedRangeNotSatisfiable)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
body := io.Reader(r.Body)
|
||||
var cleanup func()
|
||||
if updateRange.hasEnd {
|
||||
body, cleanup, err = spoolBoundedBody(r.Body, updateRange.end-updateRange.offset+1)
|
||||
if err != nil {
|
||||
writePartialUpdateError(w, err, http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
defer cleanup()
|
||||
}
|
||||
|
||||
flag := os.O_RDWR
|
||||
if !exists {
|
||||
flag |= os.O_CREATE
|
||||
}
|
||||
f, err := u.FileSystem.OpenFile(ctx, reqPath, flag, 0666)
|
||||
if err != nil {
|
||||
if os.IsNotExist(err) {
|
||||
http.Error(w, err.Error(), http.StatusConflict)
|
||||
return
|
||||
}
|
||||
http.Error(w, err.Error(), http.StatusNotFound)
|
||||
return
|
||||
}
|
||||
defer func() { _ = f.Close() }()
|
||||
|
||||
if _, err := f.Seek(updateRange.offset, io.SeekStart); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
if _, err := io.Copy(f, body); err != nil {
|
||||
http.Error(w, err.Error(), http.StatusMethodNotAllowed)
|
||||
return
|
||||
}
|
||||
|
||||
if !exists {
|
||||
w.WriteHeader(http.StatusCreated)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func checkPartialUpdateContentType(contentType string) error {
|
||||
if contentType == "" {
|
||||
return errors.New("missing content type")
|
||||
}
|
||||
mediaType, _, err := mime.ParseMediaType(contentType)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if mediaType != partialUpdateContentType {
|
||||
return fmt.Errorf("unsupported content type %q", mediaType)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (u *handlerUser) checkPartialUpdatePreconditions(r *http.Request, exists bool, fi os.FileInfo) (etag string, status int, err error) {
|
||||
ifMatch := r.Header.Get("If-Match")
|
||||
ifNoneMatch := r.Header.Get("If-None-Match")
|
||||
if ifMatch == "" && ifNoneMatch == "" {
|
||||
return "", 0, nil
|
||||
}
|
||||
|
||||
if ifMatch != "" && !exists {
|
||||
return "", http.StatusPreconditionFailed, errors.New("resource does not exist")
|
||||
}
|
||||
|
||||
if exists {
|
||||
etag, err = findPartialETag(r.Context(), fi)
|
||||
if err != nil {
|
||||
return "", http.StatusInternalServerError, err
|
||||
}
|
||||
}
|
||||
|
||||
if ifMatch != "" && !partialETagHeaderMatches(ifMatch, etag, exists) {
|
||||
return etag, http.StatusPreconditionFailed, errors.New("etag does not match")
|
||||
}
|
||||
|
||||
if ifNoneMatch != "" && exists && partialETagHeaderMatches(ifNoneMatch, etag, true) {
|
||||
return etag, http.StatusPreconditionFailed, errors.New("etag matches")
|
||||
}
|
||||
|
||||
return etag, 0, nil
|
||||
}
|
||||
|
||||
func findPartialETag(ctx context.Context, fi os.FileInfo) (string, error) {
|
||||
if etager, ok := fi.(webdav.ETager); ok {
|
||||
etag, err := etager.ETag(ctx)
|
||||
if !errors.Is(err, webdav.ErrNotImplemented) {
|
||||
return etag, err
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf(`"%x%x"`, fi.ModTime().UnixNano(), fi.Size()), nil
|
||||
}
|
||||
|
||||
func partialETagHeaderMatches(header, etag string, exists bool) bool {
|
||||
for _, item := range strings.Split(header, ",") {
|
||||
item = strings.TrimSpace(item)
|
||||
if item == "*" {
|
||||
return exists
|
||||
}
|
||||
if item == etag || strings.ReplaceAll(item, `\"`, `"`) == etag {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func parseUpdateRange(header string) (updateRange, error) {
|
||||
if header == "" {
|
||||
return updateRange{}, errors.New("missing X-Update-Range header")
|
||||
}
|
||||
if header == "append" {
|
||||
return updateRange{append: true}, nil
|
||||
}
|
||||
if !strings.HasPrefix(header, "bytes=") {
|
||||
return updateRange{}, errors.New("invalid X-Update-Range header")
|
||||
}
|
||||
return parseByteRange(strings.TrimPrefix(header, "bytes="), true)
|
||||
}
|
||||
|
||||
func parseContentRange(header string) (updateRange, error) {
|
||||
if !strings.HasPrefix(header, "bytes ") {
|
||||
return updateRange{}, errors.New("invalid Content-Range header")
|
||||
}
|
||||
spec, _, ok := strings.Cut(strings.TrimPrefix(header, "bytes "), "/")
|
||||
if !ok {
|
||||
return updateRange{}, errors.New("invalid Content-Range header")
|
||||
}
|
||||
return parseByteRange(spec, false)
|
||||
}
|
||||
|
||||
func parseByteRange(spec string, allowNegativeStart bool) (updateRange, error) {
|
||||
if strings.HasPrefix(spec, "-") {
|
||||
if !allowNegativeStart {
|
||||
return updateRange{}, errors.New("invalid byte range start")
|
||||
}
|
||||
start, err := strconv.ParseInt(strings.TrimPrefix(spec, "-"), 10, 64)
|
||||
if err != nil || start < 0 {
|
||||
return updateRange{}, errors.New("invalid byte range start")
|
||||
}
|
||||
if start == 0 {
|
||||
return updateRange{append: true}, nil
|
||||
}
|
||||
return updateRange{offset: -start}, nil
|
||||
}
|
||||
|
||||
startText, endText, ok := strings.Cut(spec, "-")
|
||||
if !ok || startText == "" {
|
||||
return updateRange{}, errors.New("invalid byte range")
|
||||
}
|
||||
|
||||
start, err := strconv.ParseInt(startText, 10, 64)
|
||||
if err != nil {
|
||||
return updateRange{}, errors.New("invalid byte range start")
|
||||
}
|
||||
if start < 0 && !allowNegativeStart {
|
||||
return updateRange{}, errors.New("invalid byte range start")
|
||||
}
|
||||
|
||||
r := updateRange{offset: start}
|
||||
if endText == "" {
|
||||
return r, nil
|
||||
}
|
||||
if start < 0 {
|
||||
return updateRange{}, errors.New("negative byte range cannot include an end")
|
||||
}
|
||||
|
||||
end, err := strconv.ParseInt(endText, 10, 64)
|
||||
if err != nil {
|
||||
return updateRange{}, errors.New("invalid byte range end")
|
||||
}
|
||||
if end < start {
|
||||
return updateRange{}, newPartialUpdateError(http.StatusRequestedRangeNotSatisfiable, "invalid byte range")
|
||||
}
|
||||
r.end = end
|
||||
r.hasEnd = true
|
||||
return r, nil
|
||||
}
|
||||
|
||||
func spoolBoundedBody(body io.Reader, expected int64) (io.Reader, func(), error) {
|
||||
tmp, err := os.CreateTemp("", "webdav-partial-update-*")
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
cleanup := func() {
|
||||
name := tmp.Name()
|
||||
_ = tmp.Close()
|
||||
_ = os.Remove(name)
|
||||
}
|
||||
cleanupOnError := true
|
||||
defer func() {
|
||||
if cleanupOnError {
|
||||
cleanup()
|
||||
}
|
||||
}()
|
||||
|
||||
n, err := io.Copy(tmp, io.LimitReader(body, expected+1))
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
if n != expected {
|
||||
return nil, nil, newPartialUpdateError(http.StatusRequestedRangeNotSatisfiable, "body length does not match byte range")
|
||||
}
|
||||
|
||||
if _, err := tmp.Seek(0, io.SeekStart); err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
cleanupOnError = false
|
||||
return tmp, cleanup, nil
|
||||
}
|
||||
|
||||
// confirmPartialUpdateLocks mirrors the unexported confirmLocks helper from
|
||||
// golang.org/x/net/webdav so that partial updates honor WebDAV locks the same
|
||||
// way regular PUT requests do. Keep it in sync if the upstream behavior changes.
|
||||
func (u *handlerUser) confirmPartialUpdateLocks(r *http.Request, src string) (release func(), status int, err error) {
|
||||
hdr := r.Header.Get("If")
|
||||
if hdr == "" {
|
||||
now := time.Now()
|
||||
token, err := u.LockSystem.Create(now, webdav.LockDetails{
|
||||
Root: src,
|
||||
Duration: -1,
|
||||
ZeroDepth: true,
|
||||
})
|
||||
if err != nil {
|
||||
if errors.Is(err, webdav.ErrLocked) {
|
||||
return nil, webdav.StatusLocked, err
|
||||
}
|
||||
return nil, http.StatusInternalServerError, err
|
||||
}
|
||||
return func() {
|
||||
_ = u.LockSystem.Unlock(now, token)
|
||||
}, 0, nil
|
||||
}
|
||||
|
||||
ifLists, ok := parsePartialIfHeader(hdr)
|
||||
if !ok {
|
||||
return nil, http.StatusBadRequest, errors.New("webdav: invalid If header")
|
||||
}
|
||||
for _, l := range ifLists {
|
||||
lsrc := l.resourceTag
|
||||
if lsrc == "" {
|
||||
lsrc = src
|
||||
} else {
|
||||
parsedURL, err := url.Parse(lsrc)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
if parsedURL.Host != r.Host {
|
||||
continue
|
||||
}
|
||||
lsrc, err = stripPartialPrefix(parsedURL.Path, u.Prefix)
|
||||
if err != nil {
|
||||
return nil, http.StatusNotFound, err
|
||||
}
|
||||
if lsrc == "" {
|
||||
lsrc = src
|
||||
}
|
||||
}
|
||||
release, err = u.LockSystem.Confirm(time.Now(), lsrc, "", l.conditions...)
|
||||
if errors.Is(err, webdav.ErrConfirmationFailed) {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return nil, http.StatusInternalServerError, err
|
||||
}
|
||||
return release, 0, nil
|
||||
}
|
||||
return nil, http.StatusPreconditionFailed, webdav.ErrLocked
|
||||
}
|
||||
|
||||
type partialIfList struct {
|
||||
resourceTag string
|
||||
conditions []webdav.Condition
|
||||
}
|
||||
|
||||
// parsePartialIfHeader, parsePartialIfConditions and cutPartialIfToken
|
||||
// reimplement the unexported If-header parser from golang.org/x/net/webdav,
|
||||
// which is not accessible from outside that package. Keep them in sync with the
|
||||
// upstream parseIfHeader if it changes.
|
||||
func parsePartialIfHeader(header string) ([]partialIfList, bool) {
|
||||
s := strings.TrimSpace(header)
|
||||
tagged := strings.HasPrefix(s, "<")
|
||||
var lists []partialIfList
|
||||
for s != "" {
|
||||
resourceTag := ""
|
||||
if strings.HasPrefix(s, "<") {
|
||||
if !tagged {
|
||||
return nil, false
|
||||
}
|
||||
var ok bool
|
||||
resourceTag, s, ok = cutPartialIfToken(s, '<', '>')
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
s = strings.TrimSpace(s)
|
||||
if !strings.HasPrefix(s, "(") {
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
for strings.HasPrefix(s, "(") {
|
||||
body, rest, ok := cutPartialIfToken(s, '(', ')')
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
conditions, ok := parsePartialIfConditions(body)
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
lists = append(lists, partialIfList{resourceTag: resourceTag, conditions: conditions})
|
||||
s = strings.TrimSpace(rest)
|
||||
}
|
||||
if s != "" && !strings.HasPrefix(s, "<") {
|
||||
return nil, false
|
||||
}
|
||||
}
|
||||
return lists, len(lists) > 0
|
||||
}
|
||||
|
||||
func parsePartialIfConditions(s string) ([]webdav.Condition, bool) {
|
||||
var conditions []webdav.Condition
|
||||
for {
|
||||
s = strings.TrimSpace(s)
|
||||
if s == "" {
|
||||
return conditions, len(conditions) > 0
|
||||
}
|
||||
not := false
|
||||
if strings.HasPrefix(s, "Not ") || strings.HasPrefix(s, "Not\t") {
|
||||
not = true
|
||||
s = strings.TrimSpace(s[3:])
|
||||
}
|
||||
if s == "" {
|
||||
return nil, false
|
||||
}
|
||||
var token string
|
||||
switch s[0] {
|
||||
case '<':
|
||||
var ok bool
|
||||
token, s, ok = cutPartialIfToken(s, '<', '>')
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
conditions = append(conditions, webdav.Condition{Not: not, Token: token})
|
||||
case '[':
|
||||
var ok bool
|
||||
token, s, ok = cutPartialIfToken(s, '[', ']')
|
||||
if !ok {
|
||||
return nil, false
|
||||
}
|
||||
conditions = append(conditions, webdav.Condition{Not: not, ETag: token})
|
||||
default:
|
||||
i := strings.IndexAny(s, " \t")
|
||||
if i < 0 {
|
||||
token, s = s, ""
|
||||
} else {
|
||||
token, s = s[:i], s[i:]
|
||||
}
|
||||
if token == "" || strings.ContainsAny(token, "()<>[]") {
|
||||
return nil, false
|
||||
}
|
||||
conditions = append(conditions, webdav.Condition{Not: not, Token: token})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func cutPartialIfToken(s string, open, close byte) (string, string, bool) {
|
||||
if s == "" || s[0] != open {
|
||||
return "", "", false
|
||||
}
|
||||
token, rest, ok := strings.Cut(s[1:], string(close))
|
||||
return token, rest, ok
|
||||
}
|
||||
|
||||
func stripPartialPrefix(p, prefix string) (string, error) {
|
||||
if prefix == "" {
|
||||
return p, nil
|
||||
}
|
||||
if stripped := strings.TrimPrefix(p, prefix); len(stripped) < len(p) {
|
||||
return stripped, nil
|
||||
}
|
||||
return "", errors.New("webdav: prefix mismatch")
|
||||
}
|
||||
+36
-16
@@ -3,7 +3,6 @@ package lib
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path/filepath"
|
||||
"regexp"
|
||||
"strings"
|
||||
@@ -16,6 +15,10 @@ type Rule struct {
|
||||
}
|
||||
|
||||
func (r *Rule) Validate() error {
|
||||
if r.Regex == nil && r.Path == "" {
|
||||
return errors.New("invalid rule: must either define a path of a regex")
|
||||
}
|
||||
|
||||
if r.Regex != nil && r.Path != "" {
|
||||
return errors.New("invalid rule: cannot define both regex and path")
|
||||
}
|
||||
@@ -32,22 +35,32 @@ func (r *Rule) Matches(path string) bool {
|
||||
return strings.HasPrefix(path, r.Path)
|
||||
}
|
||||
|
||||
type RulesBehavior string
|
||||
|
||||
const (
|
||||
RulesOverwrite RulesBehavior = "overwrite"
|
||||
RulesAppend RulesBehavior = "append"
|
||||
)
|
||||
|
||||
type UserPermissions struct {
|
||||
Directory string
|
||||
Permissions Permissions
|
||||
Rules []*Rule
|
||||
Directory string
|
||||
Permissions Permissions
|
||||
Rules []*Rule
|
||||
RulesBehavior RulesBehavior
|
||||
}
|
||||
|
||||
// Allowed checks if the user has permission to access a directory/file
|
||||
func (p UserPermissions) Allowed(r *http.Request, fileExists func(string) bool) bool {
|
||||
func (p UserPermissions) Allowed(r *request, fileExists func(string) bool) bool {
|
||||
// For COPY and MOVE requests, we first check the permissions for the destination
|
||||
// path. As soon as a rule matches and does not allow the operation at the destination,
|
||||
// we fail immediately. If no rule matches, we check the global permissions.
|
||||
if r.Method == "COPY" || r.Method == "MOVE" {
|
||||
dst := r.Header.Get("Destination")
|
||||
if r.method == "COPY" || r.method == "MOVE" {
|
||||
dst := r.destination
|
||||
ruleMatched := false
|
||||
|
||||
for i := len(p.Rules) - 1; i >= 0; i-- {
|
||||
if p.Rules[i].Matches(dst) {
|
||||
ruleMatched = true
|
||||
if !p.Rules[i].Permissions.AllowedDestination(r, fileExists) {
|
||||
return false
|
||||
}
|
||||
@@ -57,7 +70,7 @@ func (p UserPermissions) Allowed(r *http.Request, fileExists func(string) bool)
|
||||
}
|
||||
}
|
||||
|
||||
if !p.Permissions.AllowedDestination(r, fileExists) {
|
||||
if !ruleMatched && !p.Permissions.AllowedDestination(r, fileExists) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
@@ -65,7 +78,7 @@ func (p UserPermissions) Allowed(r *http.Request, fileExists func(string) bool)
|
||||
// Go through rules beginning from the last one, and check the permissions at
|
||||
// the source. The first matched rule returns.
|
||||
for i := len(p.Rules) - 1; i >= 0; i-- {
|
||||
if p.Rules[i].Matches(r.URL.Path) {
|
||||
if p.Rules[i].Matches(r.path) {
|
||||
return p.Rules[i].Permissions.Allowed(r, fileExists)
|
||||
}
|
||||
}
|
||||
@@ -87,6 +100,13 @@ func (p *UserPermissions) Validate() error {
|
||||
}
|
||||
}
|
||||
|
||||
switch p.RulesBehavior {
|
||||
case RulesAppend, RulesOverwrite:
|
||||
// Good to go
|
||||
default:
|
||||
return fmt.Errorf("invalid rule behavior: %s", p.RulesBehavior)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -123,8 +143,8 @@ func (p *Permissions) UnmarshalText(data []byte) error {
|
||||
|
||||
// Allowed returns whether this permission set has permissions to execute this
|
||||
// request in the source directory. This applies to all requests with all methods.
|
||||
func (p Permissions) Allowed(r *http.Request, fileExists func(string) bool) bool {
|
||||
switch r.Method {
|
||||
func (p Permissions) Allowed(r *request, fileExists func(string) bool) bool {
|
||||
switch r.method {
|
||||
case "GET", "HEAD", "OPTIONS", "POST", "PROPFIND":
|
||||
// Note: POST backend implementation just returns the same thing as GET.
|
||||
return p.Read
|
||||
@@ -132,8 +152,8 @@ func (p Permissions) Allowed(r *http.Request, fileExists func(string) bool) bool
|
||||
return p.Create
|
||||
case "PROPPATCH":
|
||||
return p.Update
|
||||
case "PUT":
|
||||
if fileExists(r.URL.Path) {
|
||||
case "PUT", "PATCH":
|
||||
if fileExists(r.path) {
|
||||
return p.Update
|
||||
} else {
|
||||
return p.Create
|
||||
@@ -153,10 +173,10 @@ func (p Permissions) Allowed(r *http.Request, fileExists func(string) bool) bool
|
||||
|
||||
// AllowedDestination returns whether this permissions set has permissions to execute this
|
||||
// request in the destination directory. This only applies for COPY and MOVE requests.
|
||||
func (p Permissions) AllowedDestination(r *http.Request, fileExists func(string) bool) bool {
|
||||
switch r.Method {
|
||||
func (p Permissions) AllowedDestination(r *request, fileExists func(string) bool) bool {
|
||||
switch r.method {
|
||||
case "COPY", "MOVE":
|
||||
if fileExists(r.Header.Get("Destination")) {
|
||||
if fileExists(r.destination) {
|
||||
return p.Update
|
||||
} else {
|
||||
return p.Create
|
||||
|
||||
@@ -0,0 +1,57 @@
|
||||
package lib
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type request struct {
|
||||
method string
|
||||
path string
|
||||
destination string
|
||||
}
|
||||
|
||||
func newRequest(r *http.Request, prefix string) (*request, error) {
|
||||
ctx := &request{
|
||||
method: r.Method,
|
||||
}
|
||||
|
||||
if destination := r.Header.Get("Destination"); destination != "" {
|
||||
u, err := url.Parse(destination)
|
||||
if err != nil {
|
||||
return nil, errors.New("invalid destination header")
|
||||
}
|
||||
|
||||
if prefix != "" {
|
||||
destination = strings.TrimPrefix(u.Path, prefix)
|
||||
if len(destination) >= len(u.Path) {
|
||||
return nil, errors.New("invalid url prefix")
|
||||
}
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(destination, "/") {
|
||||
destination = "/" + destination
|
||||
}
|
||||
|
||||
ctx.destination = destination
|
||||
}
|
||||
|
||||
path := r.URL.Path
|
||||
|
||||
if prefix != "" {
|
||||
path = strings.TrimPrefix(r.URL.Path, prefix)
|
||||
if len(path) >= len(r.URL.Path) {
|
||||
return nil, errors.New("invalid url prefix")
|
||||
}
|
||||
}
|
||||
|
||||
if !strings.HasPrefix(path, "/") {
|
||||
path = "/" + path
|
||||
}
|
||||
|
||||
ctx.path = path
|
||||
|
||||
return ctx, nil
|
||||
}
|
||||
+10
-1
@@ -27,12 +27,21 @@ func (u User) checkPassword(input string) bool {
|
||||
func (u *User) Validate(noPassword bool) error {
|
||||
if u.Username == "" {
|
||||
return errors.New("invalid user: username must be set")
|
||||
} else if strings.HasPrefix(u.Username, "{env}") {
|
||||
env := strings.TrimPrefix(u.Username, "{env}")
|
||||
if env == "" {
|
||||
return fmt.Errorf("invalid user %q: username environment variable not set", u.Username)
|
||||
}
|
||||
|
||||
u.Username = os.Getenv(env)
|
||||
if u.Username == "" {
|
||||
return fmt.Errorf("invalid user %q: username environment variable is empty", u.Username)
|
||||
}
|
||||
}
|
||||
|
||||
if u.Password == "" && !noPassword {
|
||||
return fmt.Errorf("invalid user %q: password must be set", u.Username)
|
||||
} else if strings.HasPrefix(u.Password, "{env}") {
|
||||
|
||||
env := strings.TrimPrefix(u.Password, "{env}")
|
||||
if env == "" {
|
||||
return fmt.Errorf("invalid user %q: password environment variable not set", u.Username)
|
||||
|
||||
@@ -2,6 +2,8 @@ package main
|
||||
|
||||
import (
|
||||
"github.com/hacdias/webdav/v5/cmd"
|
||||
|
||||
_ "golang.org/x/crypto/x509roots/fallback"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"$schema": "https://docs.renovatebot.com/renovate-schema.json",
|
||||
"extends": [
|
||||
"config:recommended",
|
||||
"group:allNonMajor",
|
||||
"group:allDigest",
|
||||
":disableDependencyDashboard",
|
||||
":semanticCommitTypeAll(chore)"
|
||||
],
|
||||
"postUpdateOptions": [
|
||||
"gomodUpdateImportPaths",
|
||||
"gomodTidy"
|
||||
],
|
||||
"schedule": "* * * * 0,6"
|
||||
}
|
||||
Reference in New Issue
Block a user