Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
90134a326f | ||
|
|
22543e6f7f | ||
|
|
9e399df8e4 | ||
|
|
123705aa53 | ||
|
|
28db575c92 | ||
|
|
ba5ad177b7 | ||
|
|
6f8af2cfa4 | ||
|
|
6d32460b13 | ||
|
|
b0dfc1ad74 | ||
|
|
c2a634c13f | ||
|
|
a2887fa6db | ||
|
|
c5b4262a4c | ||
|
|
f535e8b7d0 | ||
|
|
84519cf7cc | ||
|
|
2f93e4cdbc | ||
|
|
ca4c906814 | ||
|
|
3c8d247b28 | ||
|
|
872585833b | ||
|
|
3c7daea3c1 | ||
|
|
e6034a69a6 | ||
|
|
87b76b80f6 | ||
|
|
2e18a774f2 | ||
|
|
b75863ba51 | ||
|
|
8043ac1409 | ||
|
|
eef0e453bf | ||
|
|
1e59da6193 | ||
|
|
f3804b7e2e | ||
|
|
d1c0be2c24 | ||
|
|
8ce30e6194 | ||
|
|
d2d6621add | ||
|
|
f0e5c1fc06 | ||
|
|
5546fe5317 | ||
|
|
fad6baf28a | ||
|
|
964ab2c46f | ||
|
|
048c6bf131 | ||
|
|
02e703ffc3 | ||
|
|
c15763d9f8 | ||
|
|
90d1c8d1bb | ||
|
|
d2adc54132 | ||
|
|
2b29865b9c | ||
|
|
e3fb2cb255 | ||
|
|
50ede0b2f9 | ||
|
|
bef866fb6a | ||
|
|
dc1a9b6f03 | ||
|
|
2126808cee | ||
|
|
ff22f05576 | ||
|
|
9b9d4f0577 | ||
|
|
6abd3323d2 | ||
|
|
b71a29b6ef | ||
|
|
cd2983af52 | ||
|
|
f8a8e12add | ||
|
|
c558caba5b | ||
|
|
523a0955c4 | ||
|
|
e7fce80239 | ||
|
|
e3c6f28182 | ||
|
|
d500ddc7ab | ||
|
|
a7abdab1f7 | ||
|
|
fe9f5a9272 | ||
|
|
42a0f3f05c | ||
|
|
9860ee9b40 | ||
|
|
446eb8e1ef | ||
|
|
9f8eb92e5b | ||
|
|
a7f351a75f | ||
|
|
b03d7bb1a3 | ||
|
|
ffc972662e | ||
|
|
452c29ac95 | ||
|
|
ca40cce9e9 | ||
|
|
9305c636e1 | ||
|
|
7f39e0f271 | ||
|
|
9f6c417147 |
No files matched your search
@@ -0,0 +1,11 @@
|
||||
# Only requirements.txt, dsc/, start.py, and healthcheck.py belong in the
|
||||
# build context.
|
||||
*
|
||||
!requirements.txt
|
||||
!start.py
|
||||
!healthcheck.py
|
||||
!dsc/
|
||||
|
||||
# Keep local artifacts out even though dsc/ is re-included above.
|
||||
dsc/**/__pycache__/
|
||||
dsc/**/*.py[cod]
|
||||
@@ -0,0 +1,35 @@
|
||||
version: 2
|
||||
|
||||
updates:
|
||||
# Python runtime dependencies pinned in requirements.txt.
|
||||
- package-ecosystem: pip
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
open-pull-requests-limit: 5
|
||||
labels:
|
||||
- dependencies
|
||||
commit-message:
|
||||
prefix: pip
|
||||
|
||||
# Base image in the Dockerfile. The Seafile AppImage is fetched by URL and
|
||||
# checksum, so Dependabot cannot track it; bump SEAFILE_CLI_VERSION and
|
||||
# SEAFILE_CLI_SHA256 by hand.
|
||||
- package-ecosystem: docker
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
labels:
|
||||
- dependencies
|
||||
commit-message:
|
||||
prefix: docker
|
||||
|
||||
# Actions used by .github/workflows.
|
||||
- package-ecosystem: github-actions
|
||||
directory: /
|
||||
schedule:
|
||||
interval: weekly
|
||||
labels:
|
||||
- dependencies
|
||||
commit-message:
|
||||
prefix: ci
|
||||
@@ -9,45 +9,105 @@ on:
|
||||
|
||||
pull_request:
|
||||
|
||||
# Catch newly disclosed CVEs against unchanged code; matches Dependabot's
|
||||
# weekly cadence in .github/dependabot.yml.
|
||||
schedule:
|
||||
- cron: '0 6 * * 1'
|
||||
|
||||
# Run the scan on demand instead of waiting for the next cron tick.
|
||||
workflow_dispatch:
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
env:
|
||||
IMAGE: snegov/seafile-client
|
||||
|
||||
jobs:
|
||||
# Application failures must be distinguishable from packaging failures, so
|
||||
# the unit tests do not depend on the image build.
|
||||
unit-test:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- uses: actions/setup-python@v7
|
||||
with:
|
||||
python-version: '3.11'
|
||||
cache: pip
|
||||
|
||||
- name: Install dependencies
|
||||
run: pip install -r requirements-dev.txt
|
||||
|
||||
- name: Run unit tests
|
||||
run: pytest -q
|
||||
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- name: Run tests
|
||||
run: |
|
||||
if [ -f docker-compose.test.yml ]; then
|
||||
docker-compose --file docker-compose.test.yml build
|
||||
docker-compose --file docker-compose.test.yml run sut
|
||||
else
|
||||
docker build . --file Dockerfile
|
||||
fi
|
||||
- name: Validate compose example
|
||||
run: docker compose --file compose.example.yaml config --quiet
|
||||
|
||||
- name: Build image
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
context: .
|
||||
push: false
|
||||
load: true
|
||||
tags: ${{ env.IMAGE }}:ci
|
||||
|
||||
# Exercises the real seaf-cli and seaf-daemon in the built image, which
|
||||
# the unit tests cannot do. The runner is x86_64, matching the AppImage.
|
||||
- name: Container smoke test
|
||||
run: tests/smoke.sh ${{ env.IMAGE }}:ci
|
||||
|
||||
# ignore-unfixed: the debian:bookworm-slim base carries CVEs with no
|
||||
# upstream fix yet; failing on those would block every build on
|
||||
# findings nothing in this repo can act on. A fixable HIGH/CRITICAL
|
||||
# finding still fails the build.
|
||||
- name: Scan image for vulnerabilities
|
||||
uses: aquasecurity/trivy-action@v0.36.0
|
||||
with:
|
||||
image-ref: ${{ env.IMAGE }}:ci
|
||||
severity: HIGH,CRITICAL
|
||||
ignore-unfixed: true
|
||||
exit-code: '1'
|
||||
|
||||
push:
|
||||
needs: test
|
||||
needs: [unit-test, test]
|
||||
|
||||
runs-on: ubuntu-latest
|
||||
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v2
|
||||
- uses: actions/checkout@v7
|
||||
|
||||
- uses: docker/build-push-action@v1
|
||||
# Every tag of a release must resolve to one manifest digest, so the
|
||||
# image is built once and all tags are attached to that single build.
|
||||
- name: Collect tags and labels
|
||||
id: meta
|
||||
uses: docker/metadata-action@v6
|
||||
with:
|
||||
images: ${{ env.IMAGE }}
|
||||
tags: |
|
||||
type=ref,event=tag
|
||||
flavor: |
|
||||
latest=true
|
||||
|
||||
- name: Log in to Docker Hub
|
||||
uses: docker/login-action@v4
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
repository: snegov/seafile-client
|
||||
tag_with_ref: true
|
||||
add_git_labels: true
|
||||
push: ${{ startsWith(github.ref, 'refs/tags/') }}
|
||||
password: ${{ secrets.DOCKER_TOKEN }}
|
||||
|
||||
- uses: docker/build-push-action@v1
|
||||
- name: Build and push
|
||||
uses: docker/build-push-action@v7
|
||||
with:
|
||||
username: ${{ secrets.DOCKER_USERNAME }}
|
||||
password: ${{ secrets.DOCKER_PASSWORD }}
|
||||
repository: snegov/seafile-client
|
||||
tags: latest
|
||||
add_git_labels: true
|
||||
push: ${{ startsWith(github.ref, 'refs/tags/') }}
|
||||
context: .
|
||||
push: true
|
||||
tags: ${{ steps.meta.outputs.tags }}
|
||||
labels: ${{ steps.meta.outputs.labels }}
|
||||
@@ -3,3 +3,4 @@
|
||||
__pycache__/
|
||||
.python-version
|
||||
docker-compose.yml
|
||||
.smoke-*/
|
||||
@@ -0,0 +1,102 @@
|
||||
# Agent Instructions - docker-seafile-client
|
||||
|
||||
Docker container for Seafile CLI client with automatic retry logic for server outages.
|
||||
|
||||
## Quick Commands
|
||||
|
||||
### Build & Test Locally
|
||||
```bash
|
||||
# Build image
|
||||
docker build -t snegov/seafile-client:test .
|
||||
|
||||
# Test locally with docker-compose
|
||||
docker compose build
|
||||
docker compose up
|
||||
|
||||
# Check logs
|
||||
docker compose logs -f
|
||||
```
|
||||
|
||||
### Build & Deploy Test Image to Docker Hub
|
||||
```bash
|
||||
# Build fresh image without cache
|
||||
docker build --no-cache -t snegov/seafile-client:test .
|
||||
|
||||
# Push to Docker Hub (requires login)
|
||||
docker push snegov/seafile-client:test
|
||||
```
|
||||
|
||||
Deploying to hosts is documented in `CLAUDE.local.md` (private, not in the
|
||||
repo).
|
||||
|
||||
### Release New Version
|
||||
```bash
|
||||
# Create tag; pushing it to GitHub runs the Docker Hub publish workflow
|
||||
git tag 0.0.X
|
||||
git push gh 0.0.X
|
||||
|
||||
# Docker Hub will automatically build snegov/seafile-client:latest and snegov/seafile-client:0.0.X
|
||||
```
|
||||
|
||||
### Syntax Check
|
||||
```bash
|
||||
python3 -m py_compile dsc/client.py
|
||||
python3 -m py_compile start.py
|
||||
```
|
||||
|
||||
## Project Structure
|
||||
|
||||
```
|
||||
dsc/
|
||||
client.py - Main SeafileClient class
|
||||
const.py - Constants
|
||||
misc.py - Helper functions
|
||||
__init__.py - Package init
|
||||
start.py - Container entrypoint
|
||||
Dockerfile - Image definition
|
||||
docker-compose.yml - Local testing setup
|
||||
requirements.txt - Python dependencies
|
||||
```
|
||||
|
||||
## Architecture Notes
|
||||
|
||||
### HTTP Retry Strategy
|
||||
- 30 retry attempts with exponential backoff (2s base, 60s max)
|
||||
- Retries on 500, 502, 503, 504 status codes
|
||||
- Prevents container crash-loop during server outages
|
||||
- urllib3 debug logging shows retry attempts
|
||||
|
||||
### Session Management
|
||||
- Single `requests.Session` per client instance
|
||||
- Retry logic configured via `HTTPAdapter` + `Retry`
|
||||
- Token cached in `self.__token` (fetched on first use)
|
||||
|
||||
### Server URL Handling
|
||||
- Assumes HTTPS unless `http://` explicitly specified
|
||||
- No initial connection test (fails fast on first API call)
|
||||
|
||||
### Library Status Monitoring
|
||||
- Dynamic column width (max 30 chars) for clean output
|
||||
- Only logs status changes (not every poll)
|
||||
- Handles long library names without breaking alignment
|
||||
|
||||
## Testing
|
||||
|
||||
No formal test suite yet. Manual testing via:
|
||||
1. Build image
|
||||
2. Run with docker-compose
|
||||
3. Monitor logs for expected behavior
|
||||
4. Test with server down (should retry, not crash)
|
||||
|
||||
## Deployment
|
||||
|
||||
- Production: `snegov/seafile-client:latest` (auto-built from tags)
|
||||
- Testing: `snegov/seafile-client:test` (manual push)
|
||||
|
||||
## Common Issues
|
||||
|
||||
**Container crash-loops on 502**: Retry logic should handle this (check urllib3 logs).
|
||||
|
||||
**No retry logs visible**: Ensure urllib3 logger is set to DEBUG and propagate=True.
|
||||
|
||||
**Wrong image deployed**: Clear old image with `docker rmi` before pulling fresh one.
|
||||
+82
-14
@@ -1,25 +1,93 @@
|
||||
FROM python:3.8.12-slim-buster
|
||||
FROM debian:bookworm-slim
|
||||
|
||||
RUN apt-get update && apt-get install gnupg curl -y && rm -rf /var/lib/apt/lists/*
|
||||
RUN curl https://linux-clients.seafile.com/seafile.asc | apt-key add - && \
|
||||
echo 'deb [arch=amd64] https://linux-clients.seafile.com/seafile-deb/buster/ stable main' > /etc/apt/sources.list.d/seafile.list && \
|
||||
apt-get update -y && \
|
||||
apt-get install -y seafile-cli procps grep && \
|
||||
# Seafile discontinued its APT repository; linux-clients.seafile.com no longer
|
||||
# resolves to a reachable host. Upstream now ships the CLI as an AppImage.
|
||||
ARG SEAFILE_CLI_VERSION=9.0.19
|
||||
ARG SEAFILE_CLI_SHA256=4af848362d8493be218b903e17e3fbbd282e9ea94af000211ce05c3f44e48715
|
||||
ARG SEAFILE_CLI_URL=https://sos-ch-dk-2.exo.io/seafile-downloads/Seafile-cli-x86_64-${SEAFILE_CLI_VERSION}.AppImage
|
||||
|
||||
RUN apt-get update && \
|
||||
apt-get install -y --no-install-recommends \
|
||||
ca-certificates curl binutils squashfs-tools python3.11-venv && \
|
||||
rm -rf /var/lib/apt/lists/*
|
||||
|
||||
WORKDIR /seafile-client
|
||||
COPY requirements.txt ./
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
# An AppImage is an ELF runtime with a squashfs image appended. Unpack the
|
||||
# squashfs directly rather than executing the AppImage: running it needs FUSE,
|
||||
# and so a privileged container. Verify the download before unpacking it.
|
||||
RUN curl -fsSL -o /tmp/seaf-cli.AppImage "$SEAFILE_CLI_URL" && \
|
||||
echo "${SEAFILE_CLI_SHA256} /tmp/seaf-cli.AppImage" | sha256sum -c - && \
|
||||
offset=$(LC_ALL=C readelf -h /tmp/seaf-cli.AppImage | awk '\
|
||||
/Start of section headers/ {s=$5} \
|
||||
/Size of section headers/ {z=$5} \
|
||||
/Number of section headers/{n=$5} \
|
||||
END {print s + z * n}') && \
|
||||
unsquashfs -q -d /opt/seafile-cli -o "$offset" /tmp/seaf-cli.AppImage && \
|
||||
rm /tmp/seaf-cli.AppImage
|
||||
|
||||
# The bundled AppRun expects APPDIR, which only the AppImage runtime sets.
|
||||
# seaf-cli also requires seaf-daemon on PATH, so keep usr/bin ahead of it.
|
||||
RUN printf '%s\n' \
|
||||
'#!/bin/sh' \
|
||||
'APPDIR=/opt/seafile-cli' \
|
||||
'export PATH="$APPDIR/usr/bin${PATH:+:$PATH}"' \
|
||||
'export LD_LIBRARY_PATH="$APPDIR/usr/lib${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}"' \
|
||||
'export PYTHONPATH="$APPDIR/usr/lib/python3.9/site-packages${PYTHONPATH:+:$PYTHONPATH}"' \
|
||||
'exec python3 "$APPDIR/usr/bin/seaf-cli" "$@"' \
|
||||
> /usr/local/bin/seaf-cli && \
|
||||
chmod +x /usr/local/bin/seaf-cli
|
||||
|
||||
# Use virtual environment
|
||||
ENV VIRTUAL_ENV=/opt/venv
|
||||
RUN python3 -m venv --system-site-packages $VIRTUAL_ENV
|
||||
ENV PATH="$VIRTUAL_ENV/bin:$PATH"
|
||||
|
||||
# The APT package used to install the seafile/pysearpc RPC bindings system-wide.
|
||||
# The AppImage keeps them in its own tree, so put them on the venv path: dsc
|
||||
# imports seafile directly, not only through seaf-cli. They are pure Python, so
|
||||
# the 3.9 build works unchanged on this interpreter.
|
||||
RUN python3 -c "import pathlib, site; \
|
||||
pathlib.Path(site.getsitepackages()[0], 'seafile-appimage.pth') \
|
||||
.write_text('/opt/seafile-cli/usr/lib/python3.9/site-packages\n')"
|
||||
|
||||
# Install app requirements
|
||||
WORKDIR /dsc
|
||||
COPY requirements.txt ./
|
||||
# venv creation bootstraps its own setuptools via ensurepip, which
|
||||
# requirements.txt does not cover. 66.1.1 carries CVE-2024-6345 and
|
||||
# CVE-2025-47273; 78.1.1 fixes both.
|
||||
RUN pip install --no-cache-dir --upgrade "setuptools>=78.1.1" && \
|
||||
pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Copy app
|
||||
COPY dsc ./dsc/
|
||||
COPY start.py ./start.py
|
||||
COPY healthcheck.py ./healthcheck.py
|
||||
|
||||
RUN chmod +x /seafile-client/start.py && \
|
||||
useradd -U -d /seafile-client -s /bin/bash seafile && \
|
||||
# Create seafile user and init seafile client
|
||||
RUN chmod +x /dsc/start.py /dsc/healthcheck.py && \
|
||||
useradd -U -d /dsc -s /bin/bash seafile && \
|
||||
usermod -G users seafile && \
|
||||
chown seafile:seafile -R /seafile-client && \
|
||||
su - seafile -c "seaf-cli init -d /seafile-client"
|
||||
mkdir -p /dsc/seafile-data && \
|
||||
chown seafile:seafile -R /dsc
|
||||
|
||||
VOLUME /seafile-client/seafile-data
|
||||
# Smoke checks: seaf-cli has no --version flag, so assert its subcommands, and
|
||||
# confirm the app's own imports resolve.
|
||||
RUN seaf-cli --help | grep -q 'download-by-name' && \
|
||||
seaf-cli sync --help | grep -q '\--token' && \
|
||||
seaf-cli list --help | grep -q '\--json' && \
|
||||
python3 -c "import seafile, pysearpc, dsc.client, dsc.misc, healthcheck"
|
||||
|
||||
# Record the pinned client version in the image so it can be checked at
|
||||
# runtime; seaf-cli itself has no --version flag.
|
||||
ENV SEAFILE_CLI_VERSION=${SEAFILE_CLI_VERSION}
|
||||
|
||||
VOLUME /dsc/seafile-data
|
||||
|
||||
# The container's own process already runs as the seafile user (see
|
||||
# dsc.misc.drop_privileges), but a HEALTHCHECK is a fresh process started by
|
||||
# the Docker daemon, which starts it as root. runuser drops it to the same
|
||||
# unprivileged user before it ever touches the RPC socket.
|
||||
HEALTHCHECK --interval=30s --timeout=5s --start-period=90s --retries=3 \
|
||||
CMD runuser -u seafile -- python3 /dsc/healthcheck.py
|
||||
|
||||
CMD ["./start.py"]
|
||||
+303
@@ -0,0 +1,303 @@
|
||||
# Improvement Plan
|
||||
|
||||
This plan prioritizes user safety and a working release pipeline before public
|
||||
portfolio polish. The project already has useful adoption evidence: more than
|
||||
5,800 Docker Hub pulls, external issues, and external contributions.
|
||||
|
||||
Security-sensitive findings should be fixed and released before detailed
|
||||
exploit scenarios are discussed in public issues.
|
||||
|
||||
## P0 - Release blockers
|
||||
|
||||
### Restore reproducible image builds
|
||||
|
||||
- [x] Replace the unavailable Seafile APT repository used in `Dockerfile`.
|
||||
Upstream discontinued it; the CLI now ships as an x86_64-only AppImage.
|
||||
- [x] Install a supported Seafile CLI version from an official source.
|
||||
- [x] Pin the version and verify its checksum during the build. The checksum is
|
||||
trust-on-first-use: upstream publishes no digest or signature alongside the
|
||||
AppImage, so this is weaker than the signed APT repository it replaces.
|
||||
- [x] Remove `apt-key`, which is deprecated and trusts keys globally.
|
||||
- [x] Add a smoke check that `seaf-cli` runs to the image build. Note that
|
||||
`seaf-cli` has no `--version` flag; use `seaf-cli --help` and assert the
|
||||
expected subcommands, and record the installed version from the package
|
||||
manager instead.
|
||||
- [x] Scan the resulting image and review every high or critical finding. Of
|
||||
67 HIGH/CRITICAL findings (`trivy image`), 65 are in `debian:bookworm-slim`
|
||||
packages with no upstream fix yet; the CI scan uses `--ignore-unfixed` so it
|
||||
fails only on findings this repo can act on. The other 2, both `setuptools`
|
||||
(bundled by `ensurepip` in the venv, not from `requirements.txt`), had
|
||||
fixes and are resolved: see `Dockerfile`.
|
||||
- [ ] Establish a stronger trust anchor for the AppImage than a self-derived
|
||||
checksum: an upstream digest or signature, or a verified artifact mirrored
|
||||
somewhere we control.
|
||||
|
||||
Acceptance criteria:
|
||||
|
||||
- A clean `docker build --no-cache .` succeeds in CI.
|
||||
- The installed Seafile version is explicit and current.
|
||||
- An invalid artifact checksum fails the build. Upstream publishes no signature
|
||||
for the AppImage, so signature verification is not achievable from this
|
||||
source.
|
||||
|
||||
### Remove shell and path injection risks
|
||||
|
||||
- [x] Pass subprocess arguments as arrays instead of joining values into shell
|
||||
command strings in `dsc/client.py` and `dsc/misc.py`. The password is no
|
||||
longer wrapped in quotes to survive a shell, which also fixes passwords
|
||||
containing quotes, `$`, and backticks.
|
||||
- [x] Replace `su -c` with a mechanism such as `runuser --` that does not need a
|
||||
shell. `runuser -u` sets the same `HOME` and a `PATH` that still finds the
|
||||
`seaf-cli` wrapper, so the daemon environment is unchanged.
|
||||
- [x] Treat server-provided library names as untrusted input.
|
||||
- [x] Resolve every target directory and prove that it remains under
|
||||
`/dsc/seafile` before creating or writing it. Symlinks are resolved first,
|
||||
so an existing symlink in the libraries directory cannot redirect a write.
|
||||
- [x] Define how duplicate, absolute, empty, and traversal-style library names
|
||||
are handled. See `dsc/paths.py` and the "Some notes" section of the README.
|
||||
|
||||
Acceptance criteria:
|
||||
|
||||
- Tests cover quotes, command substitutions, separators, newlines, absolute
|
||||
paths, parent traversal, Unicode, and colliding library names.
|
||||
- No configuration or server value can execute a command or escape the data
|
||||
directory.
|
||||
|
||||
### Support secrets safely
|
||||
|
||||
- [x] Implement `PASSWORD_FILE` for Docker Compose and Swarm secrets. Only a
|
||||
trailing newline is stripped, so a secret keeps any surrounding spaces.
|
||||
- [x] Add token-based authentication and `TOKEN_FILE` if supported by the
|
||||
installed Seafile CLI. It is: `seaf-cli sync` takes `-T`, and ignores the
|
||||
password when a token is given.
|
||||
- [x] Define precedence and reject conflicting secret sources. Two sources for
|
||||
one secret (`PASSWORD` with `PASSWORD_FILE`) are rejected; a token takes
|
||||
precedence over a password, as it does in `seaf-cli` itself.
|
||||
- [x] Ensure secrets are absent from application logs. Both the password and
|
||||
the token are masked before a command is logged.
|
||||
- [x] Document any upstream limitation that exposes a secret in process
|
||||
arguments. `seaf-cli` accepts credentials only as arguments, so a secret is
|
||||
visible to any process in the container. The account password no longer goes
|
||||
there: the client authenticates with an API token, which can be revoked.
|
||||
See the README.
|
||||
|
||||
Acceptance criteria:
|
||||
|
||||
- A container can authenticate with a mounted file under `/run/secrets`.
|
||||
- Tests reject conflicting inputs and verify newline handling.
|
||||
- Logs never contain the password or token.
|
||||
|
||||
### Correct environment parsing and defaults
|
||||
|
||||
- [x] Replace direct `os.getenv()` assignments in `start.py` with typed parsers.
|
||||
See `dsc/config.py` and `defaults_from_env()`.
|
||||
- [x] Preserve the documented defaults for upload limit, download limit, and
|
||||
delete-confirm threshold when variables are absent. They were not: an unset
|
||||
variable overwrote the argparse default with `None`, so a default container
|
||||
sent the literal string `None` for all three.
|
||||
- [x] Validate UID, GID, limits, threshold, and booleans before daemon startup.
|
||||
UID and GID are now integers; as strings they never equalled the integers
|
||||
they were compared against, so `usermod` ran on every start.
|
||||
- [x] Reject negative and malformed numeric values with useful messages.
|
||||
- [x] Do not pass `None` as a Seafile configuration value. Booleans are also
|
||||
rendered as `true`/`false` rather than Python's `True`/`False`. This fixed
|
||||
`DISABLE_VERIFY_CERTIFICATE`, which never worked. The daemon reads the key
|
||||
with `seafile_session_config_get_bool`, which is
|
||||
`g_strcmp0(value, "true") == 0`, so it accepts only the exact string
|
||||
`"true"`. Python's `str(True)` stored the string `"True"`, which did not
|
||||
match and was therefore read as false, leaving verification on for anyone
|
||||
who asked to disable it. The default stored the string `"False"`, which is
|
||||
also not `"true"` and so was correctly read as false.
|
||||
|
||||
Acceptance criteria:
|
||||
|
||||
- Table-driven tests cover unset, zero, valid, negative, and malformed values.
|
||||
- A default container receives exactly the defaults documented in the README.
|
||||
|
||||
### Make startup and shutdown deterministic
|
||||
|
||||
- [x] Check every important subprocess return code. A failed `seaf-cli sync` is
|
||||
reported per library and does not stop the remaining ones.
|
||||
- [x] Add timeouts to daemon startup, shutdown, and readiness polling. See
|
||||
`DAEMON_START_TIMEOUT` and `DAEMON_STOP_TIMEOUT` in `dsc/const.py`; the stop
|
||||
timeout is deliberately below the 10 second `docker stop` grace period.
|
||||
- [x] Handle `SIGTERM` and `SIGINT` and stop the daemon in `finally`.
|
||||
- [x] Return a nonzero container exit code on configuration or daemon failure.
|
||||
- [x] Produce actionable errors instead of waiting forever.
|
||||
|
||||
Acceptance criteria:
|
||||
|
||||
- A daemon that never becomes ready causes a bounded failure.
|
||||
- `docker stop` performs a graceful shutdown within Docker's timeout.
|
||||
- Failure-injection tests cover command errors and interrupted startup.
|
||||
|
||||
### Add real tests
|
||||
|
||||
- [ ] Add unit tests for configuration parsing, command construction, library
|
||||
resolution, path validation, retries, and status parsing. Command
|
||||
construction and path validation are covered in `tests/`; configuration
|
||||
parsing, retries, and status parsing are not.
|
||||
- [ ] Add regression tests for externally reported password and deletion
|
||||
threshold issues.
|
||||
- [x] Add a container smoke test for imports, installed CLI version, startup,
|
||||
and shutdown using controlled fakes. See `tests/smoke.sh`, run by the image
|
||||
build job. It exercises the real `seaf-cli` and `seaf-daemon`, which the unit
|
||||
tests cannot: the runner is x86_64, matching the AppImage. The pinned client
|
||||
version is exposed as `SEAFILE_CLI_VERSION` in the image so it can be
|
||||
asserted at runtime.
|
||||
- [x] Keep image construction as a separate CI job so packaging failures are
|
||||
distinguishable from application failures. The `unit-test` job does not
|
||||
depend on the image build.
|
||||
|
||||
Acceptance criteria:
|
||||
|
||||
- CI fails on a deliberate parsing, quoting, or path-safety regression.
|
||||
- Application tests run without requiring a live production server.
|
||||
|
||||
### Repair and validate the quick start
|
||||
|
||||
- [x] Change the Compose example to mapping syntax so quote characters are not
|
||||
passed as part of `LIBRARY_ID`.
|
||||
- [x] Pin the example to a versioned image instead of an implicit latest tag.
|
||||
- [x] Add a checked-in `compose.example.yaml`.
|
||||
- [x] Validate it with `docker compose config` in CI.
|
||||
|
||||
## P1 - Reliability and supply chain
|
||||
|
||||
### Networking and protocol behavior
|
||||
|
||||
- [x] Add explicit connect and read timeouts to all HTTP requests. See
|
||||
`HTTP_TIMEOUT` in `dsc/const.py`; both `SeafileClient` requests pass it.
|
||||
- [x] Define a bounded retry budget with backoff. Measured: the
|
||||
previous `Retry(total=30, backoff_factor=2, backoff_max=60)` with no request
|
||||
timeout waited about 26 minutes on a single unreachable server before giving
|
||||
up, which is indistinguishable from a hang. Observed while writing the smoke
|
||||
test, when a probe pointed at an unroutable host. Replaced with
|
||||
`HTTP_RETRY_TOTAL`/`HTTP_RETRY_BACKOFF_FACTOR`/`HTTP_RETRY_BACKOFF_MAX`,
|
||||
bounding the worst case to a few minutes; a network failure now raises
|
||||
`NetworkError` instead of an unhandled `requests` exception. `urllib3`'s
|
||||
`Retry` has no jitter parameter, so backoff remains deterministic.
|
||||
- [ ] Handle authentication, rate limits, malformed responses, and retryable
|
||||
server errors separately.
|
||||
- [ ] Make TLS configuration consistent between Python requests and Seafile.
|
||||
- [ ] Support a custom CA bundle; keep certificate disabling as a last resort.
|
||||
- [x] Prefer structured JSON output from `seaf-cli` over parsing display text.
|
||||
`seaf-cli list --json` is used instead of splitting the display columns,
|
||||
which could not represent a library name or a path containing whitespace.
|
||||
`list-remote` still uses the HTTP API rather than the CLI.
|
||||
- [x] Reject ambiguous library names and an empty requested library set.
|
||||
`get_library_id` used to silently return the first library matching a
|
||||
requested name, even if two libraries shared it; it now raises
|
||||
`ConfigError` when a name matches more than one library ID.
|
||||
`resolve_libraries` rejects an empty entry from `LIBRARY_ID` (an empty
|
||||
string, or one produced by `"a::b"`/a leading or trailing `:`) the same
|
||||
way. See `tests/test_libraries.py`.
|
||||
|
||||
### Runtime hardening
|
||||
|
||||
- [x] Run the long-lived process as the configured non-root user after setup.
|
||||
`start.py` used to stay root for its whole life; only the individual
|
||||
`seaf-cli`/`seaf-daemon` subprocess calls were unprivileged (via
|
||||
`runuser`). Now `main()` drops privileges in-process
|
||||
(`dsc.misc.drop_privileges`, using `os.initgroups`/`setgid`/`setuid`)
|
||||
right after `setup_uid()`/`create_dir()`, and before `SeafileClient` or
|
||||
the daemon/RPC/watch loop start. `runuser` is gone from `user_cmd()`
|
||||
since it can't be invoked from an already non-root process anyway.
|
||||
Verified against the real image (not just mocked unit tests): a running
|
||||
container's PID 1 shows `Uid: 1000 1000 1000 1000` in `/proc/1/status`.
|
||||
- [x] Reject UID or GID zero unless a documented use case requires it.
|
||||
`main()` now exits with code 2 and a clear message if `--uid`/`SEAFILE_UID`
|
||||
or `--gid`/`SEAFILE_GID` resolve to 0, before `setup_uid()` ever runs.
|
||||
- [x] Add a health check for the daemon and RPC endpoint.
|
||||
`SeafileClient.is_healthy()` checks `seaf-cli status` and a real RPC call
|
||||
(`get_repo_list`); `healthcheck.py` exposes it to Docker's `HEALTHCHECK`.
|
||||
Each check is a fresh root-spawned process (unlike the long-lived
|
||||
`start.py`), so it drops to the `seafile` user with `runuser` before
|
||||
touching the RPC socket - the one place that mechanism still belongs.
|
||||
- [x] Handle temporary RPC failures and daemon restarts without corrupting
|
||||
state. `watch_status()`'s per-iteration RPC read is now wrapped so an
|
||||
unexpected failure (the daemon crashing or restarting mid-call) logs a
|
||||
warning and retries on the next tick instead of crashing the container;
|
||||
a stop signal or another `DscError` still ends the loop as before. Prior
|
||||
state is left untouched across a failed read, so the next successful one
|
||||
still reports every real change. Verified against the real image: the
|
||||
container survives `seaf-daemon` being killed outright.
|
||||
- [ ] Document supported CPU architectures instead of implying multi-platform
|
||||
support.
|
||||
|
||||
### CI and release pipeline
|
||||
|
||||
- [x] Replace `actions/checkout@v2` and `docker/build-push-action@v1`.
|
||||
- [x] Set workflow permissions explicitly to `contents: read` by default.
|
||||
- [x] Use a scoped Docker Hub access token. The workflow now reads
|
||||
`secrets.DOCKER_TOKEN`; the repository secret still has to be created from a
|
||||
scoped Docker Hub token before the next tag is pushed.
|
||||
- [x] Build a release image once and attach all version and `latest` tags to
|
||||
the same manifest digest.
|
||||
- [x] Add OCI labels via `docker/metadata-action`.
|
||||
- [ ] Add an SBOM, provenance, and image signing.
|
||||
- [x] Add dependency updates for Python, Docker, and GitHub Actions. A weekly
|
||||
Dependabot configuration covers `requirements.txt`, the Dockerfile base
|
||||
image, and the workflow actions. The Seafile AppImage is fetched by URL and
|
||||
checksum, so it still has to be bumped by hand.
|
||||
- [x] Run dependency and image scans on pull requests and on a schedule. The
|
||||
`test` job runs the Trivy image scan on every pull request, on every push
|
||||
to `master` or a tag, and now weekly (`schedule: cron '0 6 * * 1'`,
|
||||
matching Dependabot's cadence) to catch newly disclosed CVEs against
|
||||
unchanged code. Dependency updates themselves are Dependabot's job; see
|
||||
"CI and release pipeline" above.
|
||||
|
||||
Acceptance criteria:
|
||||
|
||||
- Every tag for one release resolves to the same manifest digest.
|
||||
- Pull requests cannot access publication credentials.
|
||||
- The current dependency update pull request passes all checks.
|
||||
|
||||
## P2 - Maintainability and presentation
|
||||
|
||||
### Simplify the implementation
|
||||
|
||||
- [ ] Separate configuration, subprocess execution, library resolution, and
|
||||
status monitoring so each can be tested independently.
|
||||
- [x] Remove unused imports and unnecessary dependencies. Both pinned
|
||||
requirements are used; `urllib3` is imported directly but only pinned
|
||||
transitively through `requests`.
|
||||
- [ ] Add type annotations and static checks at external-input boundaries.
|
||||
- [ ] Make logging configurable and avoid forced dependency debug logs.
|
||||
- [ ] Add `.dockerignore` and reduce unnecessary image packages. `.dockerignore`
|
||||
is in place; `binutils` and `squashfs-tools` are still shipped in the final
|
||||
image because the AppImage is unpacked in the same stage.
|
||||
|
||||
### Establish a visible maintenance process
|
||||
|
||||
- [ ] Publish GitHub Releases for future tags with compatibility and rollback
|
||||
notes.
|
||||
- [ ] Add `CHANGELOG.md`, `SECURITY.md`, and concise contribution guidance.
|
||||
- [ ] Add issue templates that request image, client, and server versions plus
|
||||
sanitized logs.
|
||||
- [ ] Triage stale issues and document the status of Docker secret support.
|
||||
- [ ] Enable branch protection and require passing CI before merge.
|
||||
|
||||
### Improve the public project page
|
||||
|
||||
- [x] Link directly to the Docker Hub image near the top of `README.md`.
|
||||
- [ ] Add CI, release, Docker pulls, and license badges after the checks are
|
||||
trustworthy.
|
||||
- [ ] Add a short architecture and process-lifecycle section.
|
||||
- [ ] Add a tested compatibility matrix.
|
||||
- [ ] Explain deletion behavior, volume ownership, state loss, backup
|
||||
expectations, and recovery.
|
||||
- [ ] Fix example inconsistencies and typographical errors.
|
||||
|
||||
## Release gate
|
||||
|
||||
Do not publish the next image until all of the following are true:
|
||||
|
||||
- [ ] A clean, reproducible build uses a supported Seafile client.
|
||||
- [ ] External values cannot reach a shell or escape the data directory.
|
||||
- [ ] Secret-file or token authentication is covered by tests.
|
||||
- [ ] Startup, retries, and shutdown are bounded and observable.
|
||||
- [ ] Unit and container smoke tests pass.
|
||||
- [ ] The steady-state process is non-root and has a useful health check.
|
||||
- [ ] Release tags point to one scanned and signed image digest.
|
||||
- [ ] The README quick start succeeds from a clean environment.
|
||||
@@ -1,7 +1,7 @@
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2018 Robin Grönberg
|
||||
Copyright (c) 2019 Maks Snegov
|
||||
Copyright (c) 2019-2023 Maks Snegov
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
|
||||
@@ -1,42 +1,127 @@
|
||||
# docker-seafile-client
|
||||
Runs a seafile client in docker with possibility to sync seafile repositories.
|
||||
Docker image for [Seafile CLI client](https://help.seafile.com/syncing_client/linux-cli/).
|
||||
|
||||
Image on Docker Hub:
|
||||
[snegov/seafile-client](https://hub.docker.com/r/snegov/seafile-client).
|
||||
|
||||
### Docker-compose example:
|
||||
Also available as a ready-to-use [`compose.example.yaml`](compose.example.yaml).
|
||||
|
||||
## Docker-compose example:
|
||||
```yaml
|
||||
version: '3'
|
||||
|
||||
services:
|
||||
seafile-client:
|
||||
restart: always
|
||||
image: snegov/seafile-client
|
||||
image: snegov/seafile-client:0.0.13
|
||||
environment:
|
||||
- LIBRARY_ID=<your-library-id-here>
|
||||
- SERVER_HOST=<server-host>
|
||||
- USERNAME=<username>
|
||||
- PASSWORD=<password>
|
||||
- SEAFILE_UID=<your_uid>
|
||||
- SEAFILE_GID=<your_gid>
|
||||
hostname: docker-seafile-client
|
||||
LIBRARY_ID: "79867cbf-2944-488d-9105-852463ecdf9e:my_library"
|
||||
SERVER_HOST: seafile.example.com
|
||||
USERNAME: user
|
||||
PASSWORD: password
|
||||
SEAFILE_UID: 1000
|
||||
SEAFILE_GID: 100
|
||||
hostname: dsc
|
||||
volumes:
|
||||
- seafile-data:/seafile-client/seafile-data
|
||||
- <host-volume-path>:/data
|
||||
- /home/johndow/seafile:/dsc/seafile
|
||||
- sync-data:/dsc/seafile-data
|
||||
container_name: seafile-client
|
||||
|
||||
volumes:
|
||||
seafile-data:
|
||||
sync-data:
|
||||
```
|
||||
|
||||
Library id could be found from "My Libraries" page in Seafile webUI - link to each library contains library ID in it.
|
||||
### Environment variables:
|
||||
- `LIBRARY_ID` - library to sync, ID or name. Multiple libraries could be
|
||||
separated by colon `:`.
|
||||
- `SERVER_HOST` - hostname of your Seafile server, eg: _seafile.example.com_.
|
||||
If you're using non-standard port, you can specify it here,
|
||||
eg: _seafile.example.com:8080_.
|
||||
- `USERNAME` / `PASSWORD` - credentials to access Seafile server.
|
||||
- `PASSWORD_FILE` - path to a file holding the password, for Docker Compose
|
||||
and Swarm secrets. Use either `PASSWORD` or `PASSWORD_FILE`, never both.
|
||||
- `TOKEN` / `TOKEN_FILE` - an API token to authenticate with instead of a
|
||||
password. A token takes precedence over a password and can be revoked on the
|
||||
server. Use either `TOKEN` or `TOKEN_FILE`, never both.
|
||||
- `SEAFILE_UID` / `SEAFILE_GID` - UID/GID of user inside container. You can
|
||||
use it to set permissions on synced files. Default values are _1000_ / _1000_.
|
||||
- `DELETE_CONFIRM_THRESHOLD` - represents the number of files that require
|
||||
confirmation before being deleted simultaneously. Default value is _500_.
|
||||
- `DISABLE_VERIFY_CERTIFICATE` - set to _true_ to disable server's certificate
|
||||
verification. Default value is _false_. Booleans accept _true_/_false_,
|
||||
_1_/_0_, _yes_/_no_ and _on_/_off_, in any case. Note that this setting had no
|
||||
effect in released images up to and including 0.0.13: whatever you set the
|
||||
variable to, the client stored the string `True`, and the Seafile daemon
|
||||
accepts only the lowercase string `true`, so verification stayed on even when
|
||||
the variable was set. The default was never affected, because the string
|
||||
`False` is also not `true`.
|
||||
- `UPLOAD_LIMIT` / `DOWNLOAD_LIMIT` - upload/download speed limit in B/s
|
||||
(bytes per second). Default values are _0_ (unlimited).
|
||||
|
||||
Inside container libraries' content will be put in `/data` directory, so map your host directory to it.
|
||||
Numeric variables must be whole, non-negative numbers. A malformed or negative
|
||||
value stops the container at startup with a message naming the variable,
|
||||
rather than being passed on to the Seafile client.
|
||||
|
||||
`hostname` parameter in docker-compose will set client name in Seafile's "Linked devices" admin page. Resulting name will be prefixed by "terminal-".
|
||||
### Using Docker secrets:
|
||||
Mount the secret and point `PASSWORD_FILE` at it, so the password never enters
|
||||
the environment:
|
||||
|
||||
Also you could check [docker-compose example](docker-compose.example.yml).
|
||||
```yaml
|
||||
services:
|
||||
seafile-client:
|
||||
environment:
|
||||
PASSWORD_FILE: /run/secrets/seafile_password
|
||||
secrets:
|
||||
- seafile_password
|
||||
|
||||
## Environment variables:
|
||||
- `LIBRARY_ID=<your-library-id-here>` Library to sync, ID or name; multiple libraries could be separated by colon `:`.
|
||||
- `SERVER_HOST=<server-host>` Hostname of your seafile server, eg: `seafile.example.com`. If you're using non-standart port, specify it here, eg: `seafile.example.com:8080`.
|
||||
- `USERNAME=<username>` Seafile account username.
|
||||
- `PASSWORD=<password>` Seafile account password.
|
||||
- `SEAFILE_UID=<uid>` Downloaded files will have this uid.
|
||||
- `SEAFILE_GID=<gid>` Downloaded files will have this gid.
|
||||
secrets:
|
||||
seafile_password:
|
||||
file: ./seafile_password.txt
|
||||
```
|
||||
|
||||
A trailing newline in the file is ignored; everything else, including
|
||||
surrounding spaces, is part of the secret.
|
||||
|
||||
The client authenticates `seaf-cli` with an API token rather than the account
|
||||
password, so the password never appears in a command line. The token does
|
||||
appear there, and command lines are visible to any process in the container.
|
||||
This is a limitation of `seaf-cli`, which accepts credentials only as
|
||||
arguments. A token can at least be revoked on the server.
|
||||
|
||||
### Volumes:
|
||||
- `/dsc/seafile-data` Seafile client data directory (sync status, etc).
|
||||
- `/dsc/seafile` Seafile libraries content.
|
||||
|
||||
|
||||
### Some notes
|
||||
`LIBRARY_ID` could be library ID or library name. Library ID is a 36-character
|
||||
string, which is a part of URI when you open library in webUI. Library name is
|
||||
a name you gave to library when you created it.
|
||||
|
||||
Libraries will be synced in subdirectories of `/dsc/seafile` directory inside
|
||||
container. You can mount it to host directory to access files.
|
||||
|
||||
The subdirectory is named after the library, with whitespace replaced by
|
||||
underscores. A library is skipped with a warning when its name cannot be a
|
||||
directory of its own: an empty name, `.`, `..`, or a name containing `/`. Two
|
||||
libraries whose names would produce the same directory both get their library
|
||||
ID appended, so they never share one. Everything is created under the
|
||||
libraries directory (`/dsc/seafile`, or the deprecated `/data` when that
|
||||
exists); a library name can never place it elsewhere.
|
||||
|
||||
The container stops gracefully on `docker stop`: it shuts the Seafile daemon
|
||||
down and exits with code 0. It exits with a nonzero code and an explanatory
|
||||
message when the daemon fails to start or stop within its timeout, instead of
|
||||
waiting forever.
|
||||
|
||||
`hostname` parameter is optional, but it's recommended to set it to some unique
|
||||
value, it will be shown in Seafile webUI as client name (`terminal-dsc` in
|
||||
given example).
|
||||
|
||||
`sync-data` volume is optional too, but it's recommended to use it. Otherwise,
|
||||
sync status will be lost when container is recreated.
|
||||
|
||||
At the moment there is no suitable way to confirm deletion of large number of
|
||||
files. So, if you're going to delete a lot of files, you should set
|
||||
`DELETE_CONFIRM_THRESHOLD` to some larger value.
|
||||
|
||||
### Links
|
||||
- [Official Seafile CLI client documentation](https://help.seafile.com/syncing_client/linux-cli/)
|
||||
@@ -0,0 +1,19 @@
|
||||
services:
|
||||
seafile-client:
|
||||
restart: always
|
||||
image: snegov/seafile-client:0.0.13
|
||||
environment:
|
||||
LIBRARY_ID: "79867cbf-2944-488d-9105-852463ecdf9e:my_library"
|
||||
SERVER_HOST: seafile.example.com
|
||||
USERNAME: user
|
||||
PASSWORD: password
|
||||
SEAFILE_UID: 1000
|
||||
SEAFILE_GID: 100
|
||||
hostname: dsc
|
||||
volumes:
|
||||
- /home/johndow/seafile:/dsc/seafile
|
||||
- sync-data:/dsc/seafile-data
|
||||
container_name: seafile-client
|
||||
|
||||
volumes:
|
||||
sync-data:
|
||||
@@ -1,21 +0,0 @@
|
||||
version: '3'
|
||||
|
||||
services:
|
||||
seafile-client:
|
||||
restart: always
|
||||
image: snegov/seafile-client
|
||||
environment:
|
||||
- LIBRARY_ID="79867cbf-2944-488d-9105-859463ecdf9e:test_library"
|
||||
- SERVER_HOST=seafile.example.com
|
||||
- USERNAME=user
|
||||
- PASSWORD=password
|
||||
- SEAFILE_UID=1000
|
||||
- SEAFILE_GID=100
|
||||
hostname: docker-seafcli
|
||||
volumes:
|
||||
- seafile-data:/seafile-client/seafile-data
|
||||
- /home/johndow/seafile:/data
|
||||
container_name: seafile-client
|
||||
|
||||
volumes:
|
||||
seafile-data:
|
||||
+1
-1
@@ -1 +1 @@
|
||||
from .client import SeafileClient, start_seaf_daemon
|
||||
from .client import SeafileClient, const
|
||||
+328
-73
@@ -1,40 +1,112 @@
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
from typing import Optional
|
||||
from urllib.parse import urlparse
|
||||
|
||||
from cached_property import cached_property_with_ttl
|
||||
import requests
|
||||
from requests.adapters import HTTPAdapter
|
||||
from urllib3.util.retry import Retry
|
||||
import seafile
|
||||
|
||||
from dsc import consts
|
||||
from dsc.misc import create_dir, hide_password
|
||||
from dsc import const
|
||||
from dsc.errors import ConfigError, DaemonError, DaemonTimeout, DscError, NetworkError
|
||||
from dsc.misc import config_value, create_dir, hide_secrets, user_cmd
|
||||
|
||||
_lg = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class SeafileClient:
|
||||
def __init__(self, host: str, user: str, passwd: str):
|
||||
up = urlparse(requests.get(f"http://{host}").url)
|
||||
self.url = f"{up.scheme}://{up.netloc}"
|
||||
def __init__(self,
|
||||
host: str,
|
||||
user: str,
|
||||
passwd: str = None,
|
||||
app_dir: str = const.DEFAULT_APP_DIR,
|
||||
token: str = None):
|
||||
self.user = user
|
||||
self.password = passwd
|
||||
self.__token = None
|
||||
self.app_dir = os.path.abspath(app_dir)
|
||||
self.rpc = seafile.RpcClient(os.path.join(self.app_dir, 'seafile-data', 'seafile.sock'))
|
||||
# A token supplied by the operator is used as is; otherwise one is
|
||||
# fetched from the server with the password.
|
||||
self.__token = token
|
||||
|
||||
# determine server URL (assume HTTPS unless explicitly specified)
|
||||
if host.startswith('http://') or host.startswith('https://'):
|
||||
self.url = host.rstrip('/')
|
||||
else:
|
||||
self.url = f"https://{host}"
|
||||
|
||||
# configure session with retry strategy
|
||||
# enable urllib3 retry logging at DEBUG level (shows retry attempts)
|
||||
urllib3_logger = logging.getLogger("urllib3.connectionpool")
|
||||
urllib3_logger.setLevel(logging.DEBUG)
|
||||
urllib3_logger.propagate = True
|
||||
|
||||
self.session = requests.Session()
|
||||
retry_strategy = Retry(
|
||||
total=const.HTTP_RETRY_TOTAL,
|
||||
backoff_factor=const.HTTP_RETRY_BACKOFF_FACTOR,
|
||||
backoff_max=const.HTTP_RETRY_BACKOFF_MAX,
|
||||
status_forcelist=[500, 502, 503, 504],
|
||||
allowed_methods=["GET", "POST"]
|
||||
)
|
||||
adapter = HTTPAdapter(max_retries=retry_strategy)
|
||||
self.session.mount("http://", adapter)
|
||||
self.session.mount("https://", adapter)
|
||||
|
||||
def __str__(self):
|
||||
return f"SeafileClient({self.user}@{self.url})"
|
||||
|
||||
def __gen_cmd(self, argv: list) -> list:
|
||||
return user_cmd(argv)
|
||||
|
||||
def __run(self, argv: list, check: bool = True, **kwargs):
|
||||
"""Run a seaf-cli command and, unless told otherwise, check its exit
|
||||
code. An unchecked failure here surfaces much later as a daemon that
|
||||
never becomes ready, with nothing pointing at the real cause."""
|
||||
proc = subprocess.run(self.__gen_cmd(argv), **kwargs)
|
||||
if check and proc.returncode != 0:
|
||||
raise DaemonError(
|
||||
f"Command {' '.join(argv)} failed with exit code {proc.returncode}"
|
||||
)
|
||||
return proc
|
||||
|
||||
def __wait_for_daemon(self, ready: bool, timeout: float, action: str):
|
||||
"""Wait until the daemon is ready (or stopped), but never forever."""
|
||||
deadline = time.monotonic() + timeout
|
||||
while self.daemon_ready != ready:
|
||||
if time.monotonic() >= deadline:
|
||||
state = "ready" if ready else "stopped"
|
||||
raise DaemonTimeout(
|
||||
f"Seafile daemon did not become {state} within {timeout}s"
|
||||
f" while {action}"
|
||||
)
|
||||
time.sleep(const.DAEMON_POLL_PERIOD)
|
||||
|
||||
@property
|
||||
def token(self):
|
||||
if self.__token is None:
|
||||
if not self.password:
|
||||
raise ConfigError("No password or token available to authenticate")
|
||||
url = f"{self.url}/api2/auth-token/"
|
||||
_lg.info("Fetching token: %s", url)
|
||||
r = requests.post(url, data={"username": self.user,
|
||||
"password": self.password})
|
||||
try:
|
||||
r = self.session.post(
|
||||
url,
|
||||
data={"username": self.user, "password": self.password},
|
||||
timeout=const.HTTP_TIMEOUT,
|
||||
)
|
||||
except requests.exceptions.RequestException as err:
|
||||
raise NetworkError(f"Can't reach {url}: {err}") from err
|
||||
if r.status_code != 200:
|
||||
raise RuntimeError(f"Can't get token: {r.text}")
|
||||
self.__token = r.json()['token']
|
||||
raise NetworkError(
|
||||
f"Can't get token from {url}: HTTP {r.status_code}: {r.text}"
|
||||
)
|
||||
self.__token = r.json()["token"]
|
||||
return self.__token
|
||||
|
||||
@cached_property_with_ttl(ttl=60)
|
||||
@@ -42,90 +114,273 @@ class SeafileClient:
|
||||
url = f"{self.url}/api2/repos/"
|
||||
_lg.info("Fetching remote libraries: %s", url)
|
||||
auth_header = {"Authorization": f"Token {self.token}"}
|
||||
r = requests.get(url, headers=auth_header)
|
||||
try:
|
||||
r = self.session.get(url, headers=auth_header, timeout=const.HTTP_TIMEOUT)
|
||||
except requests.exceptions.RequestException as err:
|
||||
raise NetworkError(f"Can't reach {url}: {err}") from err
|
||||
if r.status_code != 200:
|
||||
raise RuntimeError(r.text)
|
||||
raise NetworkError(f"Can't fetch {url}: HTTP {r.status_code}: {r.text}")
|
||||
r_libs = {lib["id"]: lib["name"] for lib in r.json()}
|
||||
return r_libs
|
||||
|
||||
@property
|
||||
def config_initialized(self) -> bool:
|
||||
return os.path.isdir(os.path.join(self.app_dir, ".ccnet"))
|
||||
|
||||
@property
|
||||
def daemon_ready(self) -> bool:
|
||||
cmd = ["seaf-cli", "status"]
|
||||
_lg.info("Checking seafile daemon status: %s", " ".join(cmd))
|
||||
proc = subprocess.run(
|
||||
self.__gen_cmd(cmd),
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
)
|
||||
return proc.returncode == 0
|
||||
|
||||
def init_config(self):
|
||||
if self.config_initialized:
|
||||
return
|
||||
cmd = ["seaf-cli", "init", "-d", self.app_dir]
|
||||
_lg.info("Initializing seafile config: %s", " ".join(cmd))
|
||||
self.__run(cmd)
|
||||
|
||||
def start_daemon(self):
|
||||
cmd = ["seaf-cli", "start"]
|
||||
_lg.info("Starting seafile daemon: %s", " ".join(cmd))
|
||||
self.__run(cmd)
|
||||
_lg.info("Waiting up to %ss for seafile daemon to start",
|
||||
const.DAEMON_START_TIMEOUT)
|
||||
self.__wait_for_daemon(True, const.DAEMON_START_TIMEOUT, "starting")
|
||||
_lg.info("Seafile daemon is ready")
|
||||
|
||||
def stop_daemon(self):
|
||||
cmd = ["seaf-cli", "stop"]
|
||||
_lg.info("Stopping seafile daemon: %s", " ".join(cmd))
|
||||
# A daemon that is already gone makes "stop" fail; the state below is
|
||||
# what matters, not this exit code.
|
||||
self.__run(cmd, check=False)
|
||||
_lg.info("Waiting up to %ss for seafile daemon to stop",
|
||||
const.DAEMON_STOP_TIMEOUT)
|
||||
self.__wait_for_daemon(False, const.DAEMON_STOP_TIMEOUT, "stopping")
|
||||
_lg.info("Seafile daemon is stopped")
|
||||
|
||||
def is_healthy(self) -> bool:
|
||||
"""
|
||||
Report whether the daemon process and its RPC socket both respond.
|
||||
|
||||
Used by the container's HEALTHCHECK. Neither check needs the Seafile
|
||||
server, so this works without a token or password.
|
||||
"""
|
||||
if not self.daemon_ready:
|
||||
return False
|
||||
try:
|
||||
self.rpc.get_repo_list(-1, -1)
|
||||
except Exception as err:
|
||||
_lg.warning("RPC endpoint is not responding: %s", err)
|
||||
return False
|
||||
return True
|
||||
|
||||
def get_library_id(self, library) -> Optional[str]:
|
||||
for lib_id, lib_name in self.remote_libraries.items():
|
||||
if library in (lib_id, lib_name):
|
||||
return lib_id
|
||||
return None
|
||||
"""
|
||||
Resolve a requested name or ID to the one library ID it names.
|
||||
|
||||
def sync_lib(self, lib_id: str, data_dir: str):
|
||||
lib_name = self.remote_libraries[lib_id]
|
||||
lib_dir = os.path.join(data_dir, lib_name.replace(' ', '_'))
|
||||
Library IDs are unique, but two libraries can share a name. Silently
|
||||
matching more than one and picking the first would sync whichever
|
||||
happened to come first in the server's response, not necessarily the
|
||||
one requested.
|
||||
"""
|
||||
matches = [lib_id for lib_id, lib_name in self.remote_libraries.items()
|
||||
if library in (lib_id, lib_name)]
|
||||
if len(matches) > 1:
|
||||
raise ConfigError(
|
||||
f"{library!r} matches {len(matches)} libraries on the server; "
|
||||
"use the library ID instead"
|
||||
)
|
||||
return matches[0] if matches else None
|
||||
|
||||
def sync_lib(self, lib_id: str, lib_dir: str) -> bool:
|
||||
"""
|
||||
Sync a library into an already resolved directory. The caller decides
|
||||
the directory, see dsc.paths.plan_lib_dirs: the name comes from the
|
||||
server and must not be turned into a path here.
|
||||
|
||||
Returns whether the library was accepted. One library that cannot be
|
||||
synced must not stop the others, so this reports instead of raising.
|
||||
"""
|
||||
create_dir(lib_dir)
|
||||
cmd = ['seaf-cli', 'sync',
|
||||
'-l', lib_id,
|
||||
'-s', self.url,
|
||||
'-d', lib_dir,
|
||||
'-u', self.user,
|
||||
'-p', self.password]
|
||||
_lg.info("Syncing library %s: %s", lib_name, ' '.join(hide_password(cmd, self.password)))
|
||||
subprocess.run(['su', '-', consts.DEFAULT_USERNAME, '-c', ' '.join(cmd)])
|
||||
cmd = [
|
||||
"seaf-cli",
|
||||
"sync",
|
||||
"-l", lib_id,
|
||||
"-s", self.url,
|
||||
"-d", lib_dir,
|
||||
"-u", self.user,
|
||||
# The token, not the password: seaf-cli ignores the password when a
|
||||
# token is given, and command arguments are visible to any process
|
||||
# in the container. A token can also be revoked on the server.
|
||||
"-T", self.token,
|
||||
]
|
||||
_lg.info(
|
||||
"Syncing library %s into %s: %s", lib_id, lib_dir,
|
||||
" ".join(hide_secrets(cmd, self.token, self.password)),
|
||||
)
|
||||
proc = self.__run(cmd, check=False)
|
||||
if proc.returncode != 0:
|
||||
_lg.error("Failed to sync library %s into %s: seaf-cli exited with %s",
|
||||
lib_id, lib_dir, proc.returncode)
|
||||
return False
|
||||
return True
|
||||
|
||||
def get_status(self):
|
||||
cmd = 'seaf-cli status'
|
||||
_lg.debug("Fetching seafile client status: %s", cmd)
|
||||
out = subprocess.check_output(['su', '-', consts.DEFAULT_USERNAME, '-c', cmd])
|
||||
out = out.decode().splitlines()
|
||||
def __print_tx_task(self, tx_task) -> str:
|
||||
""" Print transfer task status """
|
||||
try:
|
||||
percentage = tx_task.block_done / tx_task.block_total * 100
|
||||
tx_rate = tx_task.rate / 1024.0
|
||||
return f" {percentage:.1f}%, {tx_rate:.1f}KB/s"
|
||||
except ZeroDivisionError:
|
||||
return ""
|
||||
|
||||
def get_status(self) -> dict:
|
||||
""" Get status of all libraries """
|
||||
statuses = dict()
|
||||
for line in out:
|
||||
if line.startswith('#') or not line.strip():
|
||||
|
||||
# fetch statuses of libraries being cloned
|
||||
tasks = self.rpc.get_clone_tasks()
|
||||
for clone_task in tasks:
|
||||
if clone_task.state == "done":
|
||||
continue
|
||||
lib, status = line.split(sep='\t', maxsplit=1)
|
||||
lib = lib.strip()
|
||||
status = " ".join(status.split())
|
||||
statuses[lib] = status
|
||||
|
||||
elif clone_task.state == "fetch":
|
||||
statuses[clone_task.repo_name] = "downloading"
|
||||
tx_task = self.rpc.find_transfer_task(clone_task.repo_id)
|
||||
statuses[clone_task.repo_name] += self.__print_tx_task(tx_task)
|
||||
|
||||
elif clone_task.state == "error":
|
||||
err = self.rpc.sync_error_id_to_str(clone_task.error)
|
||||
statuses[clone_task.repo_name] = f"error: {err}"
|
||||
|
||||
else:
|
||||
statuses[clone_task.repo_name] = clone_task.state
|
||||
|
||||
# fetch statuses of synced libraries
|
||||
repos = self.rpc.get_repo_list(-1, -1)
|
||||
for repo in repos:
|
||||
auto_sync_enabled = self.rpc.is_auto_sync_enabled()
|
||||
if not auto_sync_enabled or not repo.auto_sync:
|
||||
statuses[repo.name] = "auto sync disabled"
|
||||
continue
|
||||
|
||||
sync_task = self.rpc.get_repo_sync_task(repo.id)
|
||||
if sync_task is None:
|
||||
statuses[repo.name] = "waiting for sync"
|
||||
|
||||
elif sync_task.state in ("uploading", "downloading"):
|
||||
statuses[repo.name] = sync_task.state
|
||||
tx_task = self.rpc.find_transfer_task(repo.id)
|
||||
|
||||
if sync_task.state == "downloading":
|
||||
if tx_task.rt_state == "data":
|
||||
statuses[repo.name] += " files"
|
||||
elif tx_task.rt_state == "fs":
|
||||
statuses[repo.name] += " file list"
|
||||
|
||||
statuses[repo.name] += self.__print_tx_task(tx_task)
|
||||
|
||||
elif sync_task.state == "error":
|
||||
err = self.rpc.sync_error_id_to_str(sync_task.error)
|
||||
statuses[repo.name] = f"error: {err}"
|
||||
|
||||
else:
|
||||
statuses[repo.name] = sync_task.state
|
||||
|
||||
return statuses
|
||||
|
||||
def watch_status(self):
|
||||
prev_status = dict()
|
||||
max_name_len = 0
|
||||
fmt = "Library {:%ds} {}" % max_name_len
|
||||
while True:
|
||||
time.sleep(consts.STATUS_POLL_PERIOD)
|
||||
cur_status = self.get_status()
|
||||
for folder, state in cur_status.items():
|
||||
if state != prev_status.get(folder):
|
||||
logging.info("Library %s:\t%s", folder, state)
|
||||
prev_status[folder] = cur_status[folder]
|
||||
time.sleep(const.STATUS_POLL_PERIOD)
|
||||
try:
|
||||
cur_status = self.get_status()
|
||||
except DscError:
|
||||
# A stop signal or another DscError must still end the loop;
|
||||
# only an unexpected RPC failure below is worth retrying.
|
||||
raise
|
||||
except Exception as err:
|
||||
# The daemon can restart under us; a status read caught mid
|
||||
# restart must not take the whole process down with it.
|
||||
# prev_status is left untouched, so the next successful read
|
||||
# still reports every real change since it, not just since
|
||||
# this failure.
|
||||
_lg.warning("Could not read sync status, retrying: %s", err,
|
||||
exc_info=err)
|
||||
continue
|
||||
for library, state in cur_status.items():
|
||||
if state != prev_status.get(library):
|
||||
if 30 > len(library) > max_name_len:
|
||||
max_name_len = len(library)
|
||||
fmt = "Library {:%ds} {}" % max_name_len
|
||||
logging.info(fmt.format(library, state))
|
||||
prev_status[library] = cur_status[library]
|
||||
|
||||
def get_local_libraries(self) -> set:
|
||||
cmd = 'seaf-cli list'
|
||||
_lg.info("Listing local libraries: %s", cmd)
|
||||
out = subprocess.check_output(['su', '-', consts.DEFAULT_USERNAME, '-c', cmd])
|
||||
out = out.decode().splitlines()[1:] # first line is a header
|
||||
# The display output is whitespace separated, so a library name or a
|
||||
# path containing a space cannot be parsed back apart. Ask for JSON.
|
||||
cmd = ["seaf-cli", "list", "--json"]
|
||||
_lg.info("Listing local libraries: %s", " ".join(cmd))
|
||||
out = self.__run(cmd, stdout=subprocess.PIPE).stdout
|
||||
|
||||
local_libs = set()
|
||||
for line in out:
|
||||
lib_name, lib_id, lib_path = line.rsplit(maxsplit=3)
|
||||
local_libs.add(lib_id)
|
||||
return local_libs
|
||||
try:
|
||||
libraries = json.loads(out.decode())
|
||||
except (UnicodeDecodeError, ValueError) as err:
|
||||
raise DaemonError(
|
||||
f"Cannot read the library list from seaf-cli: {err}"
|
||||
) from err
|
||||
|
||||
# Valid JSON is not necessarily the expected shape, and an unexpected
|
||||
# one must fail the same way rather than as a bare TypeError.
|
||||
try:
|
||||
return {lib["id"] for lib in libraries}
|
||||
except (KeyError, TypeError) as err:
|
||||
raise DaemonError(
|
||||
f"Unexpected library list from seaf-cli: {err}"
|
||||
) from err
|
||||
|
||||
def check_seaf_daemon_is_ready() -> bool:
|
||||
cmd = 'seaf-cli status'
|
||||
_lg.info("Checking seafile daemon status: %s", cmd)
|
||||
proc = subprocess.run(
|
||||
['su', '-', consts.DEFAULT_USERNAME, '-c', cmd],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL
|
||||
)
|
||||
return proc.returncode == 0
|
||||
def configure(self, args: argparse.Namespace, check_for_daemon: bool = True):
|
||||
need_restart = False
|
||||
# Options can be fetched or set only when daemon is running
|
||||
if check_for_daemon and not self.daemon_ready:
|
||||
self.start_daemon()
|
||||
|
||||
for key, value in args.__dict__.items():
|
||||
if key not in const.AVAILABLE_SEAFCLI_OPTIONS:
|
||||
continue
|
||||
|
||||
def start_seaf_daemon():
|
||||
cmd = 'seaf-cli start'
|
||||
_lg.info("Starting seafile daemon: %s", cmd)
|
||||
subprocess.run(['su', '-', consts.DEFAULT_USERNAME, '-c', cmd])
|
||||
_lg.info("Waiting for seafile daemon to start")
|
||||
if value is None:
|
||||
raise ConfigError(f"No value for seafile option {key}")
|
||||
|
||||
while True:
|
||||
if check_seaf_daemon_is_ready():
|
||||
break
|
||||
time.sleep(5)
|
||||
# check current value
|
||||
cmd = ["seaf-cli", "config", "-k", key]
|
||||
_lg.info("Checking seafile client option: %s", " ".join(cmd))
|
||||
proc = self.__run(cmd, stdout=subprocess.PIPE)
|
||||
# stdout looks like "option = value"
|
||||
cur_value = proc.stdout.decode().strip()
|
||||
try:
|
||||
cur_value = cur_value.split(sep="=")[1].strip()
|
||||
except IndexError:
|
||||
cur_value = None
|
||||
if cur_value == config_value(value):
|
||||
continue
|
||||
|
||||
_lg.info("Seafile daemon is ready")
|
||||
# set new value
|
||||
cmd = ["seaf-cli", "config", "-k", key, "-v", config_value(value)]
|
||||
_lg.info("Setting seafile client option: %s", " ".join(cmd))
|
||||
self.__run(cmd)
|
||||
need_restart = True
|
||||
|
||||
if need_restart:
|
||||
_lg.info("Restarting seafile daemon")
|
||||
self.stop_daemon()
|
||||
self.start_daemon()
|
||||
@@ -0,0 +1,66 @@
|
||||
"""Typed reading of the container's environment.
|
||||
|
||||
Everything in the environment is text, including values the client later
|
||||
compares as numbers or passes to seaf-cli. Reading them directly leaves two
|
||||
failures that are silent until much later: an unset variable becomes None and
|
||||
reaches seaf-cli as the string "None", and a numeric setting stays a string
|
||||
that never equals the integer it is compared against.
|
||||
"""
|
||||
|
||||
import os
|
||||
from typing import Optional
|
||||
|
||||
from dsc.errors import ConfigError
|
||||
|
||||
_TRUE_VALUES = {"true", "1", "yes", "on"}
|
||||
_FALSE_VALUES = {"false", "0", "no", "off"}
|
||||
|
||||
|
||||
def env_str(name: str, default: Optional[str] = None) -> Optional[str]:
|
||||
"""Return a text setting. An empty variable counts as unset."""
|
||||
value = os.getenv(name)
|
||||
if value is None or value == "":
|
||||
return default
|
||||
return value
|
||||
|
||||
|
||||
def env_int(name: str, default: int, minimum: int = 0) -> int:
|
||||
"""
|
||||
Return a numeric setting as an int, never as text and never as None.
|
||||
|
||||
Values below ``minimum`` are rejected: a negative speed limit or deletion
|
||||
threshold is not something to pass on to seaf-cli and hope for the best.
|
||||
"""
|
||||
raw = env_str(name)
|
||||
if raw is None:
|
||||
return default
|
||||
|
||||
stripped = raw.strip()
|
||||
try:
|
||||
value = int(stripped, 10)
|
||||
except ValueError:
|
||||
raise ConfigError(
|
||||
f"{name} must be a whole number, got {stripped!r}"
|
||||
)
|
||||
|
||||
if value < minimum:
|
||||
raise ConfigError(
|
||||
f"{name} must be {minimum} or greater, got {stripped!r}"
|
||||
)
|
||||
return value
|
||||
|
||||
|
||||
def env_bool(name: str, default: bool = False) -> bool:
|
||||
"""Return a boolean setting, accepting the usual spellings."""
|
||||
raw = env_str(name)
|
||||
if raw is None:
|
||||
return default
|
||||
|
||||
value = raw.strip().lower()
|
||||
if value in _TRUE_VALUES:
|
||||
return True
|
||||
if value in _FALSE_VALUES:
|
||||
return False
|
||||
|
||||
accepted = ", ".join(sorted(_TRUE_VALUES | _FALSE_VALUES))
|
||||
raise ConfigError(f"{name} must be one of {accepted}, got {raw.strip()!r}")
|
||||
@@ -0,0 +1,29 @@
|
||||
DEFAULT_APP_DIR = "/dsc"
|
||||
DEFAULT_LIBS_DIR = "/dsc/seafile"
|
||||
DEPRECATED_LIBS_DIR = "/data"
|
||||
DEFAULT_USERNAME = "seafile"
|
||||
STATUS_POLL_PERIOD = 1
|
||||
|
||||
# Bounds for daemon startup and shutdown, in seconds. The stop timeout has to
|
||||
# fit inside the grace period of "docker stop", which sends SIGKILL 10 seconds
|
||||
# after SIGTERM by default, otherwise shutdown is never graceful.
|
||||
DAEMON_POLL_PERIOD = 1
|
||||
DAEMON_START_TIMEOUT = 120
|
||||
DAEMON_STOP_TIMEOUT = 8
|
||||
|
||||
# Bounds for HTTP requests to the Seafile server. Without a request timeout,
|
||||
# a total=30/backoff_factor=2/backoff_max=60 retry policy was measured to
|
||||
# take about 26 minutes against an unreachable host before giving up, which
|
||||
# is indistinguishable from a hang. HTTP_TIMEOUT is (connect, read); the
|
||||
# retry budget below now bounds the worst case to a few minutes instead.
|
||||
HTTP_TIMEOUT = (10, 30)
|
||||
HTTP_RETRY_TOTAL = 5
|
||||
HTTP_RETRY_BACKOFF_FACTOR = 1
|
||||
HTTP_RETRY_BACKOFF_MAX = 30
|
||||
|
||||
AVAILABLE_SEAFCLI_OPTIONS = {
|
||||
"delete_confirm_threshold",
|
||||
"disable_verify_certificate",
|
||||
"upload_limit",
|
||||
"download_limit",
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
DEFAULT_USERNAME = "seafile"
|
||||
STATUS_POLL_PERIOD = 1
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Errors that must end the container with a useful message."""
|
||||
|
||||
|
||||
class DscError(Exception):
|
||||
"""Base class for failures that stop the client."""
|
||||
|
||||
|
||||
class ConfigError(DscError):
|
||||
"""The container was configured in a way that cannot be acted on."""
|
||||
|
||||
|
||||
class DaemonError(DscError):
|
||||
"""A seaf-cli command failed."""
|
||||
|
||||
|
||||
class DaemonTimeout(DscError):
|
||||
"""The daemon did not reach the expected state in time."""
|
||||
|
||||
|
||||
class NetworkError(DscError):
|
||||
"""A request to the Seafile server failed or exceeded its timeout."""
|
||||
|
||||
|
||||
class GracefulShutdown(DscError):
|
||||
"""SIGTERM or SIGINT was received; stop the daemon and exit cleanly."""
|
||||
+74
-5
@@ -2,15 +2,34 @@ import os
|
||||
import pwd
|
||||
import subprocess
|
||||
|
||||
from dsc.consts import DEFAULT_USERNAME
|
||||
from dsc.const import DEFAULT_USERNAME
|
||||
|
||||
|
||||
def setup_uid(uid: int, gid: int):
|
||||
"""
|
||||
Set GID and UID of default user so that seafile client creates files with
|
||||
correct permissions.
|
||||
If GID does not match, create a new group with the given GID.
|
||||
Then update UID and GID of default user to match the given ones.
|
||||
"""
|
||||
user_pwinfo = pwd.getpwnam(DEFAULT_USERNAME)
|
||||
create_group(gid)
|
||||
if user_pwinfo.pw_uid != uid or user_pwinfo.pw_gid != gid:
|
||||
subprocess.call(["usermod", "-o", "-u", str(uid), "-g", str(gid), DEFAULT_USERNAME])
|
||||
|
||||
|
||||
def create_group(gid: int):
|
||||
"""Search for a group with the given GID. If not found, create a new one."""
|
||||
if not os.path.exists(f"/etc/group"):
|
||||
raise RuntimeError(f"File /etc/group does not exist")
|
||||
with open("/etc/group", "r") as f:
|
||||
for line in f.readlines():
|
||||
cur_gid = line.split(sep=":", maxsplit=3)[2]
|
||||
if int(cur_gid) == gid:
|
||||
return
|
||||
subprocess.call(["groupadd", "-g", str(gid), DEFAULT_USERNAME + "-data"])
|
||||
|
||||
|
||||
def create_dir(dir_path: str):
|
||||
if not os.path.exists(dir_path):
|
||||
os.mkdir(dir_path)
|
||||
@@ -21,9 +40,59 @@ def create_dir(dir_path: str):
|
||||
raise RuntimeError(f"Data dir {dir_path} is not a directory")
|
||||
|
||||
|
||||
def hide_password(cmd: list, password: str) -> list:
|
||||
def user_cmd(argv: list) -> list:
|
||||
"""
|
||||
Return a command as-is, having already validated it is a plain argument
|
||||
list and never a shell string.
|
||||
|
||||
The process itself runs as the seafile user for its whole life after
|
||||
drop_privileges() (see start.py), so subprocess calls no longer need to
|
||||
be individually re-targeted with ``runuser``.
|
||||
"""
|
||||
if not isinstance(argv, list):
|
||||
raise TypeError(f"Command must be a list of arguments, got {type(argv).__name__}")
|
||||
return argv
|
||||
|
||||
|
||||
def drop_privileges(uid: int, gid: int):
|
||||
"""
|
||||
Permanently switch the current process to the given UID/GID.
|
||||
|
||||
Must run after setup_uid()/create_dir(), which need root, and before any
|
||||
other code, since everything from here on (the daemon, the RPC socket,
|
||||
the sync loop) runs as this user for the rest of the process's life.
|
||||
Order matters: supplementary groups and the GID must be set before the
|
||||
UID is dropped, since giving up root removes the permission to change
|
||||
them.
|
||||
"""
|
||||
user_pwinfo = pwd.getpwnam(DEFAULT_USERNAME)
|
||||
os.initgroups(DEFAULT_USERNAME, gid)
|
||||
os.setgid(gid)
|
||||
os.setuid(uid)
|
||||
os.environ["HOME"] = user_pwinfo.pw_dir
|
||||
os.environ["USER"] = DEFAULT_USERNAME
|
||||
os.environ["LOGNAME"] = DEFAULT_USERNAME
|
||||
|
||||
|
||||
def hide_secrets(cmd: list, *secrets: str) -> list:
|
||||
"""Mask every given secret in a command before it is logged."""
|
||||
cmd = cmd.copy()
|
||||
for i, arg in enumerate(cmd):
|
||||
if arg == password:
|
||||
cmd[i] = '********'
|
||||
for secret in secrets:
|
||||
if not secret:
|
||||
continue
|
||||
for i, arg in enumerate(cmd):
|
||||
if secret in arg:
|
||||
cmd[i] = arg.replace(secret, "********")
|
||||
return cmd
|
||||
|
||||
|
||||
def config_value(value) -> str:
|
||||
"""
|
||||
Render a setting the way seaf-cli stores it.
|
||||
|
||||
Booleans are written as "true" and "false": the daemon reads this setting
|
||||
with its boolean accessor, and Python's str() would produce "True".
|
||||
"""
|
||||
if isinstance(value, bool):
|
||||
return "true" if value else "false"
|
||||
return str(value)
|
||||
+101
@@ -0,0 +1,101 @@
|
||||
"""Turn server-provided library names into safe local directories.
|
||||
|
||||
Library names come from the Seafile server and are untrusted: a name is chosen
|
||||
by whoever can create a library, and it must never decide where the container
|
||||
writes. Every name is reduced to a single path component and every resulting
|
||||
path is proven to stay under the libraries directory.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
from collections import Counter
|
||||
|
||||
_lg = logging.getLogger(__name__)
|
||||
|
||||
# Whitespace is folded into underscores so that library names survive as
|
||||
# readable directory names, as they always have.
|
||||
_WHITESPACE_REPLACEMENT = "_"
|
||||
|
||||
# Names that are not usable as a directory of their own.
|
||||
_RESERVED_NAMES = {"", ".", "..", "..."}
|
||||
|
||||
# Length of the library id used to break ties between duplicate names.
|
||||
_ID_SUFFIX_LEN = 8
|
||||
|
||||
|
||||
class UnsafeLibraryName(ValueError):
|
||||
"""A library name cannot be mapped to a directory under the parent."""
|
||||
|
||||
|
||||
def lib_dirname(lib_name: str) -> str:
|
||||
"""
|
||||
Return the directory name for a library, or raise for a name that cannot
|
||||
be one. Shell metacharacters are ordinary filename characters here: nothing
|
||||
reaches a shell any more, so they are kept rather than mangled.
|
||||
"""
|
||||
if not isinstance(lib_name, str):
|
||||
raise UnsafeLibraryName(f"Library name is not a string: {lib_name!r}")
|
||||
|
||||
name = "".join(
|
||||
_WHITESPACE_REPLACEMENT if ch.isspace() else ch
|
||||
for ch in lib_name.strip()
|
||||
)
|
||||
|
||||
if "\0" in name:
|
||||
raise UnsafeLibraryName("Library name contains a null byte")
|
||||
if os.sep in name or (os.altsep and os.altsep in name):
|
||||
raise UnsafeLibraryName(f"Library name contains a path separator: {lib_name!r}")
|
||||
if name in _RESERVED_NAMES:
|
||||
raise UnsafeLibraryName(f"Library name is not usable as a directory: {lib_name!r}")
|
||||
|
||||
return name
|
||||
|
||||
|
||||
def resolve_lib_dir(parent_dir: str, dir_name: str) -> str:
|
||||
"""
|
||||
Resolve ``dir_name`` inside ``parent_dir`` and prove that the result stays
|
||||
there. Symlinks are resolved first, so an existing symlink inside the
|
||||
parent cannot be used to write outside it.
|
||||
"""
|
||||
parent = os.path.realpath(parent_dir)
|
||||
resolved = os.path.realpath(os.path.join(parent, dir_name))
|
||||
|
||||
if resolved != parent and not resolved.startswith(parent + os.sep):
|
||||
raise UnsafeLibraryName(
|
||||
f"Library directory {resolved} is outside {parent}"
|
||||
)
|
||||
if resolved == parent:
|
||||
raise UnsafeLibraryName(f"Library directory resolves to {parent} itself")
|
||||
|
||||
return resolved
|
||||
|
||||
|
||||
def plan_lib_dirs(libraries: dict, parent_dir: str) -> dict:
|
||||
"""
|
||||
Map library id to its directory for every library that can safely have one.
|
||||
|
||||
Libraries whose names collide after whitespace folding would otherwise
|
||||
share a directory and corrupt each other, so each of them is suffixed with
|
||||
the start of its own id. Unsafe names are skipped with a warning rather
|
||||
than aborting the sync of the remaining libraries.
|
||||
"""
|
||||
names = dict()
|
||||
for lib_id, lib_name in libraries.items():
|
||||
try:
|
||||
names[lib_id] = lib_dirname(lib_name)
|
||||
except UnsafeLibraryName as err:
|
||||
_lg.warning("Skipping library %s: %s", lib_id, err)
|
||||
|
||||
counts = Counter(names.values())
|
||||
duplicates = {name for name, count in counts.items() if count > 1}
|
||||
|
||||
plan = dict()
|
||||
for lib_id, name in names.items():
|
||||
if name in duplicates:
|
||||
name = f"{name}-{lib_id[:_ID_SUFFIX_LEN]}"
|
||||
try:
|
||||
plan[lib_id] = resolve_lib_dir(parent_dir, name)
|
||||
except UnsafeLibraryName as err:
|
||||
_lg.warning("Skipping library %s: %s", lib_id, err)
|
||||
|
||||
return plan
|
||||
@@ -0,0 +1,57 @@
|
||||
"""Read secrets from a variable or a mounted file.
|
||||
|
||||
Docker Compose and Swarm secrets arrive as files under /run/secrets, which
|
||||
keeps them out of the environment. Nothing here ever puts a secret value into
|
||||
a message: an error about a secret must not leak the secret.
|
||||
"""
|
||||
|
||||
import logging
|
||||
import os
|
||||
|
||||
from dsc.errors import ConfigError
|
||||
|
||||
_lg = logging.getLogger(__name__)
|
||||
|
||||
|
||||
def read_secret_file(path: str) -> str:
|
||||
"""
|
||||
Return the secret stored in ``path``.
|
||||
|
||||
Only trailing newlines are removed. Secret files are commonly written with
|
||||
one, and a password that silently carries it just fails to authenticate.
|
||||
Everything else, including surrounding spaces, is part of the secret.
|
||||
"""
|
||||
if not os.path.isfile(path):
|
||||
raise ConfigError(f"Secret file {path} does not exist or is not a file")
|
||||
|
||||
try:
|
||||
with open(path, "r") as f:
|
||||
secret = f.read()
|
||||
except OSError as err:
|
||||
raise ConfigError(f"Cannot read secret file {path}: {err.strerror}")
|
||||
|
||||
secret = secret.rstrip("\r\n")
|
||||
if not secret:
|
||||
raise ConfigError(f"Secret file {path} is empty")
|
||||
return secret
|
||||
|
||||
|
||||
def resolve_secret(name: str, value: str, file_path: str) -> str:
|
||||
"""
|
||||
Return the secret named ``name``, from either the variable or the file.
|
||||
|
||||
Supplying both is rejected rather than resolved by precedence: the two
|
||||
values are usually meant to be the same, and quietly picking one hides a
|
||||
misconfiguration until authentication fails.
|
||||
"""
|
||||
file_name = f"{name}_FILE"
|
||||
if value and file_path:
|
||||
raise ConfigError(
|
||||
f"{name} and {file_name} are both set; use exactly one of them"
|
||||
)
|
||||
|
||||
if file_path:
|
||||
_lg.info("Reading %s from %s", name, file_path)
|
||||
return read_secret_file(file_path)
|
||||
|
||||
return value or None
|
||||
@@ -0,0 +1,21 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Docker HEALTHCHECK entry point.
|
||||
|
||||
Exits 0 if the seafile daemon and its RPC socket both respond, 1 otherwise.
|
||||
Runs as a separate, short-lived process on every check, so it needs no
|
||||
credentials and touches no state the main process owns.
|
||||
"""
|
||||
|
||||
import sys
|
||||
|
||||
from dsc import const
|
||||
from dsc.client import SeafileClient
|
||||
|
||||
|
||||
def main() -> int:
|
||||
client = SeafileClient(host="unused", user="unused", app_dir=const.DEFAULT_APP_DIR)
|
||||
return 0 if client.is_healthy() else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,4 @@
|
||||
[pytest]
|
||||
testpaths = tests
|
||||
# The application is imported from the repository root, not installed.
|
||||
pythonpath = .
|
||||
@@ -0,0 +1,3 @@
|
||||
-r requirements.txt
|
||||
|
||||
pytest==9.2.0
|
||||
+2
-2
@@ -1,2 +1,2 @@
|
||||
cached_property==1.5.2
|
||||
requests==2.31.0
|
||||
cached_property==2.0.1
|
||||
requests==2.34.2
|
||||
@@ -3,50 +3,178 @@
|
||||
import argparse
|
||||
import logging
|
||||
import os
|
||||
import os.path
|
||||
import signal
|
||||
import sys
|
||||
|
||||
from dsc import SeafileClient, start_seaf_daemon
|
||||
from dsc.misc import setup_uid, create_dir
|
||||
from dsc import SeafileClient, const
|
||||
from dsc.config import env_bool, env_int, env_str
|
||||
from dsc.errors import ConfigError, DscError, GracefulShutdown
|
||||
from dsc.misc import setup_uid, create_dir, drop_privileges
|
||||
from dsc.paths import plan_lib_dirs
|
||||
from dsc.secrets import resolve_secret
|
||||
|
||||
_lg = logging.getLogger('dsc')
|
||||
|
||||
|
||||
def handle_signal(signum, frame):
|
||||
"""Turn a stop signal into an exception so the daemon is stopped on the
|
||||
way out instead of the container being killed with the daemon running."""
|
||||
raise GracefulShutdown(signal.Signals(signum).name)
|
||||
|
||||
|
||||
def install_signal_handlers():
|
||||
for signum in (signal.SIGTERM, signal.SIGINT):
|
||||
signal.signal(signum, handle_signal)
|
||||
|
||||
|
||||
def defaults_from_env() -> dict:
|
||||
"""
|
||||
Read every setting from the environment with its documented default.
|
||||
|
||||
Reading these directly leaves an unset variable as None, which reaches
|
||||
seaf-cli as the string "None" and silently replaces the documented value.
|
||||
"""
|
||||
return dict(
|
||||
server=env_str("SERVER_HOST"),
|
||||
username=env_str("USERNAME"),
|
||||
password=env_str("PASSWORD"),
|
||||
password_file=env_str("PASSWORD_FILE"),
|
||||
token=env_str("TOKEN"),
|
||||
token_file=env_str("TOKEN_FILE"),
|
||||
libraries=env_str("LIBRARY_ID"),
|
||||
uid=env_int("SEAFILE_UID", 1000),
|
||||
gid=env_int("SEAFILE_GID", 1000),
|
||||
upload_limit=env_int("UPLOAD_LIMIT", 0),
|
||||
download_limit=env_int("DOWNLOAD_LIMIT", 0),
|
||||
delete_confirm_threshold=env_int("DELETE_CONFIRM_THRESHOLD", 500),
|
||||
disable_verify_certificate=env_bool("DISABLE_VERIFY_CERTIFICATE", False),
|
||||
)
|
||||
|
||||
|
||||
def resolve_libraries(client, requested: str, server: str) -> set:
|
||||
"""Map the requested names or IDs to library IDs that are not synced yet."""
|
||||
requested_names = requested.split(sep=":")
|
||||
if any(name == "" for name in requested_names):
|
||||
raise ConfigError(
|
||||
f"library set must not contain an empty entry, got {requested!r}"
|
||||
)
|
||||
|
||||
libs_to_sync = set()
|
||||
for arg_lib in requested_names:
|
||||
lib_id = client.get_library_id(arg_lib)
|
||||
if lib_id:
|
||||
libs_to_sync.add(lib_id)
|
||||
else:
|
||||
_lg.warning("Library %s is not found on server %s", arg_lib, server)
|
||||
|
||||
# don't start to sync libraries already in sync
|
||||
return libs_to_sync - client.get_local_libraries()
|
||||
|
||||
|
||||
def run(client, args, libs_dir: str) -> int:
|
||||
"""
|
||||
Run the client lifecycle and return the process exit code. The daemon is
|
||||
always stopped on the way out, including on a failure or a stop signal.
|
||||
"""
|
||||
rc = 0
|
||||
try:
|
||||
client.init_config()
|
||||
client.start_daemon()
|
||||
client.configure(args, check_for_daemon=False)
|
||||
|
||||
libs_to_sync = resolve_libraries(client, args.libraries, args.server)
|
||||
|
||||
# Library names come from the server, so the directory for each one is
|
||||
# resolved and checked before anything is created or written.
|
||||
lib_dirs = plan_lib_dirs(
|
||||
{lib_id: client.remote_libraries[lib_id] for lib_id in libs_to_sync},
|
||||
libs_dir,
|
||||
)
|
||||
for lib_id, lib_dir in lib_dirs.items():
|
||||
client.sync_lib(lib_id, lib_dir)
|
||||
client.watch_status()
|
||||
except GracefulShutdown as err:
|
||||
_lg.info("Received %s, shutting down", err)
|
||||
except DscError as err:
|
||||
_lg.error("%s", err)
|
||||
rc = 1
|
||||
|
||||
try:
|
||||
client.stop_daemon()
|
||||
except DscError as err:
|
||||
_lg.error("Could not stop seafile daemon cleanly: %s", err)
|
||||
rc = 1
|
||||
return rc
|
||||
|
||||
|
||||
def main():
|
||||
logging.basicConfig(format="%(asctime)s %(message)s", level=logging.INFO)
|
||||
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--uid", default=os.getenv("SEAFILE_UID", default=1000), type=int)
|
||||
parser.add_argument("--gid", default=os.getenv("SEAFILE_GID", default=100), type=int)
|
||||
parser.add_argument("--data-dir", default=os.getenv("DATA_DIR", default="/data"))
|
||||
parser.add_argument("--host", default=os.getenv("SERVER_HOST"))
|
||||
parser.add_argument("--username", default=os.getenv("USERNAME"))
|
||||
parser.add_argument("--password", default=os.getenv("PASSWORD"))
|
||||
parser.add_argument("--libs", default=os.getenv("LIBRARY_ID"))
|
||||
parser.add_argument("-s", "--server")
|
||||
parser.add_argument("-u", "--username")
|
||||
parser.add_argument("-p", "--password")
|
||||
parser.add_argument("--password-file")
|
||||
parser.add_argument("-T", "--token")
|
||||
parser.add_argument("--token-file")
|
||||
parser.add_argument("-l", "--libraries")
|
||||
parser.add_argument("--uid", type=int)
|
||||
parser.add_argument("--gid", type=int)
|
||||
parser.add_argument("--upload-limit", type=int, default=0)
|
||||
parser.add_argument("--download-limit", type=int, default=0)
|
||||
parser.add_argument("--disable-verify-certificate", action="store_true")
|
||||
parser.add_argument("--delete-confirm-threshold", type=int, default=500)
|
||||
|
||||
try:
|
||||
parser.set_defaults(**defaults_from_env())
|
||||
except ConfigError as err:
|
||||
_lg.error("%s", err)
|
||||
return 2
|
||||
args = parser.parse_args()
|
||||
if not args.server:
|
||||
parser.error("Seafile server is not specified")
|
||||
if not args.username:
|
||||
parser.error("username is not specified")
|
||||
if not args.libraries:
|
||||
parser.error("library is not specified")
|
||||
if args.uid == 0:
|
||||
parser.error("uid must not be 0; running the daemon as root defeats "
|
||||
"the point of --uid/SEAFILE_UID")
|
||||
if args.gid == 0:
|
||||
parser.error("gid must not be 0 (the root group); running the daemon "
|
||||
"with it defeats the point of --gid/SEAFILE_GID")
|
||||
|
||||
try:
|
||||
password = resolve_secret("PASSWORD", args.password, args.password_file)
|
||||
token = resolve_secret("TOKEN", args.token, args.token_file)
|
||||
except ConfigError as err:
|
||||
_lg.error("%s", err)
|
||||
return 2
|
||||
if not password and not token:
|
||||
parser.error("neither a password nor a token is specified")
|
||||
if password and token:
|
||||
# seaf-cli behaves the same way: a token makes the password unused.
|
||||
_lg.info("Both a password and a token are configured; using the token")
|
||||
|
||||
install_signal_handlers()
|
||||
|
||||
setup_uid(args.uid, args.gid)
|
||||
create_dir(args.data_dir)
|
||||
start_seaf_daemon()
|
||||
create_dir(const.DEFAULT_APP_DIR)
|
||||
drop_privileges(args.uid, args.gid)
|
||||
|
||||
libs_to_sync = set()
|
||||
client = SeafileClient(args.server, args.username, password,
|
||||
const.DEFAULT_APP_DIR, token=token)
|
||||
|
||||
client = SeafileClient(args.host, args.username, args.password)
|
||||
for arg_lib in args.libs.split(sep=":"):
|
||||
lib_id = client.get_library_id(arg_lib)
|
||||
if lib_id:
|
||||
libs_to_sync.add(lib_id)
|
||||
else:
|
||||
_lg.warning("Library %s is not found on server %s", arg_lib, args.host)
|
||||
# check for deprecated /data directory
|
||||
if os.path.isdir(const.DEPRECATED_LIBS_DIR):
|
||||
_lg.warning("*** DEPRECATED DIRECTORY FOUND ***")
|
||||
_lg.warning("Deprecated directory %s is found, please mount your host directory with"
|
||||
" libraries to %s instead", const.DEPRECATED_LIBS_DIR, const.DEFAULT_LIBS_DIR)
|
||||
libs_dir = const.DEPRECATED_LIBS_DIR
|
||||
else:
|
||||
libs_dir = const.DEFAULT_LIBS_DIR
|
||||
|
||||
# don't start to sync libraries already in sync
|
||||
libs_to_sync -= client.get_local_libraries()
|
||||
|
||||
for lib_id in libs_to_sync:
|
||||
client.sync_lib(lib_id, args.data_dir)
|
||||
client.watch_status()
|
||||
|
||||
return 0
|
||||
return run(client, args, libs_dir)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
|
||||
@@ -0,0 +1,53 @@
|
||||
"""Make ``dsc.client`` importable outside the container.
|
||||
|
||||
``seafile`` and ``pysearpc`` ship with the Seafile CLI AppImage and only exist
|
||||
inside the image. The application tests must not need a live server or that
|
||||
AppImage, so a stub module stands in for the RPC client.
|
||||
"""
|
||||
|
||||
import sys
|
||||
import types
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
|
||||
|
||||
def _install_seafile_stub():
|
||||
if "seafile" in sys.modules:
|
||||
return
|
||||
seafile = types.ModuleType("seafile")
|
||||
seafile.RpcClient = mock.MagicMock(name="RpcClient")
|
||||
sys.modules["seafile"] = seafile
|
||||
|
||||
|
||||
_install_seafile_stub()
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def fresh_rpc_client(monkeypatch):
|
||||
"""
|
||||
Give every test its own RPC client mock.
|
||||
|
||||
A single module-level mock returns the same ``RpcClient()`` object to every
|
||||
test, so changes one test makes to it leak into the next. One such leak:
|
||||
when ``monkeypatch.setattr`` patches a method on that object, undoing the
|
||||
patch deletes the attribute, and a deleted attribute on a ``MagicMock``
|
||||
stays deleted.
|
||||
"""
|
||||
monkeypatch.setattr(sys.modules["seafile"], "RpcClient", mock.MagicMock(name="RpcClient"))
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def no_network(monkeypatch):
|
||||
"""
|
||||
Fail loudly instead of reaching the network.
|
||||
|
||||
The client retries failed requests with backoff, so a test that
|
||||
accidentally makes a real request appears to hang rather than fail.
|
||||
"""
|
||||
import requests
|
||||
|
||||
def blocked(self, method, url, *args, **kwargs):
|
||||
raise AssertionError(f"Test attempted a real request: {method} {url}")
|
||||
|
||||
monkeypatch.setattr(requests.Session, "request", blocked)
|
||||
Executable
+277
@@ -0,0 +1,277 @@
|
||||
#!/usr/bin/env bash
|
||||
#
|
||||
# Container smoke test: exercises the built image, not the source tree.
|
||||
#
|
||||
# Everything here needs the real seaf-cli and seaf-daemon from the image, so
|
||||
# it cannot run in the unit test job. Usage:
|
||||
#
|
||||
# tests/smoke.sh [image] # native architecture
|
||||
# PLATFORM=linux/amd64 tests/smoke.sh # the AppImage is x86_64 only
|
||||
#
|
||||
set -uo pipefail
|
||||
|
||||
IMAGE="${1:-snegov/seafile-client:ci}"
|
||||
PLATFORM_ARG=""
|
||||
[ -n "${PLATFORM:-}" ] && PLATFORM_ARG="--platform ${PLATFORM}"
|
||||
|
||||
WORK=$(mktemp -d "${PWD}/.smoke-XXXXXX")
|
||||
trap 'rm -rf "$WORK"; docker rm -f dsc-smoke >/dev/null 2>&1 || true' EXIT
|
||||
|
||||
failures=0
|
||||
|
||||
pass() { printf ' ok %s\n' "$1"; }
|
||||
fail() { printf ' FAIL %s\n' "$1"; failures=$((failures + 1)); }
|
||||
|
||||
check() { # check <description> <expected> <actual>
|
||||
if [ "$2" = "$3" ]; then pass "$1"; else
|
||||
fail "$1"; printf ' expected %s, got %s\n' "$2" "$3"
|
||||
fi
|
||||
}
|
||||
|
||||
run() { docker run --rm $PLATFORM_ARG "$@"; }
|
||||
|
||||
echo "== imports and pinned client version"
|
||||
# The exit status matters as much as the output: a traceback also prints a
|
||||
# non-empty last line, and must not be mistaken for a version.
|
||||
if out=$(run "$IMAGE" python3 -c "
|
||||
import os, seafile, pysearpc, dsc.client, dsc.misc, dsc.paths, dsc.secrets, dsc.config
|
||||
print('VERSION', os.environ['SEAFILE_CLI_VERSION'])" 2>&1); then
|
||||
version=$(printf '%s\n' "$out" | sed -n 's/^VERSION //p')
|
||||
case "$version" in
|
||||
[0-9]*.[0-9]*) pass "imports resolve, seafile client version is $version" ;;
|
||||
*) fail "no usable version reported, output was: $out" ;;
|
||||
esac
|
||||
else
|
||||
fail "imports or SEAFILE_CLI_VERSION failed: $out"
|
||||
fi
|
||||
|
||||
echo "== the real daemon starts, reports ready, and stops"
|
||||
out=$(run "$IMAGE" python3 -c "
|
||||
from dsc.client import SeafileClient
|
||||
c = SeafileClient('example.invalid', 'u', 'pw', '/dsc', token='tok')
|
||||
c.init_config()
|
||||
c.start_daemon()
|
||||
ready = c.daemon_ready
|
||||
c.stop_daemon()
|
||||
print('READY', ready, 'STOPPED', not c.daemon_ready)" 2>&1 | tail -1)
|
||||
check "daemon lifecycle" "READY True STOPPED True" "$out"
|
||||
|
||||
echo "== docker stop shuts the daemon down gracefully"
|
||||
docker rm -f dsc-smoke >/dev/null 2>&1 || true
|
||||
docker run -d $PLATFORM_ARG --name dsc-smoke "$IMAGE" python3 -c "
|
||||
import argparse, logging, time
|
||||
import start
|
||||
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)
|
||||
from dsc.client import SeafileClient
|
||||
|
||||
def watch():
|
||||
print('WATCHING', flush=True)
|
||||
while True:
|
||||
time.sleep(0.2)
|
||||
|
||||
c = SeafileClient('example.invalid', 'u', 'pw', '/dsc', token='tok')
|
||||
# The daemon is real; the server is not. Nothing here may reach the network,
|
||||
# so library lookup is stubbed and only the lifecycle is exercised.
|
||||
c.watch_status = watch
|
||||
c.get_library_id = lambda name: None
|
||||
c.get_local_libraries = lambda: set()
|
||||
|
||||
start.install_signal_handlers()
|
||||
raise SystemExit(
|
||||
start.run(c, argparse.Namespace(libraries='none', server='s'), '/dsc/seafile')
|
||||
)
|
||||
" >/dev/null
|
||||
|
||||
# Wait for the daemon to be up and the process to be in its watch loop. If it
|
||||
# never gets there the shutdown assertions mean nothing, so say so loudly
|
||||
# instead of measuring the shutdown of something that already exited.
|
||||
watching=0
|
||||
for _ in $(seq 1 60); do
|
||||
if docker logs dsc-smoke 2>&1 | grep -q WATCHING; then watching=1; break; fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
if [ "$watching" -eq 0 ]; then
|
||||
fail "the container never reached its watch loop, shutdown not measured"
|
||||
printf ' container log:\n'
|
||||
docker logs dsc-smoke 2>&1 | sed 's/^/ /' | tail -20
|
||||
docker rm -f dsc-smoke >/dev/null
|
||||
echo
|
||||
echo "smoke test failed: $failures check(s)"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
started=$(date +%s)
|
||||
docker stop dsc-smoke >/dev/null
|
||||
elapsed=$(( $(date +%s) - started ))
|
||||
code=$(docker inspect -f '{{.State.ExitCode}}' dsc-smoke)
|
||||
|
||||
check "graceful shutdown exit code" "0" "$code"
|
||||
if [ "$elapsed" -lt 10 ]; then
|
||||
pass "docker stop returned in ${elapsed}s, inside the 10s grace period"
|
||||
else
|
||||
fail "docker stop took ${elapsed}s, the process was killed"
|
||||
fi
|
||||
if docker logs dsc-smoke 2>&1 | grep -q "Seafile daemon is stopped"; then
|
||||
pass "the daemon was stopped on the way out"
|
||||
else
|
||||
fail "the daemon was not stopped on the way out"
|
||||
fi
|
||||
docker rm -f dsc-smoke >/dev/null
|
||||
|
||||
echo "== a killed daemon does not crash the watch loop"
|
||||
docker rm -f dsc-smoke >/dev/null 2>&1 || true
|
||||
docker run -d $PLATFORM_ARG --name dsc-smoke "$IMAGE" python3 -c "
|
||||
import logging
|
||||
logging.basicConfig(format='%(asctime)s %(message)s', level=logging.INFO)
|
||||
from dsc.client import SeafileClient
|
||||
|
||||
c = SeafileClient('example.invalid', 'u', 'pw', '/dsc', token='tok')
|
||||
c.init_config()
|
||||
c.start_daemon()
|
||||
c.watch_status() # the real thing, not a stub: this is what is under test
|
||||
" >/dev/null
|
||||
|
||||
started=0
|
||||
for _ in $(seq 1 30); do
|
||||
logs=$(docker logs dsc-smoke 2>&1)
|
||||
if printf '%s' "$logs" | grep -q "Seafile daemon is ready"; then started=1; break; fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
if [ "$started" -eq 0 ]; then
|
||||
fail "the daemon never became ready, kill scenario not measured"
|
||||
else
|
||||
# No procps in the image, so find the PID by hand instead of pkill.
|
||||
docker exec dsc-smoke sh -c '
|
||||
for p in /proc/[0-9]*; do
|
||||
[ "$(cat "$p/comm" 2>/dev/null)" = "seaf-daemon" ] && kill -9 "${p#/proc/}"
|
||||
done' >/dev/null 2>&1
|
||||
recovered=0
|
||||
for _ in $(seq 1 30); do
|
||||
logs=$(docker logs dsc-smoke 2>&1)
|
||||
if printf '%s' "$logs" | grep -q "Could not read sync status"; then recovered=1; break; fi
|
||||
sleep 1
|
||||
done
|
||||
if [ "$recovered" -eq 1 ] && [ "$(docker inspect -f '{{.State.Running}}' dsc-smoke)" = "true" ]; then
|
||||
pass "the watch loop logged the failure and kept the container running"
|
||||
else
|
||||
fail "the container did not survive a killed daemon"
|
||||
docker logs dsc-smoke 2>&1 | sed 's/^/ /' | tail -20
|
||||
fi
|
||||
fi
|
||||
docker rm -f dsc-smoke >/dev/null
|
||||
|
||||
echo "== the HEALTHCHECK command through the real entrypoint"
|
||||
# Runs through main(), unlike the fixture above: HOME/UID/GID come from the
|
||||
# same drop_privileges() path a real deployment uses, so .ccnet ends up
|
||||
# under /dsc like it does in production, not under root's home directory.
|
||||
docker rm -f dsc-smoke >/dev/null 2>&1 || true
|
||||
docker run -d $PLATFORM_ARG --name dsc-smoke \
|
||||
-e SERVER_HOST=example.invalid -e USERNAME=u -e PASSWORD=p -e LIBRARY_ID=x \
|
||||
"$IMAGE" >/dev/null
|
||||
|
||||
ready=0
|
||||
for _ in $(seq 1 30); do
|
||||
logs=$(docker logs dsc-smoke 2>&1)
|
||||
if printf '%s' "$logs" | grep -q "Seafile daemon is ready"; then ready=1; break; fi
|
||||
sleep 1
|
||||
done
|
||||
|
||||
if [ "$ready" -eq 0 ]; then
|
||||
fail "the daemon never became ready, HEALTHCHECK not measured"
|
||||
else
|
||||
if docker exec dsc-smoke runuser -u seafile -- python3 /dsc/healthcheck.py; then
|
||||
pass "HEALTHCHECK command exits 0 while the daemon is up"
|
||||
else
|
||||
fail "HEALTHCHECK command did not exit 0 while the daemon was up"
|
||||
fi
|
||||
fi
|
||||
docker rm -f dsc-smoke >/dev/null
|
||||
|
||||
echo "== the HEALTHCHECK command reports unhealthy when the daemon is down"
|
||||
docker rm -f dsc-smoke >/dev/null 2>&1 || true
|
||||
docker run -d $PLATFORM_ARG --name dsc-smoke "$IMAGE" sleep 60 >/dev/null
|
||||
if docker exec dsc-smoke runuser -u seafile -- python3 /dsc/healthcheck.py; then
|
||||
fail "HEALTHCHECK command exited 0 with no daemon running"
|
||||
else
|
||||
pass "HEALTHCHECK command exits nonzero with no daemon running"
|
||||
fi
|
||||
docker rm -f dsc-smoke >/dev/null
|
||||
|
||||
echo "== configuration errors stop the container with a useful message"
|
||||
out=$(docker run --rm $PLATFORM_ARG -e SERVER_HOST=h -e USERNAME=u -e LIBRARY_ID=x "$IMAGE" 2>&1; echo "rc=$?")
|
||||
check "no credentials exits 2" "rc=2" "$(echo "$out" | tail -1)"
|
||||
|
||||
out=$(docker run --rm $PLATFORM_ARG -e SERVER_HOST=h -e USERNAME=u -e LIBRARY_ID=x \
|
||||
-e PASSWORD=p -e PASSWORD_FILE=/run/secrets/pw "$IMAGE" 2>&1)
|
||||
if echo "$out" | grep -q "PASSWORD_FILE are both set"; then
|
||||
pass "conflicting secret sources are rejected by name"
|
||||
else
|
||||
fail "conflicting secret sources not reported: $(echo "$out" | tail -1)"
|
||||
fi
|
||||
|
||||
out=$(docker run --rm $PLATFORM_ARG -e SERVER_HOST=h -e USERNAME=u -e PASSWORD=p \
|
||||
-e LIBRARY_ID=x -e UPLOAD_LIMIT=-5 "$IMAGE" 2>&1)
|
||||
if echo "$out" | grep -q "UPLOAD_LIMIT must be 0 or greater"; then
|
||||
pass "a negative limit is rejected by name"
|
||||
else
|
||||
fail "negative limit not reported: $(echo "$out" | tail -1)"
|
||||
fi
|
||||
|
||||
out=$(docker run --rm $PLATFORM_ARG -e SERVER_HOST=h -e USERNAME=u -e PASSWORD=p \
|
||||
-e LIBRARY_ID=x -e SEAFILE_UID=0 "$IMAGE" 2>&1; echo "rc=$?")
|
||||
if echo "$out" | grep -q "uid must not be 0" && [ "$(echo "$out" | tail -1)" = "rc=2" ]; then
|
||||
pass "SEAFILE_UID=0 is rejected"
|
||||
else
|
||||
fail "SEAFILE_UID=0 not rejected: $out"
|
||||
fi
|
||||
|
||||
out=$(docker run --rm $PLATFORM_ARG -e SERVER_HOST=h -e USERNAME=u -e PASSWORD=p \
|
||||
-e LIBRARY_ID=x -e SEAFILE_GID=0 "$IMAGE" 2>&1; echo "rc=$?")
|
||||
if echo "$out" | grep -q "gid must not be 0" && [ "$(echo "$out" | tail -1)" = "rc=2" ]; then
|
||||
pass "SEAFILE_GID=0 is rejected"
|
||||
else
|
||||
fail "SEAFILE_GID=0 not rejected: $out"
|
||||
fi
|
||||
|
||||
echo "== a mounted secret is read and stays out of the environment"
|
||||
printf 's3cret-from-file\n' > "$WORK/pw"
|
||||
out=$(docker run --rm $PLATFORM_ARG -v "$WORK/pw:/run/secrets/pw:ro" \
|
||||
-e PASSWORD_FILE=/run/secrets/pw "$IMAGE" python3 -c "
|
||||
import os
|
||||
from dsc.secrets import resolve_secret
|
||||
secret = resolve_secret('PASSWORD', os.getenv('PASSWORD'), os.getenv('PASSWORD_FILE'))
|
||||
print(secret, 'PASSWORD' in os.environ)" 2>&1 | tail -1)
|
||||
check "secret file read, password absent from the environment" \
|
||||
"s3cret-from-file False" "$out"
|
||||
|
||||
echo "== the process drops root after setup and reaches the target uid/gid"
|
||||
out=$(run "$IMAGE" python3 -c "
|
||||
import os
|
||||
from dsc.misc import setup_uid, create_dir, drop_privileges
|
||||
from dsc import const
|
||||
setup_uid(1000, 1000)
|
||||
create_dir(const.DEFAULT_APP_DIR)
|
||||
drop_privileges(1000, 1000)
|
||||
print(os.getuid(), os.getgid(), os.environ['USER'])" 2>&1 | tail -1)
|
||||
check "process runs as the target non-root user after drop_privileges" \
|
||||
"1000 1000 seafile" "$out"
|
||||
|
||||
echo "== a default container gets the documented defaults"
|
||||
out=$(run "$IMAGE" python3 -c "
|
||||
import start
|
||||
from dsc.misc import config_value
|
||||
d = start.defaults_from_env()
|
||||
print(*(config_value(d[k]) for k in (
|
||||
'upload_limit', 'download_limit', 'delete_confirm_threshold',
|
||||
'uid', 'gid', 'disable_verify_certificate')))" 2>&1 | tail -1)
|
||||
check "documented defaults" "0 0 500 1000 1000 false" "$out"
|
||||
|
||||
echo
|
||||
if [ "$failures" -eq 0 ]; then
|
||||
echo "smoke test passed"
|
||||
else
|
||||
echo "smoke test failed: $failures check(s)"
|
||||
fi
|
||||
exit $((failures > 0))
|
||||
@@ -0,0 +1,306 @@
|
||||
"""Every subprocess must be an argument list, never a shell string."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
|
||||
import pytest
|
||||
|
||||
from dsc import client as client_module
|
||||
from dsc.errors import ConfigError, DaemonError
|
||||
from dsc.client import SeafileClient
|
||||
from dsc.misc import hide_secrets, user_cmd, drop_privileges
|
||||
|
||||
# Values that would be interpreted by a shell if a command were ever joined
|
||||
# into a string and handed to ``su -c``.
|
||||
SHELL_METACHARACTERS = [
|
||||
'pa"ss',
|
||||
"pa'ss",
|
||||
"pa$(id)ss",
|
||||
"pa`id`ss",
|
||||
"pass; rm -rf /",
|
||||
"pass && curl evil.example",
|
||||
"pass | tee /tmp/x",
|
||||
"pass\nrm -rf /",
|
||||
"pass with spaces",
|
||||
"pass\\backslash",
|
||||
"паssшörд",
|
||||
]
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return SeafileClient(
|
||||
host="seafile.example",
|
||||
user="user@example",
|
||||
passwd="s3cret",
|
||||
app_dir="/dsc",
|
||||
token="tok-en",
|
||||
)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def calls(monkeypatch):
|
||||
"""Capture every subprocess invocation instead of running it."""
|
||||
recorded = []
|
||||
|
||||
def fake_run(argv, **kwargs):
|
||||
recorded.append((argv, kwargs))
|
||||
return subprocess.CompletedProcess(argv, 0, stdout=b"")
|
||||
|
||||
monkeypatch.setattr(subprocess, "run", fake_run)
|
||||
# Directory creation is covered by the path tests; keep the real
|
||||
# filesystem out of command construction.
|
||||
monkeypatch.setattr(client_module, "create_dir", lambda path: None)
|
||||
return recorded
|
||||
|
||||
|
||||
def test_user_cmd_returns_the_command_unchanged():
|
||||
# The process itself runs as the seafile user after drop_privileges(),
|
||||
# so no per-call re-targeting is needed any more.
|
||||
argv = user_cmd(["seaf-cli", "status"])
|
||||
assert argv == ["seaf-cli", "status"]
|
||||
|
||||
|
||||
def test_user_cmd_never_invokes_a_shell():
|
||||
argv = user_cmd(["seaf-cli", "sync", "-d", "a; rm -rf /"])
|
||||
assert "-c" not in argv
|
||||
assert not any(arg.endswith("sh") for arg in argv)
|
||||
# The dangerous value stays a single, unsplit argument.
|
||||
assert argv[-1] == "a; rm -rf /"
|
||||
|
||||
|
||||
def test_user_cmd_rejects_a_string():
|
||||
with pytest.raises(TypeError):
|
||||
user_cmd("seaf-cli status")
|
||||
|
||||
|
||||
class FakePwInfo:
|
||||
pw_dir = "/dsc"
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_pwnam(monkeypatch):
|
||||
monkeypatch.setattr("pwd.getpwnam", lambda name: FakePwInfo())
|
||||
|
||||
|
||||
def test_drop_privileges_sets_groups_before_gid_before_uid(monkeypatch, fake_pwnam):
|
||||
"""Order matters: root is needed for each step, and is gone after setuid."""
|
||||
calls = []
|
||||
monkeypatch.setattr("os.initgroups", lambda user, gid: calls.append(("initgroups", user, gid)))
|
||||
monkeypatch.setattr("os.setgid", lambda gid: calls.append(("setgid", gid)))
|
||||
monkeypatch.setattr("os.setuid", lambda uid: calls.append(("setuid", uid)))
|
||||
|
||||
drop_privileges(1000, 1000)
|
||||
|
||||
assert [c[0] for c in calls] == ["initgroups", "setgid", "setuid"]
|
||||
|
||||
|
||||
def test_drop_privileges_sets_the_target_environment(monkeypatch, fake_pwnam):
|
||||
monkeypatch.setattr("os.initgroups", lambda user, gid: None)
|
||||
monkeypatch.setattr("os.setgid", lambda gid: None)
|
||||
monkeypatch.setattr("os.setuid", lambda uid: None)
|
||||
# drop_privileges() writes os.environ directly, not through monkeypatch,
|
||||
# so register the keys with monkeypatch first to have it restore them.
|
||||
for key in ("HOME", "USER", "LOGNAME"):
|
||||
monkeypatch.delenv(key, raising=False)
|
||||
|
||||
drop_privileges(1000, 1000)
|
||||
|
||||
assert os.environ["USER"] == "seafile"
|
||||
assert os.environ["LOGNAME"] == "seafile"
|
||||
assert os.environ["HOME"]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("secret", SHELL_METACHARACTERS)
|
||||
def test_sync_passes_the_token_as_one_unquoted_argument(client, calls, secret):
|
||||
client._SeafileClient__token = secret
|
||||
client.sync_lib("lib-id", "/dsc/seafile/Docs")
|
||||
|
||||
argv, _ = calls[-1]
|
||||
assert argv[argv.index("-T") + 1] == secret
|
||||
|
||||
|
||||
def test_sync_authenticates_with_the_token_not_the_password(client, calls):
|
||||
client.sync_lib("lib-id", "/dsc/seafile/Docs")
|
||||
|
||||
argv, _ = calls[-1]
|
||||
assert "-p" not in argv, "the account password must never reach argv"
|
||||
assert client.password not in argv
|
||||
|
||||
|
||||
@pytest.mark.parametrize("lib_dir", [
|
||||
"/dsc/seafile/a\"; touch /tmp/pwned; #",
|
||||
"/dsc/seafile/$(id)",
|
||||
"/dsc/seafile/`id`",
|
||||
"/dsc/seafile/name with spaces",
|
||||
])
|
||||
def test_sync_passes_library_dir_as_one_argument(client, calls, lib_dir):
|
||||
client.sync_lib("lib-id", lib_dir)
|
||||
|
||||
argv, _ = calls[-1]
|
||||
assert argv[argv.index("-d") + 1] == lib_dir
|
||||
|
||||
|
||||
def test_sync_command_is_a_list_of_strings(client, calls):
|
||||
client.sync_lib("lib-id", "/dsc/seafile/Docs")
|
||||
|
||||
argv, kwargs = calls[-1]
|
||||
assert isinstance(argv, list)
|
||||
assert all(isinstance(arg, str) for arg in argv)
|
||||
assert kwargs.get("shell") is not True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("secret", SHELL_METACHARACTERS)
|
||||
def test_sync_never_logs_the_token_or_the_password(client, calls, caplog, secret):
|
||||
client._SeafileClient__token = secret
|
||||
client.password = secret + "-pw"
|
||||
with caplog.at_level("INFO"):
|
||||
client.sync_lib("lib-id", "/dsc/seafile/Docs")
|
||||
|
||||
assert secret not in caplog.text
|
||||
assert client.password not in caplog.text
|
||||
|
||||
|
||||
def test_hide_secrets_masks_every_occurrence():
|
||||
masked = hide_secrets(["-p", "secret", "-u", "secret-user"], "secret")
|
||||
assert masked == ["-p", "********", "-u", "********-user"]
|
||||
|
||||
|
||||
def test_hide_secrets_masks_several_secrets():
|
||||
masked = hide_secrets(["-p", "pw", "-T", "tok"], "pw", "tok")
|
||||
assert masked == ["-p", "********", "-T", "********"]
|
||||
|
||||
|
||||
def test_hide_secrets_ignores_secrets_that_are_not_set():
|
||||
assert hide_secrets(["-T", "tok"], None, "tok") == ["-T", "********"]
|
||||
|
||||
|
||||
def test_hide_secrets_does_not_mutate_the_original():
|
||||
argv = ["-p", "secret"]
|
||||
hide_secrets(argv, "secret")
|
||||
assert argv == ["-p", "secret"]
|
||||
|
||||
|
||||
def test_configure_passes_option_values_as_arguments(client, calls, monkeypatch):
|
||||
# Changing an option restarts the daemon, and that restart polls without a
|
||||
# timeout. Keep this test on command construction only.
|
||||
monkeypatch.setattr(client, "stop_daemon", lambda: None)
|
||||
monkeypatch.setattr(client, "start_daemon", lambda: None)
|
||||
|
||||
args = argparse.Namespace(upload_limit=100, unrelated="ignored")
|
||||
client.configure(args, check_for_daemon=False)
|
||||
|
||||
argvs = [argv for argv, _ in calls]
|
||||
prefix = ["seaf-cli", "config"]
|
||||
assert prefix + ["-k", "upload_limit"] in argvs
|
||||
assert prefix + ["-k", "upload_limit", "-v", "100"] in argvs
|
||||
# An option that seaf-cli does not know about is never forwarded.
|
||||
assert not any("ignored" in argv for argv in argvs)
|
||||
|
||||
|
||||
def run_returning(monkeypatch, stdout=b"", returncode=0):
|
||||
"""Run seaf-cli commands that produce the given output."""
|
||||
calls = []
|
||||
|
||||
def fake_run(argv, **kwargs):
|
||||
calls.append(argv)
|
||||
return subprocess.CompletedProcess(argv, returncode, stdout=stdout)
|
||||
|
||||
monkeypatch.setattr(subprocess, "run", fake_run)
|
||||
return calls
|
||||
|
||||
|
||||
def test_local_libraries_are_read_as_json(client, monkeypatch):
|
||||
out = json.dumps([
|
||||
{"name": "Docs", "id": "id-1", "path": "/dsc/seafile/Docs"},
|
||||
]).encode()
|
||||
calls = run_returning(monkeypatch, out)
|
||||
|
||||
assert client.get_local_libraries() == {"id-1"}
|
||||
assert "--json" in calls[-1]
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name, path", [
|
||||
# Display output is whitespace separated, so these used to be unparseable.
|
||||
("My Docs", "/dsc/seafile/My_Docs"),
|
||||
("Docs", "/mnt/my libraries/Docs"),
|
||||
("My Docs", "/mnt/my libraries/My Docs"),
|
||||
("Ünïcödé ☂", "/dsc/seafile/Ünïcödé_☂"),
|
||||
("tab\tname", "/dsc/seafile/tab_name"),
|
||||
])
|
||||
def test_local_libraries_survive_whitespace_in_names_and_paths(client, monkeypatch, name, path):
|
||||
out = json.dumps([{"name": name, "id": "id-1", "path": path}]).encode()
|
||||
run_returning(monkeypatch, out)
|
||||
|
||||
assert client.get_local_libraries() == {"id-1"}
|
||||
|
||||
|
||||
def test_no_local_libraries_gives_an_empty_set(client, monkeypatch):
|
||||
run_returning(monkeypatch, b"[]")
|
||||
assert client.get_local_libraries() == set()
|
||||
|
||||
|
||||
def test_local_libraries_reports_unreadable_output(client, monkeypatch):
|
||||
run_returning(monkeypatch, b"not json at all")
|
||||
with pytest.raises(DaemonError):
|
||||
client.get_local_libraries()
|
||||
|
||||
|
||||
def test_local_libraries_reports_a_failed_command(client, monkeypatch):
|
||||
run_returning(monkeypatch, b"", returncode=1)
|
||||
with pytest.raises(DaemonError):
|
||||
client.get_local_libraries()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("payload", [
|
||||
b'{"name": "Docs"}', # an object where a list is expected
|
||||
b'[{"name": "Docs"}]', # an entry with no id
|
||||
b'["Docs"]', # entries that are not objects
|
||||
b'[null]',
|
||||
b'null',
|
||||
b'42',
|
||||
])
|
||||
def test_local_libraries_reports_unexpected_json_shapes(client, monkeypatch, payload):
|
||||
"""Valid JSON of the wrong shape must not escape as a raw TypeError."""
|
||||
run_returning(monkeypatch, payload)
|
||||
with pytest.raises(DaemonError):
|
||||
client.get_local_libraries()
|
||||
|
||||
|
||||
def test_local_libraries_error_keeps_the_original_cause(client, monkeypatch):
|
||||
run_returning(monkeypatch, b"not json at all")
|
||||
with pytest.raises(DaemonError) as err:
|
||||
client.get_local_libraries()
|
||||
assert err.value.__cause__ is not None
|
||||
|
||||
|
||||
def test_configure_never_sends_none_as_a_value(client, calls):
|
||||
"""A None here reaches seaf-cli as the literal string "None"."""
|
||||
with pytest.raises(ConfigError):
|
||||
client.configure(argparse.Namespace(upload_limit=None), check_for_daemon=False)
|
||||
|
||||
for argv, _ in calls:
|
||||
assert "None" not in argv
|
||||
|
||||
|
||||
@pytest.mark.parametrize("value, expected", [
|
||||
(True, "true"),
|
||||
(False, "false"),
|
||||
(0, "0"),
|
||||
(500, "500"),
|
||||
])
|
||||
def test_configure_renders_values_the_way_seaf_cli_stores_them(
|
||||
client, calls, monkeypatch, value, expected):
|
||||
# Changing an option restarts the daemon; keep this on the value only.
|
||||
monkeypatch.setattr(client, "stop_daemon", lambda: None)
|
||||
monkeypatch.setattr(client, "start_daemon", lambda: None)
|
||||
|
||||
client.configure(argparse.Namespace(disable_verify_certificate=value)
|
||||
if isinstance(value, bool)
|
||||
else argparse.Namespace(upload_limit=value),
|
||||
check_for_daemon=False)
|
||||
|
||||
setting = [argv for argv, _ in calls if "-v" in argv][-1]
|
||||
assert setting[setting.index("-v") + 1] == expected
|
||||
@@ -0,0 +1,120 @@
|
||||
"""The environment is untyped text; everything derived from it is checked."""
|
||||
|
||||
import pytest
|
||||
|
||||
import start
|
||||
from dsc.config import env_bool, env_int, env_str
|
||||
from dsc.errors import ConfigError
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def env(monkeypatch):
|
||||
def set_env(**values):
|
||||
for name, value in values.items():
|
||||
if value is None:
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
else:
|
||||
monkeypatch.setenv(name, value)
|
||||
return set_env
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw, expected", [
|
||||
(None, 7), # unset keeps the documented default
|
||||
("", 7), # an empty variable is the same as unset
|
||||
("0", 0), # zero is a real value, not "missing"
|
||||
("1", 1),
|
||||
("4096", 4096),
|
||||
(" 42 ", 42),
|
||||
# int() accepts any Unicode decimal digit and normalises it; the value
|
||||
# leaves as an ASCII integer, so this is harmless rather than rejected.
|
||||
("\u0663", 3),
|
||||
])
|
||||
def test_env_int_accepts(env, raw, expected):
|
||||
env(LIMIT=raw)
|
||||
assert env_int("LIMIT", 7) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", ["-1", "-0.5", "abc", "1.5", "1e3", "0x10", "1 2", "٣ x"])
|
||||
def test_env_int_rejects(env, raw):
|
||||
env(LIMIT=raw)
|
||||
with pytest.raises(ConfigError) as err:
|
||||
env_int("LIMIT", 7)
|
||||
assert "LIMIT" in str(err.value)
|
||||
assert raw.strip() in str(err.value)
|
||||
|
||||
|
||||
def test_env_int_allows_a_negative_value_when_permitted(env):
|
||||
env(LIMIT="-1")
|
||||
assert env_int("LIMIT", 7, minimum=-1) == -1
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw, expected", [
|
||||
(None, False),
|
||||
("", False),
|
||||
("true", True), ("True", True), ("TRUE", True),
|
||||
("1", True), ("yes", True), ("on", True),
|
||||
("false", False), ("False", False), ("0", False),
|
||||
("no", False), ("off", False), (" true ", True),
|
||||
])
|
||||
def test_env_bool_accepts(env, raw, expected):
|
||||
env(FLAG=raw)
|
||||
assert env_bool("FLAG", False) is expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw", ["maybe", "2", "-1", "y3s", "truthy"])
|
||||
def test_env_bool_rejects(env, raw):
|
||||
env(FLAG=raw)
|
||||
with pytest.raises(ConfigError) as err:
|
||||
env_bool("FLAG", False)
|
||||
assert "FLAG" in str(err.value)
|
||||
|
||||
|
||||
def test_env_bool_keeps_a_true_default_when_unset(env):
|
||||
env(FLAG=None)
|
||||
assert env_bool("FLAG", True) is True
|
||||
|
||||
|
||||
@pytest.mark.parametrize("raw, expected", [
|
||||
(None, None), ("", None), ("value", "value"), (" spaced ", " spaced "),
|
||||
])
|
||||
def test_env_str(env, raw, expected):
|
||||
env(NAME=raw)
|
||||
assert env_str("NAME") == expected
|
||||
|
||||
|
||||
def test_a_default_container_gets_exactly_the_documented_defaults(monkeypatch):
|
||||
"""The values the README promises when nothing optional is configured."""
|
||||
for name in ("UPLOAD_LIMIT", "DOWNLOAD_LIMIT", "DELETE_CONFIRM_THRESHOLD",
|
||||
"SEAFILE_UID", "SEAFILE_GID", "DISABLE_VERIFY_CERTIFICATE"):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
|
||||
defaults = start.defaults_from_env()
|
||||
|
||||
assert defaults["upload_limit"] == 0
|
||||
assert defaults["download_limit"] == 0
|
||||
assert defaults["delete_confirm_threshold"] == 500
|
||||
assert defaults["uid"] == 1000
|
||||
assert defaults["gid"] == 1000
|
||||
assert defaults["disable_verify_certificate"] is False
|
||||
|
||||
|
||||
def test_no_default_is_none_where_a_value_is_documented(monkeypatch):
|
||||
"""A None here reaches seaf-cli as the literal string "None"."""
|
||||
for name in ("UPLOAD_LIMIT", "DOWNLOAD_LIMIT", "DELETE_CONFIRM_THRESHOLD",
|
||||
"SEAFILE_UID", "SEAFILE_GID"):
|
||||
monkeypatch.delenv(name, raising=False)
|
||||
|
||||
defaults = start.defaults_from_env()
|
||||
for key in ("upload_limit", "download_limit", "delete_confirm_threshold",
|
||||
"uid", "gid"):
|
||||
assert defaults[key] is not None, f"{key} must never default to None"
|
||||
|
||||
|
||||
def test_numeric_settings_are_integers_not_strings(monkeypatch):
|
||||
"""A string UID never equals the integer it is compared against."""
|
||||
monkeypatch.setenv("SEAFILE_UID", "1000")
|
||||
monkeypatch.setenv("UPLOAD_LIMIT", "50")
|
||||
|
||||
defaults = start.defaults_from_env()
|
||||
assert defaults["uid"] == 1000 and isinstance(defaults["uid"], int)
|
||||
assert defaults["upload_limit"] == 50 and isinstance(defaults["upload_limit"], int)
|
||||
@@ -0,0 +1,186 @@
|
||||
"""Startup and shutdown must be bounded, checked, and interruptible."""
|
||||
|
||||
import argparse
|
||||
import signal
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
import start
|
||||
from dsc import client as client_module
|
||||
from dsc import const
|
||||
from dsc.client import SeafileClient
|
||||
from dsc.errors import DaemonError, DaemonTimeout, GracefulShutdown
|
||||
|
||||
|
||||
@pytest.fixture(autouse=True)
|
||||
def fast_polling(monkeypatch):
|
||||
"""Keep the bounded waits bounded to milliseconds in tests."""
|
||||
monkeypatch.setattr(const, "DAEMON_POLL_PERIOD", 0)
|
||||
monkeypatch.setattr(const, "DAEMON_START_TIMEOUT", 0.05)
|
||||
monkeypatch.setattr(const, "DAEMON_STOP_TIMEOUT", 0.05)
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(monkeypatch):
|
||||
monkeypatch.setattr(client_module, "create_dir", lambda path: None)
|
||||
# A token keeps the tests off the network: without one, authentication
|
||||
# would be attempted against the server before syncing.
|
||||
return SeafileClient("seafile.example", "user", "pw", "/dsc", token="tok-en")
|
||||
|
||||
|
||||
def fake_runner(returncodes, monkeypatch, stdout=b""):
|
||||
"""Return exit codes by seaf-cli subcommand; record every call."""
|
||||
calls = []
|
||||
|
||||
def fake_run(argv, **kwargs):
|
||||
calls.append(argv)
|
||||
subcommand = argv[argv.index("seaf-cli") + 1]
|
||||
code = returncodes.get(subcommand, 0)
|
||||
return subprocess.CompletedProcess(argv, code, stdout=stdout)
|
||||
|
||||
monkeypatch.setattr(subprocess, "run", fake_run)
|
||||
return calls
|
||||
|
||||
|
||||
def test_start_daemon_fails_when_the_command_fails(client, monkeypatch):
|
||||
fake_runner({"start": 1}, monkeypatch)
|
||||
with pytest.raises(DaemonError):
|
||||
client.start_daemon()
|
||||
|
||||
|
||||
def test_init_config_fails_when_the_command_fails(client, monkeypatch):
|
||||
monkeypatch.setattr(type(client), "config_initialized", property(lambda self: False))
|
||||
fake_runner({"init": 2}, monkeypatch)
|
||||
with pytest.raises(DaemonError):
|
||||
client.init_config()
|
||||
|
||||
|
||||
def test_start_daemon_gives_up_when_the_daemon_never_becomes_ready(client, monkeypatch):
|
||||
# "start" succeeds but "status" never does: the daemon never comes up.
|
||||
fake_runner({"status": 1}, monkeypatch)
|
||||
|
||||
started = time.monotonic()
|
||||
with pytest.raises(DaemonTimeout) as err:
|
||||
client.start_daemon()
|
||||
|
||||
assert time.monotonic() - started < 5, "the wait must be bounded"
|
||||
assert "ready" in str(err.value).lower()
|
||||
|
||||
|
||||
def test_start_daemon_returns_once_ready(client, monkeypatch):
|
||||
fake_runner({}, monkeypatch) # status returns 0 straight away
|
||||
client.start_daemon()
|
||||
|
||||
|
||||
def test_stop_daemon_gives_up_when_the_daemon_never_stops(client, monkeypatch):
|
||||
# "status" keeps succeeding, so the daemon never reports itself stopped.
|
||||
fake_runner({}, monkeypatch)
|
||||
|
||||
started = time.monotonic()
|
||||
with pytest.raises(DaemonTimeout):
|
||||
client.stop_daemon()
|
||||
|
||||
assert time.monotonic() - started < 5, "the wait must be bounded"
|
||||
|
||||
|
||||
def test_stop_daemon_succeeds_when_the_daemon_is_already_gone(client, monkeypatch):
|
||||
# A stopped daemon makes both "stop" and "status" fail; that is success.
|
||||
fake_runner({"stop": 1, "status": 1}, monkeypatch)
|
||||
client.stop_daemon()
|
||||
|
||||
|
||||
def test_stop_timeout_fits_inside_the_docker_stop_grace_period():
|
||||
"""docker stop sends SIGKILL 10s after SIGTERM by default."""
|
||||
assert const.DAEMON_STOP_TIMEOUT < 10
|
||||
|
||||
|
||||
def test_configure_fails_when_setting_an_option_fails(client, monkeypatch):
|
||||
fake_runner({"config": 1}, monkeypatch)
|
||||
with pytest.raises(DaemonError):
|
||||
client.configure(argparse.Namespace(upload_limit=100), check_for_daemon=False)
|
||||
|
||||
|
||||
def test_sync_lib_reports_a_failure_without_stopping_other_libraries(client, monkeypatch, caplog):
|
||||
fake_runner({"sync": 1}, monkeypatch)
|
||||
with caplog.at_level("ERROR"):
|
||||
assert client.sync_lib("lib-id", "/dsc/seafile/Docs") is False
|
||||
assert "lib-id" in caplog.text
|
||||
|
||||
|
||||
def test_sync_lib_reports_success(client, monkeypatch):
|
||||
fake_runner({}, monkeypatch)
|
||||
assert client.sync_lib("lib-id", "/dsc/seafile/Docs") is True
|
||||
|
||||
|
||||
class FakeClient:
|
||||
"""A client whose lifecycle calls are recorded instead of executed."""
|
||||
|
||||
def __init__(self, fail_on=None, error=None):
|
||||
self.fail_on = fail_on
|
||||
self.error = error or DaemonError("boom")
|
||||
self.calls = []
|
||||
self.remote_libraries = {"lib-id": "Docs"}
|
||||
|
||||
def __getattr__(self, name):
|
||||
def record(*args, **kwargs):
|
||||
self.calls.append(name)
|
||||
if name == self.fail_on:
|
||||
raise self.error
|
||||
return True
|
||||
return record
|
||||
|
||||
def __record(self, name):
|
||||
self.calls.append(name)
|
||||
if name == self.fail_on:
|
||||
raise self.error
|
||||
|
||||
def get_library_id(self, name):
|
||||
self.__record("get_library_id")
|
||||
return "lib-id"
|
||||
|
||||
def get_local_libraries(self):
|
||||
self.__record("get_local_libraries")
|
||||
return set()
|
||||
|
||||
|
||||
ARGS = argparse.Namespace(libraries="Docs", server="seafile.example")
|
||||
|
||||
|
||||
def test_run_stops_the_daemon_after_a_normal_finish():
|
||||
client = FakeClient()
|
||||
assert start.run(client, ARGS, "/dsc/seafile") == 0
|
||||
assert client.calls[-1] == "stop_daemon"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("failing_step", [
|
||||
"init_config", "start_daemon", "configure", "get_local_libraries", "watch_status",
|
||||
])
|
||||
def test_run_returns_nonzero_and_still_stops_the_daemon_on_failure(failing_step):
|
||||
client = FakeClient(fail_on=failing_step)
|
||||
assert start.run(client, ARGS, "/dsc/seafile") != 0
|
||||
assert client.calls[-1] == "stop_daemon"
|
||||
|
||||
|
||||
def test_run_returns_zero_and_stops_the_daemon_on_shutdown_signal():
|
||||
client = FakeClient(fail_on="watch_status", error=GracefulShutdown("SIGTERM"))
|
||||
assert start.run(client, ARGS, "/dsc/seafile") == 0
|
||||
assert client.calls[-1] == "stop_daemon"
|
||||
|
||||
|
||||
def test_run_reports_failure_even_if_stopping_also_fails():
|
||||
client = FakeClient(fail_on="stop_daemon", error=DaemonTimeout("stuck"))
|
||||
assert start.run(client, ARGS, "/dsc/seafile") != 0
|
||||
|
||||
|
||||
@pytest.mark.parametrize("signum", [signal.SIGTERM, signal.SIGINT])
|
||||
def test_signal_handlers_raise_a_graceful_shutdown(signum):
|
||||
previous = signal.getsignal(signum)
|
||||
try:
|
||||
start.install_signal_handlers()
|
||||
handler = signal.getsignal(signum)
|
||||
with pytest.raises(GracefulShutdown):
|
||||
handler(signum, None)
|
||||
finally:
|
||||
signal.signal(signum, previous)
|
||||
@@ -0,0 +1,40 @@
|
||||
"""The container HEALTHCHECK must reflect both the daemon and its RPC socket."""
|
||||
|
||||
import pytest
|
||||
|
||||
from dsc.client import SeafileClient
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return SeafileClient("seafile.example", "user", "pw", "/dsc", token="tok-en")
|
||||
|
||||
|
||||
def test_healthy_when_daemon_and_rpc_both_respond(client, monkeypatch):
|
||||
monkeypatch.setattr(type(client), "daemon_ready", True)
|
||||
monkeypatch.setattr(client.rpc, "get_repo_list", lambda a, b: [])
|
||||
assert client.is_healthy() is True
|
||||
|
||||
|
||||
def test_unhealthy_when_the_daemon_is_not_ready(client, monkeypatch):
|
||||
monkeypatch.setattr(type(client), "daemon_ready", False)
|
||||
assert client.is_healthy() is False
|
||||
|
||||
|
||||
def test_unhealthy_when_the_rpc_socket_raises(client, monkeypatch):
|
||||
monkeypatch.setattr(type(client), "daemon_ready", True)
|
||||
|
||||
def broken(a, b):
|
||||
raise ConnectionError("socket gone")
|
||||
|
||||
monkeypatch.setattr(client.rpc, "get_repo_list", broken)
|
||||
assert client.is_healthy() is False
|
||||
|
||||
|
||||
def test_rpc_is_not_checked_when_the_daemon_is_already_down(client, monkeypatch):
|
||||
"""A dead daemon means a dead socket too; no need to touch it."""
|
||||
monkeypatch.setattr(type(client), "daemon_ready", False)
|
||||
called = []
|
||||
monkeypatch.setattr(client.rpc, "get_repo_list", lambda a, b: called.append(1))
|
||||
assert client.is_healthy() is False
|
||||
assert not called
|
||||
@@ -0,0 +1,73 @@
|
||||
"""HTTP requests to the Seafile server must be bounded, not hang forever.
|
||||
|
||||
Regression coverage for a measured issue: with no request timeout, the
|
||||
retry policy waited about 26 minutes against an unreachable host before
|
||||
giving up. See dsc/const.py for the bounds this enforces.
|
||||
"""
|
||||
|
||||
from unittest import mock
|
||||
|
||||
import pytest
|
||||
import requests
|
||||
|
||||
from dsc import const
|
||||
from dsc.client import SeafileClient
|
||||
from dsc.errors import NetworkError
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client():
|
||||
return SeafileClient("seafile.example", "user", "pw", "/dsc")
|
||||
|
||||
|
||||
def test_client_mounts_a_bounded_retry_policy(client):
|
||||
adapter = client.session.get_adapter("https://seafile.example")
|
||||
retry = adapter.max_retries
|
||||
assert retry.total == const.HTTP_RETRY_TOTAL
|
||||
assert retry.backoff_factor == const.HTTP_RETRY_BACKOFF_FACTOR
|
||||
assert retry.backoff_max == const.HTTP_RETRY_BACKOFF_MAX
|
||||
|
||||
|
||||
def test_fetching_a_token_passes_a_request_timeout(client):
|
||||
with mock.patch.object(client.session, "post") as post:
|
||||
post.return_value = mock.Mock(status_code=200, json=lambda: {"token": "tok"})
|
||||
assert client.token == "tok"
|
||||
_, kwargs = post.call_args
|
||||
assert kwargs["timeout"] == const.HTTP_TIMEOUT
|
||||
|
||||
|
||||
def test_fetching_a_token_wraps_a_network_failure(client):
|
||||
with mock.patch.object(client.session, "post", side_effect=requests.exceptions.Timeout):
|
||||
with pytest.raises(NetworkError):
|
||||
_ = client.token
|
||||
|
||||
|
||||
def test_fetching_a_token_reports_url_and_status_on_an_error_response(client):
|
||||
with mock.patch.object(client.session, "post") as post:
|
||||
post.return_value = mock.Mock(status_code=403, text="Forbidden")
|
||||
with pytest.raises(NetworkError, match="auth-token.*403.*Forbidden"):
|
||||
_ = client.token
|
||||
|
||||
|
||||
def test_listing_remote_libraries_passes_a_request_timeout(client, monkeypatch):
|
||||
monkeypatch.setattr(type(client), "token", "tok")
|
||||
with mock.patch.object(client.session, "get") as get:
|
||||
get.return_value = mock.Mock(status_code=200, json=lambda: [])
|
||||
assert client.remote_libraries == {}
|
||||
_, kwargs = get.call_args
|
||||
assert kwargs["timeout"] == const.HTTP_TIMEOUT
|
||||
|
||||
|
||||
def test_listing_remote_libraries_wraps_a_network_failure(client, monkeypatch):
|
||||
monkeypatch.setattr(type(client), "token", "tok")
|
||||
with mock.patch.object(client.session, "get", side_effect=requests.exceptions.ConnectionError):
|
||||
with pytest.raises(NetworkError):
|
||||
_ = client.remote_libraries
|
||||
|
||||
|
||||
def test_listing_remote_libraries_reports_url_and_status_on_an_error_response(client, monkeypatch):
|
||||
monkeypatch.setattr(type(client), "token", "tok")
|
||||
with mock.patch.object(client.session, "get") as get:
|
||||
get.return_value = mock.Mock(status_code=500, text="Internal Server Error")
|
||||
with pytest.raises(NetworkError, match="api2/repos.*500.*Internal Server Error"):
|
||||
_ = client.remote_libraries
|
||||
@@ -0,0 +1,56 @@
|
||||
"""A library set must resolve to exactly one library ID per entry, or fail."""
|
||||
|
||||
import pytest
|
||||
|
||||
from dsc.client import SeafileClient
|
||||
from dsc.errors import ConfigError
|
||||
from start import resolve_libraries
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(monkeypatch):
|
||||
c = SeafileClient("seafile.example", "user", "pw", "/dsc")
|
||||
monkeypatch.setattr(type(c), "remote_libraries", {
|
||||
"id-1": "Docs",
|
||||
"id-2": "Docs",
|
||||
"id-3": "Photos",
|
||||
})
|
||||
monkeypatch.setattr(c, "get_local_libraries", lambda: set())
|
||||
return c
|
||||
|
||||
|
||||
def test_get_library_id_resolves_a_unique_name(client):
|
||||
assert client.get_library_id("Photos") == "id-3"
|
||||
|
||||
|
||||
def test_get_library_id_resolves_by_id(client):
|
||||
assert client.get_library_id("id-1") == "id-1"
|
||||
|
||||
|
||||
def test_get_library_id_returns_none_for_no_match(client):
|
||||
assert client.get_library_id("Missing") is None
|
||||
|
||||
|
||||
def test_get_library_id_rejects_an_ambiguous_name(client):
|
||||
with pytest.raises(ConfigError, match="Docs.*2 libraries"):
|
||||
client.get_library_id("Docs")
|
||||
|
||||
|
||||
def test_resolve_libraries_rejects_an_empty_requested_set(client):
|
||||
with pytest.raises(ConfigError, match="empty entry"):
|
||||
resolve_libraries(client, "", "seafile.example")
|
||||
|
||||
|
||||
@pytest.mark.parametrize("requested", ["Photos:", ":Photos", "Photos::id-1"])
|
||||
def test_resolve_libraries_rejects_an_empty_entry_between_separators(client, requested):
|
||||
with pytest.raises(ConfigError, match="empty entry"):
|
||||
resolve_libraries(client, requested, "seafile.example")
|
||||
|
||||
|
||||
def test_resolve_libraries_rejects_an_ambiguous_name_end_to_end(client):
|
||||
with pytest.raises(ConfigError, match="Docs"):
|
||||
resolve_libraries(client, "Docs", "seafile.example")
|
||||
|
||||
|
||||
def test_resolve_libraries_resolves_unambiguous_names(client):
|
||||
assert resolve_libraries(client, "Photos:id-1", "seafile.example") == {"id-3", "id-1"}
|
||||
@@ -0,0 +1,111 @@
|
||||
import os
|
||||
|
||||
import pytest
|
||||
|
||||
from dsc.paths import UnsafeLibraryName, lib_dirname, plan_lib_dirs, resolve_lib_dir
|
||||
|
||||
PARENT = "/dsc/seafile"
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name, expected", [
|
||||
("Documents", "Documents"),
|
||||
("My Library", "My_Library"),
|
||||
(" padded ", "padded"),
|
||||
("Ünïcödé ☂", "Ünïcödé_☂"),
|
||||
# The characters below used to reach a shell. They are now ordinary
|
||||
# filename characters and must survive untouched.
|
||||
('quote"name', 'quote"name'),
|
||||
("single'name", "single'name"),
|
||||
("semi;colon", "semi;colon"),
|
||||
("dollar$(id)", "dollar$(id)"),
|
||||
("back`id`tick", "back`id`tick"),
|
||||
("pipe|amp&name", "pipe|amp&name"),
|
||||
("new\nline", "new_line"),
|
||||
("tab\tname", "tab_name"),
|
||||
("dash-lead", "dash-lead"),
|
||||
("-leading-dash", "-leading-dash"),
|
||||
])
|
||||
def test_lib_dirname_accepts(name, expected):
|
||||
assert lib_dirname(name) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("name", [
|
||||
"",
|
||||
" ",
|
||||
"\n",
|
||||
".",
|
||||
"..",
|
||||
"...", # not special to the kernel, but never a library name we want
|
||||
"/",
|
||||
"/etc",
|
||||
"/etc/passwd",
|
||||
"../escape",
|
||||
"../../root",
|
||||
"nested/name",
|
||||
"trailing/",
|
||||
"nul\0byte",
|
||||
])
|
||||
def test_lib_dirname_rejects(name):
|
||||
with pytest.raises(UnsafeLibraryName):
|
||||
lib_dirname(name)
|
||||
|
||||
|
||||
def test_resolve_lib_dir_stays_under_parent():
|
||||
assert resolve_lib_dir(PARENT, "Documents") == "/dsc/seafile/Documents"
|
||||
|
||||
|
||||
def test_resolve_lib_dir_rejects_escape_through_symlink(tmp_path):
|
||||
parent = tmp_path / "seafile"
|
||||
parent.mkdir()
|
||||
outside = tmp_path / "outside"
|
||||
outside.mkdir()
|
||||
(parent / "escape").symlink_to(outside)
|
||||
|
||||
with pytest.raises(UnsafeLibraryName):
|
||||
resolve_lib_dir(str(parent), "escape")
|
||||
|
||||
|
||||
def test_resolve_lib_dir_allows_real_dir_under_parent(tmp_path):
|
||||
parent = tmp_path / "seafile"
|
||||
parent.mkdir()
|
||||
(parent / "Documents").mkdir()
|
||||
|
||||
resolved = resolve_lib_dir(str(parent), "Documents")
|
||||
assert resolved == os.path.realpath(str(parent / "Documents"))
|
||||
|
||||
|
||||
def test_plan_lib_dirs_maps_each_library_to_its_own_dir():
|
||||
plan = plan_lib_dirs({"id-a": "Docs", "id-b": "My Photos"}, PARENT)
|
||||
assert plan == {
|
||||
"id-a": "/dsc/seafile/Docs",
|
||||
"id-b": "/dsc/seafile/My_Photos",
|
||||
}
|
||||
|
||||
|
||||
def test_plan_lib_dirs_disambiguates_duplicate_names():
|
||||
libs = {"aaaaaaaabbbb": "Docs", "ccccccccdddd": "Docs"}
|
||||
plan = plan_lib_dirs(libs, PARENT)
|
||||
|
||||
assert plan == {
|
||||
"aaaaaaaabbbb": "/dsc/seafile/Docs-aaaaaaaa",
|
||||
"ccccccccdddd": "/dsc/seafile/Docs-cccccccc",
|
||||
}
|
||||
|
||||
|
||||
def test_plan_lib_dirs_duplicate_suffix_is_order_independent():
|
||||
libs = {"aaaaaaaabbbb": "Docs", "ccccccccdddd": "Docs"}
|
||||
reversed_libs = dict(reversed(list(libs.items())))
|
||||
assert plan_lib_dirs(libs, PARENT) == plan_lib_dirs(reversed_libs, PARENT)
|
||||
|
||||
|
||||
def test_plan_lib_dirs_duplicates_collide_after_space_folding():
|
||||
"""'A B' and 'A_B' both fold to 'A_B' and must not share a directory."""
|
||||
libs = {"aaaaaaaabbbb": "A B", "ccccccccdddd": "A_B"}
|
||||
plan = plan_lib_dirs(libs, PARENT)
|
||||
assert len(set(plan.values())) == 2
|
||||
|
||||
|
||||
def test_plan_lib_dirs_skips_unsafe_names_and_keeps_the_rest():
|
||||
libs = {"good": "Docs", "bad": "../escape"}
|
||||
plan = plan_lib_dirs(libs, PARENT)
|
||||
assert plan == {"good": "/dsc/seafile/Docs"}
|
||||
@@ -0,0 +1,82 @@
|
||||
"""Secrets may come from a variable or a mounted file, never ambiguously."""
|
||||
|
||||
import pytest
|
||||
|
||||
from dsc.errors import ConfigError
|
||||
from dsc.secrets import read_secret_file, resolve_secret
|
||||
|
||||
|
||||
def write(tmp_path, content, name="secret"):
|
||||
path = tmp_path / name
|
||||
path.write_text(content)
|
||||
return str(path)
|
||||
|
||||
|
||||
@pytest.mark.parametrize("content, expected", [
|
||||
("s3cret", "s3cret"),
|
||||
# Secret files are usually written with a trailing newline; a password
|
||||
# that silently includes it fails to authenticate with no useful message.
|
||||
("s3cret\n", "s3cret"),
|
||||
("s3cret\r\n", "s3cret"),
|
||||
("s3cret\n\n", "s3cret"),
|
||||
# Everything else is part of the secret, including inner and edge spaces.
|
||||
(" s3cret ", " s3cret "),
|
||||
("pa ss", "pa ss"),
|
||||
('pa"ss$(id)`x`', 'pa"ss$(id)`x`'),
|
||||
("паssшörд\n", "паssшörд"),
|
||||
])
|
||||
def test_read_secret_file_strips_only_trailing_newlines(tmp_path, content, expected):
|
||||
assert read_secret_file(write(tmp_path, content)) == expected
|
||||
|
||||
|
||||
@pytest.mark.parametrize("content", ["", "\n", "\r\n", "\n\n"])
|
||||
def test_read_secret_file_rejects_an_empty_secret(tmp_path, content):
|
||||
with pytest.raises(ConfigError):
|
||||
read_secret_file(write(tmp_path, content))
|
||||
|
||||
|
||||
def test_read_secret_file_reports_a_missing_file(tmp_path):
|
||||
missing = str(tmp_path / "absent")
|
||||
with pytest.raises(ConfigError) as err:
|
||||
read_secret_file(missing)
|
||||
assert missing in str(err.value)
|
||||
|
||||
|
||||
def test_read_secret_file_never_puts_the_secret_in_the_error(tmp_path):
|
||||
path = write(tmp_path, "")
|
||||
with pytest.raises(ConfigError) as err:
|
||||
read_secret_file(path)
|
||||
assert "empty" in str(err.value).lower()
|
||||
|
||||
|
||||
def test_resolve_secret_prefers_nothing_when_neither_is_set():
|
||||
assert resolve_secret("PASSWORD", None, None) is None
|
||||
|
||||
|
||||
def test_resolve_secret_reads_the_variable():
|
||||
assert resolve_secret("PASSWORD", "s3cret", None) == "s3cret"
|
||||
|
||||
|
||||
def test_resolve_secret_reads_the_file(tmp_path):
|
||||
path = write(tmp_path, "s3cret\n")
|
||||
assert resolve_secret("PASSWORD", None, path) == "s3cret"
|
||||
|
||||
|
||||
def test_resolve_secret_rejects_two_sources_for_one_secret(tmp_path):
|
||||
path = write(tmp_path, "s3cret")
|
||||
with pytest.raises(ConfigError) as err:
|
||||
resolve_secret("PASSWORD", "other", path)
|
||||
assert "PASSWORD" in str(err.value)
|
||||
assert "PASSWORD_FILE" in str(err.value)
|
||||
|
||||
|
||||
def test_resolve_secret_conflict_message_hides_both_values(tmp_path):
|
||||
path = write(tmp_path, "file-secret")
|
||||
with pytest.raises(ConfigError) as err:
|
||||
resolve_secret("PASSWORD", "env-secret", path)
|
||||
assert "env-secret" not in str(err.value)
|
||||
assert "file-secret" not in str(err.value)
|
||||
|
||||
|
||||
def test_resolve_secret_treats_an_empty_variable_as_unset():
|
||||
assert resolve_secret("PASSWORD", "", None) is None
|
||||
@@ -0,0 +1,70 @@
|
||||
"""A transient RPC failure must not take the whole process down with it."""
|
||||
|
||||
import time
|
||||
|
||||
import pytest
|
||||
|
||||
from dsc.client import SeafileClient
|
||||
from dsc.errors import GracefulShutdown
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def client(monkeypatch):
|
||||
monkeypatch.setattr(time, "sleep", lambda seconds: None)
|
||||
return SeafileClient("seafile.example", "user", "pw", "/dsc", token="tok-en")
|
||||
|
||||
|
||||
def test_watch_status_survives_a_transient_rpc_failure(client, monkeypatch):
|
||||
"""The loop keeps going instead of crashing the container."""
|
||||
calls = []
|
||||
|
||||
def flaky_get_status():
|
||||
calls.append(1)
|
||||
if len(calls) == 1:
|
||||
raise ConnectionError("daemon restarting")
|
||||
raise GracefulShutdown("SIGTERM") # ends the otherwise-infinite loop
|
||||
|
||||
monkeypatch.setattr(client, "get_status", flaky_get_status)
|
||||
|
||||
with pytest.raises(GracefulShutdown):
|
||||
client.watch_status()
|
||||
|
||||
assert len(calls) == 2, "the loop must retry after the first failure"
|
||||
|
||||
|
||||
def test_watch_status_still_propagates_a_stop_signal(client, monkeypatch):
|
||||
"""A DscError, such as a stop signal, must still end the loop."""
|
||||
monkeypatch.setattr(client, "get_status",
|
||||
lambda: (_ for _ in ()).throw(GracefulShutdown("SIGINT")))
|
||||
|
||||
with pytest.raises(GracefulShutdown):
|
||||
client.watch_status()
|
||||
|
||||
|
||||
def test_watch_status_keeps_prior_state_across_a_failed_read(client, monkeypatch, caplog):
|
||||
"""
|
||||
A failed read is logged and skipped; it must not corrupt prior state,
|
||||
so a real change right after the failure is still detected and logged.
|
||||
"""
|
||||
calls = []
|
||||
|
||||
def flaky_get_status():
|
||||
calls.append(1)
|
||||
if len(calls) == 1:
|
||||
return {"Docs": "syncing"}
|
||||
if len(calls) == 2:
|
||||
raise ConnectionError("daemon restarting")
|
||||
if len(calls) == 3:
|
||||
return {"Docs": "done"}
|
||||
raise GracefulShutdown("SIGTERM")
|
||||
|
||||
monkeypatch.setattr(client, "get_status", flaky_get_status)
|
||||
|
||||
with caplog.at_level("INFO"):
|
||||
with pytest.raises(GracefulShutdown):
|
||||
client.watch_status()
|
||||
|
||||
assert "Could not read sync status" in caplog.text
|
||||
assert "syncing" in caplog.text
|
||||
assert "done" in caplog.text
|
||||
assert len(calls) == 4
|
||||
Reference in new issue
Block a user