90 Commits
Author SHA1 Message Date
dependabot[bot] 90134a326f pip: bump pytest from 9.1.1 to 9.2.0 (#36)
Bumps [pytest](https://github.com/pytest-dev/pytest) from 9.1.1 to 9.2.0.
- [Release notes](https://github.com/pytest-dev/pytest/releases)
- [Changelog](https://github.com/pytest-dev/pytest/blob/main/CHANGELOG.rst)
- [Commits](https://github.com/pytest-dev/pytest/compare/9.1.1...9.2.0)

---
updated-dependencies:
- dependency-name: pytest
  dependency-version: 9.2.0
  dependency-type: direct:development
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
Co-authored-by: dependabot[bot] <49699333+dependabot[bot]@users.noreply.github.com>
2026-11-23 13:36:05 -07:00
Max Shulga 22543e6f7f Give every test its own RPC client mock (#37)
The seafile stub returned the same RpcClient() mock to every test, so
changes one test made to it leaked into later tests.

pytest 9.2.0 exposed this. monkeypatch.setattr now reads the old value
from the instance __dict__, where a MagicMock does not keep its child
attributes, so undoing a patch of client.rpc.get_repo_list deletes the
attribute. A deleted attribute on a MagicMock stays deleted, and two
later health check tests failed with AttributeError.

An autouse fixture now replaces seafile.RpcClient with a new mock for
each test. All 202 tests pass on pytest 9.1.1 and 9.2.0.
2026-11-23 13:29:30 -07:00
snegov 9e399df8e4 Add CLAUDE.md 2026-10-11 13:25:21 -07:00
Maksim ShulgaandMaxim Shulga 123705aa53 Handle temporary RPC failures and daemon restarts without corrupting state (#35)
* Handle temporary RPC failures and daemon restarts without corrupting state

watch_status()'s per-iteration RPC read had no error handling: an
unexpected failure (the daemon crashing or restarting mid-call, or any
other transient RPC hiccup) propagated straight out of the loop and
crashed the whole container, indistinguishable from a real fatal
error.

The read is now wrapped: an unexpected exception logs a warning and
retries on the next tick, leaving prev_status untouched so the next
successful read still reports every real change. A stop signal or
another DscError still ends the loop exactly as before - the wrapper
explicitly re-raises DscError first, since GracefulShutdown is one and
must not be swallowed by the broader except below it.

Verified against the real image: a container survives seaf-daemon
being killed outright, logging the failure instead of exiting.

* Log a traceback on RPC failure and strengthen the state test

Copilot review:
- The RPC failure warning logged only the message; add exc_info so a
  repeated failure in production is actually debuggable.
- The 'prior state is not corrupted' test asserted the warning fired
  but never proved a real change after the failure was still detected
  and logged, which is the actual property being claimed.

---------

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
2026-08-03 18:55:34 +00:00
Maksim ShulgaandMaxim Shulga 28db575c92 Add a health check for the daemon and RPC endpoint (#34)
* Add a health check for the daemon and RPC endpoint

SeafileClient.is_healthy() checks seaf-cli status and makes a real RPC
call (get_repo_list) against the daemon's Unix socket - neither needs
the Seafile server, so it works without a token or password.

healthcheck.py exposes it as a plain script for Docker's HEALTHCHECK.
Each check is a fresh process spawned by the Docker daemon as root,
unlike the long-lived start.py process, so it drops to the seafile
user with runuser before touching the RPC socket - the one place that
mechanism still belongs after the earlier in-process privilege drop.

Verified against the real image: healthcheck.py exits 0 once the real
daemon is up (through the actual main() entrypoint, not a test
fixture) and nonzero when no daemon has been started.

* Assert the return value in the daemon-down health check test

Copilot review: the test checked the RPC call was skipped but not
what is_healthy() actually returned in that case.

---------

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
2026-08-03 18:38:19 +00:00
Maksim ShulgaandMaxim Shulga ba5ad177b7 Reject ambiguous library names and empty library-set entries (#33)
* Reject ambiguous library names and empty library-set entries

get_library_id() silently picked the first library matching a
requested name, so two libraries sharing a name would sync whichever
happened to come first in the server's response - not necessarily the
one the operator meant. It now raises ConfigError when a name matches
more than one library.

resolve_libraries() rejects an empty entry produced by an empty
LIBRARY_ID, 'a::b', or a leading/trailing ':' the same way, instead of
silently logging 'library  not found' and moving on.

* Clarify get_library_id's ambiguity docstring and error message

Copilot review: the input can be a name or an ID, and the error said
'Library name' even for an ID collision; use neutral wording. Also
made the docstring's second sentence a complete one.

---------

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
2026-08-03 18:38:06 +00:00
Maksim ShulgaandMaxim Shulga 6f8af2cfa4 Reject UID or GID zero unless a documented use case requires it (#32)
* Reject UID or GID zero unless a documented use case requires it

setup_uid() would happily remap the seafile user to UID/GID 0, which
after the previous non-root fix would mean drop_privileges() drops
straight back into root. main() now rejects --uid/SEAFILE_UID and
--gid/SEAFILE_GID being 0 with exit code 2, before setup_uid() runs.

Verified against the real image via tests/smoke.sh.

* Clarify the GID=0 rejection message

Copilot review: 'group root' isn't a commonly used phrase. Name GID 0
as the root group explicitly instead.

---------

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
2026-08-03 17:59:38 +00:00
Maksim ShulgaandMaxim Shulga 6d32460b13 Run the long-lived process as the configured non-root user (#31)
* Run the long-lived process as the configured non-root user

start.py used to stay root for its whole life; only the individual
seaf-cli/seaf-daemon subprocess calls were unprivileged, via a per-call
runuser wrapper. The orchestrating Python process itself, including the
RPC socket to seaf-daemon and the watch_status() loop, ran as root the
entire time.

main() now drops privileges in-process (dsc.misc.drop_privileges, using
os.initgroups/setgid/setuid) right after setup_uid()/create_dir() -
which still need root to remap the seafile user's UID/GID and chown
/dsc - and before SeafileClient is constructed. Since the process is
already the target user by the time any seaf-cli call happens, runuser
is removed from user_cmd(); it also could not be invoked from an
already non-root process.

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, and
tests/smoke.sh gained a check exercising setup_uid/create_dir/
drop_privileges together against the image's real /etc/passwd.

* Isolate os.environ mutation in drop_privileges test

drop_privileges() writes HOME/USER/LOGNAME directly to os.environ, and
the test asserting that didn't restore them, leaking state into later
tests. monkeypatch.delenv registers the keys so its teardown restores
them regardless of who wrote to os.environ.

---------

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
2026-08-03 17:44:34 +00:00
Maksim ShulgaandMaxim Shulga b0dfc1ad74 Run the image vulnerability scan on a weekly schedule (#30)
* Run the image vulnerability scan on a weekly schedule

The Trivy scan added in #29 only ran against changed code (PRs and
pushes), so a CVE disclosed against an otherwise unchanged base image
would go unnoticed until the next actual change. Add a weekly cron
trigger, matching Dependabot's cadence in .github/dependabot.yml.

The push job's existing `if: github.event_name == 'push'` guard means
a schedule-triggered run builds and scans but never publishes.

* Add workflow_dispatch so the scan can be run on demand

Copilot review on PR #30 suggested this: waiting for the Monday cron
to validate a fix is unnecessary friction. workflow_dispatch has no
inputs, so it just re-runs the same build/test/scan on demand; the
push job's event_name guard still keeps it from publishing.

---------

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
2026-08-03 05:26:08 +00:00
Maksim ShulgaandMaxim Shulga c2a634c13f Scan the built image for vulnerabilities and fix what's fixable (#29)
* Scan the built image for vulnerabilities and fix what's fixable

Ran trivy against the built image locally: 67 HIGH/CRITICAL findings,
65 of them in debian:bookworm-slim packages with no upstream fix yet.
The remaining 2 were both setuptools 66.1.1 (CVE-2024-6345,
CVE-2025-47273) — bundled by ensurepip when the venv is created, not
pinned by requirements.txt, so nothing was upgrading it.

- Upgrade setuptools to >=78.1.1 in the Dockerfile, which fixes both
  CVEs. Verified with a local rebuild + rescan: 0 HIGH/CRITICAL
  fixable findings remain.
- Add a Trivy scan step to the CI `test` job, after the smoke test.
  Uses --ignore-unfixed so the build fails only on findings this repo
  can act on, not on upstream Debian CVEs with no available patch.
- Check off the corresponding P0 item in IMPROVEMENTS.md; note that
  scheduled (as opposed to PR/push-triggered) scanning is still open.

* Fix trivy-action tag (needs v prefix)

* Tighten scan-coverage wording per review

Copilot review on PR #29 flagged "every pull request and push" as
ambiguous: the test job's push trigger is scoped to master and tags,
not every branch. Spell that out.

---------

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
2026-08-03 05:16:42 +00:00
Maksim ShulgaandMaxim Shulga a2887fa6db Bound HTTP request timeouts and retry budget (#28)
* Bound HTTP request timeouts and retry budget

With no request timeout, Retry(total=30, backoff_factor=2,
backoff_max=60) let a single unreachable server hang the client for
around 26 minutes: backoff sleeps alone sum to that, and each of the
30 connection attempts could itself stall indefinitely without a
timeout. Measured a black-holed connect attempt taking 75s on this
machine with no timeout set, confirming the mechanism.

- Add HTTP_TIMEOUT (connect, read) and a tighter retry budget
  (HTTP_RETRY_TOTAL/BACKOFF_FACTOR/BACKOFF_MAX) in dsc/const.py,
  bounding the worst case to a few minutes.
- Pass timeout=HTTP_TIMEOUT on both SeafileClient HTTP calls (token
  fetch, remote library listing).
- Add NetworkError(DscError) so a network failure is caught by
  start.py's existing top-level DscError handling instead of
  producing a bare traceback.
- Add tests/test_http.py covering the retry policy values, timeout
  propagation, and error wrapping.
- Check off the corresponding IMPROVEMENTS.md items.

* Include URL and status code in NetworkError messages

Copilot review on PR #28 flagged that the non-200 path for remote
library listing raised NetworkError with only the raw response body,
losing which request failed and its status code. The token-fetch
error had the same gap. Both now include the URL and HTTP status.

---------

Co-authored-by: Maxim Shulga <maxim.shulga@alludo.com>
2026-08-03 04:58:14 +00:00
Maksim Shulga c5b4262a4c Merge pull request #27 from snegov/feature/container-smoke-test
Run a container smoke test against the real seafile daemon
2026-08-03 02:52:38 +00:00
Maxim Shulga f535e8b7d0 Stop the smoke test from passing when it measured nothing
Two checks could report success without having verified anything. The version
check read the last line of output without looking at the exit status, so an
import failure printed a traceback whose last line was accepted as a version.
The shutdown check waited for the process to reach its watch loop but carried
on regardless, so if the container had already exited it measured the shutdown
of something that was not running.

The version check now requires a zero exit and a version shaped like one. The
shutdown check fails and prints the container log when the watch loop is never
reached. Both were confirmed against an image with a deliberately removed
module: each reports a failure where it previously reported success.
2026-08-02 19:46:27 -07:00
Maxim Shulga 84519cf7cc Run a container smoke test against the real seafile daemon
Startup, shutdown and secret handling were only ever checked by hand, and the
unit tests cannot check them: they stub seaf-cli, so nothing exercised the
daemon that actually ships. The GitHub runner is x86_64, which matches the
AppImage, so the image build job can run the real thing.

tests/smoke.sh starts and stops the real daemon, sends SIGTERM through docker
stop and asserts the container exits 0 within the grace period with the daemon
shut down, checks that a configuration error exits 2 naming the variable, that
a secret mounted under /run/secrets is read and stays out of the environment,
and that a default container gets exactly the documented defaults.

The pinned client version is exposed as SEAFILE_CLI_VERSION in the image,
since seaf-cli has no --version flag and there is no package manager entry
for an AppImage.
2026-08-02 19:37:26 -07:00
Maksim Shulga 2f93e4cdbc Merge pull request #26 from snegov/docs/record-certificate-flag-fix
Record why DISABLE_VERIFY_CERTIFICATE never worked
2026-08-03 01:32:23 +00:00
Maxim Shulga ca4c906814 Name the stored strings instead of implying booleans
The note explained a string comparison but wrote the values as if they were
booleans, which is the exact confusion it exists to clear up. Both places now
say which string was stored and which one the daemon accepts.
2026-08-02 18:24:43 -07:00
Maxim Shulga 3c8d247b28 Record why DISABLE_VERIFY_CERTIFICATE never worked
The daemon reads the key with seafile_session_config_get_bool, which is a
case sensitive g_strcmp0(value, "true"), so the capitalised True stored by
released images up to 0.0.13 was read as false and verification stayed on for
anyone who asked to disable it. The default was never affected, since any
value other than "true" is false.

Rendering booleans in lower case fixed this; this only writes down what the
change actually repaired, for anyone who reported the flag as broken.
2026-08-02 18:16:43 -07:00
Maksim Shulga 872585833b Merge pull request #25 from snegov/feature/typed-env-parsing
Read the environment with typed parsers and apply the documented defaults
2026-08-03 01:12:06 +00:00
Maxim Shulga 3c7daea3c1 Annotate env_str as returning an optional string
It returns the default when a variable is unset, and that default is None,
so the previous annotation was wrong for both the parameter and the result.
2026-08-02 18:08:38 -07:00
Maxim Shulga e6034a69a6 Read the environment with typed parsers and apply the documented defaults
set_defaults() assigned os.getenv() results directly, which overwrote the
argparse defaults with None whenever a variable was unset. A default container
therefore ran "seaf-cli config -k delete_confirm_threshold -v None", and the
same for upload_limit and download_limit: none of the three documented
defaults were ever applied.

SEAFILE_UID and SEAFILE_GID had a second problem. argparse type=int applies
only to command line flags, never to set_defaults, so both stayed strings.
The check in setup_uid compares them against pwd integers, and a string is
never equal to one, so usermod ran on every start.

dsc/config.py reads each variable with its documented default and rejects a
malformed or negative value at startup, naming the variable, instead of
passing it on. An empty variable counts as unset.

Booleans are now rendered as true and false rather than Python's True and
False. The daemon reads disable_verify_certificate with its boolean accessor,
which does not recognise the capitalised form. I could not run the daemon to
confirm the previous value's effect, since the AppImage is x86_64 only.

seaf-cli is no longer given a None value for any option.
2026-08-02 17:44:57 -07:00
Maksim Shulga 87b76b80f6 Merge pull request #24 from snegov/feature/parse-library-list-as-json
Read the local library list as JSON instead of splitting columns
2026-08-03 00:36:38 +00:00
Maxim Shulga 2e18a774f2 Fail the same way on JSON of an unexpected shape
json.loads succeeding does not mean the result is a list of objects with an
id. A dict, an entry without an id, or a scalar raised TypeError or KeyError,
which escaped unhandled and defeated the point of the change. Both cases now
raise DaemonError, and the original exception is chained so the cause is
visible.
2026-08-02 17:33:45 -07:00
Maxim Shulga b75863ba51 Read the local library list as JSON instead of splitting columns
get_local_libraries unpacked "line.rsplit(maxsplit=3)" into three names, but
maxsplit=3 yields up to four fields. seaf-cli prints "name id path" separated
by whitespace, so any library whose name contains a space produced a fourth
field and raised ValueError, which nothing caught.

The failure only appeared after the first run: the list is empty until a
library has been synced, so a container would work when it was set up and then
crash on every restart.

seaf-cli list --json returns name, id and path as structured fields, which
display output cannot represent unambiguously for names or paths containing
whitespace. Its exit code is now checked and unreadable output is reported as
a daemon error instead of a traceback.

The image smoke check asserts that the installed seaf-cli offers --json and
--token, so a future version bump that drops either fails the build rather
than the container.
2026-08-02 17:29:51 -07:00
Maksim Shulga 8043ac1409 Merge pull request #23 from snegov/feature/secrets-support
Authenticate from mounted secrets and stop passing the password to seaf-cli
2026-08-03 00:24:28 +00:00
Maxim Shulga eef0e453bf Authenticate from mounted secrets and stop passing the password to seaf-cli
The password could only be given through the PASSWORD variable, so Docker
Compose and Swarm secrets were unusable and the password sat in the container
environment.

PASSWORD_FILE and TOKEN_FILE read a secret from a mounted file. Only trailing
newlines are stripped, since secret files are usually written with one and a
password that silently carries it just fails to authenticate; everything else,
including surrounding spaces, belongs to the secret. Setting both a variable
and a file for one secret is rejected rather than resolved by precedence,
because the two are meant to be the same value and quietly picking one hides
the mistake until authentication fails.

The installed seaf-cli supports token authentication and ignores the password
when a token is given, so sync now passes -T instead of -p. The account
password no longer appears in any command line. The token does, because
seaf-cli accepts credentials only as arguments, but a token can be revoked on
the server. This is documented in the README.

Both secrets are masked before a command is logged.

Tests cover newline handling, empty and missing files, conflicting sources,
and that neither secret reaches the logs. Requests are now blocked in tests:
the client retries with backoff, so a test that reached the network appeared
to hang instead of failing.
2026-08-02 17:21:46 -07:00
Maksim Shulga 1e59da6193 Merge pull request #22 from snegov/feature/deterministic-startup-shutdown
Bound daemon startup and shutdown and exit with a useful code
2026-08-03 00:12:50 +00:00
Maxim Shulga f3804b7e2e Bound daemon startup and shutdown and exit with a useful code
start_daemon and stop_daemon polled "while True" with no bound, and no
seaf-cli exit code was checked. A daemon that failed to start left the
container spinning forever with nothing pointing at the cause, and there was
no signal handling, so "docker stop" waited the full 10 second grace period
and then SIGKILLed the process with the daemon still running.

Readiness polling is now bounded by DAEMON_START_TIMEOUT and
DAEMON_STOP_TIMEOUT. The stop timeout is 8 seconds so a graceful shutdown
fits inside the docker stop grace period, and a test asserts that relation.

SIGTERM and SIGINT raise GracefulShutdown, and the lifecycle moved into
start.run(), which always stops the daemon on the way out and returns the
process exit code: 0 on a clean finish or a stop signal, 1 on a daemon or
configuration failure.

seaf-cli exit codes are checked. A failed sync is reported per library and
does not stop the remaining libraries, since one bad library should not take
the container down.

Verified in the built image: "docker stop" now returns in 0s with exit code 0
and the daemon stopped, against 10s and exit 137 before. A daemon that cannot
start exits 1 with the failing command and its exit code in the log.

Also bumps actions/setup-python to v7, which clears the last Node 20
deprecation warning; v7 only drops the unused pip-install input.
2026-08-02 17:10:20 -07:00
Maksim Shulga d1c0be2c24 Merge pull request #17 from snegov/dependabot/pip/cached-property-2.0.1
pip: bump cached-property from 1.5.2 to 2.0.1
2026-08-03 00:02:50 +00:00
dependabot[bot] 8ce30e6194 pip: bump cached-property from 1.5.2 to 2.0.1
Bumps [cached-property](https://github.com/pydanny/cached-property) from 1.5.2 to 2.0.1.
- [Release notes](https://github.com/pydanny/cached-property/releases)
- [Changelog](https://github.com/pydanny/cached-property/blob/main/HISTORY.md)
- [Commits](https://github.com/pydanny/cached-property/compare/1.5.2...2.0.1)

---
updated-dependencies:
- dependency-name: cached-property
  dependency-version: 2.0.1
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-03 00:01:34 +00:00
Maksim Shulga d2d6621add Merge pull request #15 from snegov/dependabot/github_actions/docker/login-action-4
ci: bump docker/login-action from 3 to 4
2026-08-03 00:00:37 +00:00
Maksim Shulga f0e5c1fc06 Merge pull request #20 from snegov/dependabot/github_actions/docker/metadata-action-6
ci: bump docker/metadata-action from 5 to 6
2026-08-03 00:00:31 +00:00
Maksim Shulga 5546fe5317 Merge pull request #18 from snegov/dependabot/pip/requests-2.34.2
pip: bump requests from 2.33.0 to 2.34.2
2026-08-02 23:59:58 +00:00
Maksim Shulga fad6baf28a Merge pull request #16 from snegov/dependabot/github_actions/actions/checkout-7
ci: bump actions/checkout from 4 to 7
2026-08-02 23:59:42 +00:00
Maksim Shulga 964ab2c46f Merge pull request #19 from snegov/dependabot/github_actions/docker/build-push-action-7
ci: bump docker/build-push-action from 6 to 7
2026-08-02 23:59:39 +00:00
dependabot[bot] 048c6bf131 ci: bump actions/checkout from 4 to 7
Bumps [actions/checkout](https://github.com/actions/checkout) from 4 to 7.
- [Release notes](https://github.com/actions/checkout/releases)
- [Changelog](https://github.com/actions/checkout/blob/main/CHANGELOG.md)
- [Commits](https://github.com/actions/checkout/compare/v4...v7)

---
updated-dependencies:
- dependency-name: actions/checkout
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-02 23:57:15 +00:00
Maksim Shulga 02e703ffc3 Merge pull request #21 from snegov/feature/no-shell-and-path-injection
Stop server-provided values from reaching a shell or escaping /dsc/seafile
2026-08-02 23:55:20 +00:00
Maxim Shulga c15763d9f8 Stop server-provided values from reaching a shell or escaping /dsc/seafile
Commands were joined into a string and passed to "su -c", so a login shell
parsed every interpolated value. A library name is chosen on the server, and
"sync -d /dsc/seafile/<name>" put it straight into that string: a library
named 'Docs; touch /tmp/pwned; #' ran as an arbitrary command. Confirmed
against the built image before and after this change.

Every command is now an argument list executed by "runuser --", which execs
directly with no shell. runuser -u sets the same HOME and a PATH that still
finds the seaf-cli wrapper, so the daemon environment is unchanged.

The password no longer needs its surrounding quotes, which also fixes
passwords containing quotes, dollar signs, and backticks.

Library names are untrusted, so dsc/paths.py reduces each one to a single
path component and proves the result stays under the libraries directory
with symlinks resolved. Empty, ".", "..", and names containing a separator
are skipped with a warning; names that would collide are suffixed with their
library ID rather than sharing a directory.

Tests cover quotes, command substitutions, separators, newlines, absolute
paths, parent traversal, Unicode, and colliding names. They run in a separate
CI job so application failures stay distinguishable from packaging failures.
2026-08-02 16:53:19 -07:00
dependabot[bot] 90d1c8d1bb ci: bump docker/metadata-action from 5 to 6
Bumps [docker/metadata-action](https://github.com/docker/metadata-action) from 5 to 6.
- [Release notes](https://github.com/docker/metadata-action/releases)
- [Commits](https://github.com/docker/metadata-action/compare/v5...v6)

---
updated-dependencies:
- dependency-name: docker/metadata-action
  dependency-version: '6'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-02 23:34:48 +00:00
dependabot[bot] d2adc54132 ci: bump docker/build-push-action from 6 to 7
Bumps [docker/build-push-action](https://github.com/docker/build-push-action) from 6 to 7.
- [Release notes](https://github.com/docker/build-push-action/releases)
- [Commits](https://github.com/docker/build-push-action/compare/v6...v7)

---
updated-dependencies:
- dependency-name: docker/build-push-action
  dependency-version: '7'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-02 23:34:37 +00:00
dependabot[bot] 2b29865b9c pip: bump requests from 2.33.0 to 2.34.2
Bumps [requests](https://github.com/psf/requests) from 2.33.0 to 2.34.2.
- [Release notes](https://github.com/psf/requests/releases)
- [Changelog](https://github.com/psf/requests/blob/main/HISTORY.md)
- [Commits](https://github.com/psf/requests/compare/v2.33.0...v2.34.2)

---
updated-dependencies:
- dependency-name: requests
  dependency-version: 2.34.2
  dependency-type: direct:production
  update-type: version-update:semver-minor
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-02 23:34:33 +00:00
dependabot[bot] e3fb2cb255 ci: bump docker/login-action from 3 to 4
Bumps [docker/login-action](https://github.com/docker/login-action) from 3 to 4.
- [Release notes](https://github.com/docker/login-action/releases)
- [Commits](https://github.com/docker/login-action/compare/v3...v4)

---
updated-dependencies:
- dependency-name: docker/login-action
  dependency-version: '4'
  dependency-type: direct:production
  update-type: version-update:semver-major
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-02 23:34:25 +00:00
Maksim Shulga 50ede0b2f9 Merge pull request #14 from snegov/feature/dependabot-updates
Track dependency updates with Dependabot
2026-08-02 23:33:39 +00:00
Maxim ShulgaandClaude Opus 5 bef866fb6a Track dependency updates with Dependabot
Add a weekly Dependabot configuration for pip, the Dockerfile base image,
and the GitHub Actions used by the publish workflow.

The Seafile AppImage is fetched by URL with a pinned checksum, which
Dependabot cannot resolve, so it stays a manual bump.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 16:29:35 -07:00
Maksim Shulga dc1a9b6f03 Merge pull request #13 from snegov/feature/dockerignore-and-unused-imports
Trim the build context and drop unused imports
2026-08-02 23:27:44 +00:00
Maxim ShulgaandClaude Opus 5 2126808cee Trim the build context and drop unused imports
Add a .dockerignore that whitelists only requirements.txt, start.py and
dsc/. The build context previously included .git, .idea, __pycache__ and
any local .env, which slowed builds and put a secrets file within reach
of any future COPY of the whole tree.

Remove the unused urlparse import from dsc/client.py and the redundant
import os.path from start.py; importing os already binds os.path.

Record both in IMPROVEMENTS.md, including the part still outstanding:
binutils and squashfs-tools remain in the runtime image because the
AppImage is unpacked in the same stage.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 16:23:04 -07:00
Maksim Shulga ff22f05576 Merge pull request #12 from snegov/feature/ci-release-pipeline
Publish one release image digest from a modernised workflow
2026-08-02 23:20:15 +00:00
Maxim ShulgaandClaude Opus 5 9b9d4f0577 Publish one release image digest from a modernised workflow
The push job called build-push-action twice, once for the ref tag and once
for latest. Two builds meant the two tags could resolve to different manifest
digests. Build once and let docker/metadata-action supply both tags and the
OCI labels for that single build.

Replace the deprecated actions/checkout@v2 and docker/build-push-action@v1,
default workflow permissions to contents: read so pull requests cannot reach
publication credentials, and authenticate with a scoped DOCKER_TOKEN through
docker/login-action instead of DOCKER_PASSWORD.

The test job's docker-compose.test.yml branch was dead; that file does not
exist in the repository.

Co-Authored-By: Claude Opus 5 <noreply@anthropic.com>
2026-08-02 16:18:03 -07:00
Maxim Shulga 6abd3323d2 Reconcile the improvement plan with the AppImage change
The signature acceptance criterion assumed the signed APT repository.
Upstream ships a bare AppImage with no digest or signature, so as written
it could never be met and would block the release gate indefinitely.
State what the build actually enforces, and track the weakened supply
chain as its own item rather than only a note.
2026-08-02 16:07:18 -07:00
Maksim Shulga b71a29b6ef Merge pull request #10 from snegov/dependabot/pip/requests-2.33.0
Bump requests from 2.32.4 to 2.33.0
2026-08-02 23:05:58 +00:00
dependabot[bot] cd2983af52 Bump requests from 2.32.4 to 2.33.0
Bumps [requests](https://github.com/psf/requests) from 2.32.4 to 2.33.0.
- [Release notes](https://github.com/psf/requests/releases)
- [Changelog](https://github.com/psf/requests/blob/main/HISTORY.md)
- [Commits](https://github.com/psf/requests/compare/v2.32.4...v2.33.0)

---
updated-dependencies:
- dependency-name: requests
  dependency-version: 2.33.0
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-08-02 23:03:35 +00:00
Maksim Shulga f8a8e12add Merge pull request #11 from snegov/feature/appimage-seafile-cli
Install Seafile CLI from AppImage instead of the APT repository
2026-08-02 23:00:29 +00:00
Maxim Shulga c558caba5b Keep the working directory off the CLI wrapper's search paths
Neither LD_LIBRARY_PATH nor PYTHONPATH is set in the base image, so
appending them unconditionally left a trailing ':'. An empty entry in a
colon-separated search path means the working directory, and Python
resolved it to /dsc on sys.path. Append the separator only when the
variable is already non-empty.

Reported by the automated review on #11.
2026-08-02 15:55:55 -07:00
Maxim Shulga 523a0955c4 Install Seafile CLI from AppImage instead of the APT repository
Seafile discontinued linux-clients.seafile.com: it resolves but accepts
no connections on 80 or 443, and the official docs no longer mention APT
at all. Every `docker build` has failed since. Upstream now ships the CLI
as an AppImage, so install 9.0.19 from the download site.

The AppImage is unpacked rather than executed. Running one needs FUSE and
so a privileged container, and its self-extraction also fails when the
build host cannot execute the payload's architecture. Unpacking the
appended squashfs directly avoids both.

Also add the bundled seafile/pysearpc bindings to the venv path. The APT
package installed them system-wide, where `venv --system-site-packages`
picked them up; dsc imports seafile directly for RPC, not only through
seaf-cli, so it broke when that implicit dependency went away.

Drops apt-key, pins the version, and verifies a SHA256 before unpacking.
Build-time smoke checks assert the seaf-cli subcommands and the app's own
imports.

Note: the AppImage is x86_64-only, and upstream publishes no digest or
signature, so the pinned checksum is trust-on-first-use.
2026-08-02 15:39:29 -07:00
Maxim Shulga e7fce80239 Correct smoke-check item: seaf-cli has no --version flag 2026-08-02 15:07:33 -07:00
Maxim Shulga e3c6f28182 Pin Compose example to 0.0.13, the current release 2026-08-02 15:00:48 -07:00
Maxim Shulga d500ddc7ab Fix and validate Compose quick start
The list-form environment syntax in the README passed quote characters
through as part of the value, so LIBRARY_ID was read as '"<id>"' and no
matching library was found. Switch to mapping syntax, where YAML strips
the quotes.

- Pin the example to a versioned image instead of implicit latest
- Add a checked-in compose.example.yaml
- Validate it with `docker compose config` in CI
- Link the Docker Hub image from the README
2026-08-02 14:53:08 -07:00
snegov a7abdab1f7 Add HTTP retry strategy for server connection failures
Implement automatic retry with exponential backoff (up to 30 attempts)
for 502/503/504 errors. Prevents container crash-loop during server
outages, reducing kernel log spam from repeated restarts.
2026-02-03 00:31:09 -08:00
snegov fe9f5a9272 Improve library status output formatting
Add dynamic column width alignment for library names up to 30 chars.
Prevents excessive whitespace when library names vary significantly
in length while maintaining readability for typical names.
2026-02-02 21:11:10 -08:00
Maks Snegov 42a0f3f05c Merge pull request #9 from snegov/dependabot/pip/requests-2.32.4
Bump requests from 2.32.0 to 2.32.4
2026-02-02 21:10:45 -08:00
dependabot[bot] 9860ee9b40 Bump requests from 2.32.0 to 2.32.4
Bumps [requests](https://github.com/psf/requests) from 2.32.0 to 2.32.4.
- [Release notes](https://github.com/psf/requests/releases)
- [Changelog](https://github.com/psf/requests/blob/main/HISTORY.md)
- [Commits](https://github.com/psf/requests/compare/v2.32.0...v2.32.4)

---
updated-dependencies:
- dependency-name: requests
  dependency-version: 2.32.4
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2026-02-03 05:09:23 +00:00
Maks Snegov 446eb8e1ef Merge pull request #7 from snegov/dependabot/pip/requests-2.32.0
Bump requests from 2.31.0 to 2.32.0
2026-02-02 21:07:11 -08:00
dependabot[bot] 9f8eb92e5b ---
updated-dependencies:
- dependency-name: requests
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2024-05-21 06:22:09 +00:00
snegov a7f351a75f Use RPC to fetch sync status 2023-10-24 22:12:02 -07:00
snegov b03d7bb1a3 Fix concealing a password in logs 2023-10-20 18:07:54 -07:00
snegov ffc972662e Merge pull request #6 from snegov/5-add-delete-confirm-threshold-option
Add DELETE_CONFIRM_THRESHOLD option
2023-10-20 17:39:03 -07:00
snegov 452c29ac95 Add DELETE_CONFIRM_THRESHOLD option 2023-10-20 17:32:34 -07:00
snegov ca40cce9e9 Merge pull request #4 from subvillion/patch-1
fix: client.py sync_lib password escaping
2023-10-18 09:21:00 -07:00
subvillion 9305c636e1 fix: client.py sync_lib password escaping
Please add some escaping in password env, I have password similar "xxxx&zzzz", and "&" broke syncing:

```
2023-10-16 12:50:04,655 Listing local libraries: seaf-cli list
2023-10-16 12:50:05,108 Syncing library btsync: seaf-cli sync -l 3XX2-XXX-2eXXea -s https://xxxxxxxx.xx -d /dsc/seafile/btsync -u xxx@xx.xx -p ********
-bash: line 1: zzzz: command not found
Traceback (most recent call last):
  File "/usr/bin/seaf-cli", line 1023, in <module>
    main()
  File "/usr/bin/seaf-cli", line 1019, in main
    args.func(args)
  File "/usr/bin/seaf-cli", line 675, in seaf_sync
    token = get_token(url, username, password, tfa, conf_dir)
```
2023-10-16 13:11:26 +03:00
snegov 7f39e0f271 Initialize seafile client during container start 2023-09-16 01:27:46 -07:00
snegov 9f6c417147 Use debian as base docker image 2023-09-15 20:00:04 -07:00
snegov 639265f718 Merge pull request #3 from snegov/dependabot/pip/requests-2.31.0
Bump requests from 2.27.1 to 2.31.0
2023-09-14 16:24:59 -07:00
snegov 6af5eb1b26 Wait for seafile daemon to start 2023-09-14 16:22:02 -07:00
dependabot[bot] 43237dc1f3 Bump requests from 2.27.1 to 2.31.0
Bumps [requests](https://github.com/psf/requests) from 2.27.1 to 2.31.0.
- [Release notes](https://github.com/psf/requests/releases)
- [Changelog](https://github.com/psf/requests/blob/main/HISTORY.md)
- [Commits](https://github.com/psf/requests/compare/v2.27.1...v2.31.0)

---
updated-dependencies:
- dependency-name: requests
  dependency-type: direct:production
...

Signed-off-by: dependabot[bot] <support@github.com>
2023-05-23 03:15:40 +00:00
snegov 724166b4a4 Support library names in configuration 2022-01-30 18:27:37 +03:00
snegov 681b11bbc1 Update README 2021-02-28 23:27:51 +03:00
snegov 310eb9028c Save seafile-data info in volume 2021-02-28 23:27:26 +03:00
snegov 4dcac70520 Removed DATA_DIR environment variable 2021-02-28 23:26:04 +03:00
snegov 6eadca4041 Update seafile repo URL 2021-01-30 22:59:09 +03:00
snegov 8a0b1abfe7 Fix typo in README 2021-01-30 22:35:48 +03:00
snegov a7ef878490 Update github workflow
fix
2020-08-26 00:06:59 +03:00
snegov d8438e13f5 Fix getting seafile server URL 2020-08-25 23:17:58 +03:00
snegov e73c62d034 Update github workflow 2020-08-25 22:55:13 +03:00
snegov 6048280983 Update installation process in Dockerfile 2020-08-25 21:30:44 +03:00
snegov e35cf0efa5 Fix incorrect schema issue 2020-08-25 21:17:34 +03:00
snegov ebf7574bde Update github workflow 2020-06-04 22:32:57 +03:00
snegov e4268c0b21 Update github workflow 2020-06-04 22:29:20 +03:00
snegov 91758903e9 Update github workflow 2020-06-04 22:00:45 +03:00
snegov e1d84f2d75 Update github workflow 2020-06-04 21:56:00 +03:00
snegov 10f6a5ec32 Add github workflow 2020-06-04 21:38:34 +03:00
snegov e4e60c1023 Add cleanup after package install in Dockerfile 2020-06-04 21:16:58 +03:00
40 changed files with 3115 additions and 188 deletions

No files matched your search

+11
View File
@@ -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]
+35
View File
@@ -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
+113
View File
@@ -0,0 +1,113 @@
name: Docker
on:
push:
branches:
- master
tags:
- '*'
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@v7
- 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: [unit-test, test]
runs-on: ubuntu-latest
if: github.event_name == 'push' && startsWith(github.ref, 'refs/tags/')
steps:
- uses: actions/checkout@v7
# 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_TOKEN }}
- name: Build and push
uses: docker/build-push-action@v7
with:
context: .
push: true
tags: ${{ steps.meta.outputs.tags }}
labels: ${{ steps.meta.outputs.labels }}
+1
View File
@@ -3,3 +3,4 @@
__pycache__/
.python-version
docker-compose.yml
.smoke-*/
+102
View File
@@ -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.
Symlink
+1
View File
@@ -0,0 +1 @@
AGENTS.md
+83 -13
View File
@@ -1,23 +1,93 @@
FROM python:3-slim
FROM debian:bookworm-slim
RUN apt-get update && apt-get install gnupg -y
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv-keys 8756C4F765C9AC3CB6B85D62379CE192D401AB61 && \
echo deb http://deb.seadrive.org buster main | tee /etc/apt/sources.list.d/seafile.list && \
apt-get update -y && \
apt-get install -y seafile-cli procps curl 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
# 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 ./
RUN pip install --no-cache-dir -r 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 seafile_client ./seafile_client/
# 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
# 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
View File
@@ -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 -1
View File
@@ -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
+116 -24
View File
@@ -1,35 +1,127 @@
# docker-seafile-client
Run a seafile client inside docker witch can sync files from seafile repositories
Docker image for [Seafile CLI client](https://help.seafile.com/syncing_client/linux-cli/).
See docker-compose how to use.
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
container_name: seafile-client
image: snegov/seafile-client:0.0.13
environment:
- LIBRARY_ID=<your-library-id-here>
- SERVER_HOST=<server-host>
- SERVER_PORT=<server-port>
- USERNAME=<username>
- PASSWORD=<password>
- DATA_DIR=<directory-path-to-sync>
- SEAFILE_UID=<your_uid>
- SEAFILE_GID=<your_gid>
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:
- <host-volume-path>:<directory-path-to-sync>
- /home/johndow/seafile:/dsc/seafile
- sync-data:/dsc/seafile-data
container_name: seafile-client
volumes:
sync-data:
```
## Environment variables:
- `LIBRARY_ID=<your-library-id-here>` ID of library to sync; multiple libraries could be separated by colon `:`
- `SERVER_HOST=<server-host>` Hostname of your seafile server, eg: seafile.example.com
- `SERVER_PORT=<server-port>` Which port the server is hosted on: usually 443 (https) or 80 (http)
- `USERNAME=<username>` Seafile account username
- `PASSWORD=<password>` Seafile account password
- `DATA_DIR=<directory-path-to-sync>` The path where to put the files
- `SEAFILE_UID=<uid>` Downloaded files will have this uid
- `SEAFILE_GID=<gid>` Downloaded files will have this gid
### 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).
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.
### Using Docker secrets:
Mount the secret and point `PASSWORD_FILE` at it, so the password never enters
the environment:
```yaml
services:
seafile-client:
environment:
PASSWORD_FILE: /run/secrets/seafile_password
secrets:
- seafile_password
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/)
+19
View File
@@ -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:
-17
View File
@@ -1,17 +0,0 @@
version: '3'
services:
seafile-client:
restart: always
image: snegov/seafile-client
container_name: seafile-client
environment:
- LIBRARY_ID=<your-library-id-here>
- SERVER_HOST=<server-host>
- SERVER_PORT=<server-port>
- USERNAME=<username>
- PASSWORD=<password>
- DATA_DIR=<directory-path-to-sync>
- SEAFILE_UID=<your_uid>
- SEAFILE_GID=<your_gid>
volumes:
- <host-volume-path>:<directory-path-to-sync>
+1
View File
@@ -0,0 +1 @@
from .client import SeafileClient, const
+386
View File
@@ -0,0 +1,386 @@
import argparse
import json
import logging
import os
import subprocess
import time
from typing import Optional
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 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 = None,
app_dir: str = const.DEFAULT_APP_DIR,
token: str = None):
self.user = user
self.password = passwd
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)
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 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)
def remote_libraries(self) -> dict:
url = f"{self.url}/api2/repos/"
_lg.info("Fetching remote libraries: %s", url)
auth_header = {"Authorization": f"Token {self.token}"}
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 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]:
"""
Resolve a requested name or ID to the one library ID it names.
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,
# 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 __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()
# fetch statuses of libraries being cloned
tasks = self.rpc.get_clone_tasks()
for clone_task in tasks:
if clone_task.state == "done":
continue
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(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:
# 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
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 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
if value is None:
raise ConfigError(f"No value for seafile option {key}")
# 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
# 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()
+66
View File
@@ -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}")
+29
View File
@@ -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",
}
+25
View File
@@ -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."""
+98
View File
@@ -0,0 +1,98 @@
import os
import pwd
import subprocess
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)
user_pwinfo = pwd.getpwnam(DEFAULT_USERNAME)
os.chown(dir_path, user_pwinfo.pw_uid, user_pwinfo.pw_gid)
else:
if not os.path.isdir(dir_path):
raise RuntimeError(f"Data dir {dir_path} is not a directory")
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 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
View File
@@ -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
+57
View File
@@ -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
+21
View File
@@ -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())
+4
View File
@@ -0,0 +1,4 @@
[pytest]
testpaths = tests
# The application is imported from the repository root, not installed.
pythonpath = .
+3
View File
@@ -0,0 +1,3 @@
-r requirements.txt
pytest==9.2.0
+2 -1
View File
@@ -1 +1,2 @@
requests
cached_property==2.0.1
requests==2.34.2
-1
View File
@@ -1 +0,0 @@
from .client import SeafileClient, start_seaf_daemon
-87
View File
@@ -1,87 +0,0 @@
import logging
import os
import subprocess
import time
import requests
from .consts import DEFAULT_USERNAME
from .misc import create_dir
logging.basicConfig(format="%(asctime)s %(message)s",
level=logging.INFO)
class SeafileClient:
def __init__(self, host: str, port: int, user: str, passwd: str):
self.url = f"https://{host}:{port}"
self.user = user
self.password = passwd
self.__token = None
def __str__(self):
return f"SeafileClient({self.user}@{self.url})"
@property
def token(self):
if self.__token is None:
url = f"{self.url}/api2/auth-token/"
r = requests.post(url, data={"username": self.user,
"password": self.password})
if r.status_code != 200:
raise RuntimeError(f"Can't get token: {r.text}")
self.__token = r.json()['token']
return self.__token
def get_lib_name(self, lib_id: str) -> str:
url = f"{self.url}/api2/repos/{lib_id}"
auth_header = {"Authorization": f"Token {self.token}"}
r = requests.get(url, headers=auth_header)
if r.status_code != 200:
raise RuntimeError(r.text)
return r.json()['name']
def sync_lib(self, lib_id: str, data_dir: str):
lib_name = self.get_lib_name(lib_id)
lib_dir = os.path.join(data_dir, lib_name.replace(' ', '_'))
create_dir(lib_dir)
cmd = ['seaf-cli', 'sync',
'-l', lib_id,
'-s', self.url,
'-d', lib_dir,
'-u', self.user,
'-p', self.password]
cmd = ' '.join(cmd)
subprocess.run(['su', '-', DEFAULT_USERNAME, '-c', cmd])
def get_status(self):
cmd = 'seaf-cli status'
out = subprocess.check_output(['su', '-', DEFAULT_USERNAME, '-c', cmd])
out = out.decode().splitlines()
statuses = dict()
for line in out:
if line.startswith('#') or not line.strip():
continue
lib, status = line.split(sep='\t', maxsplit=1)
lib = lib.strip()
status = " ".join(status.split())
statuses[lib] = status
return statuses
def watch_status(self):
prev_status = dict()
while True:
time.sleep(5)
cur_status = self.get_status()
for folder, state in cur_status.items():
if state != prev_status.get(folder):
logging.info(f"Library {folder}:\t{state}")
prev_status[folder] = cur_status[folder]
def start_seaf_daemon():
cmd = 'seaf-cli start'
subprocess.run(['su', '-', DEFAULT_USERNAME, '-c', cmd])
time.sleep(5)
-1
View File
@@ -1 +0,0 @@
DEFAULT_USERNAME = "seafile"
-25
View File
@@ -1,25 +0,0 @@
import os
import pwd
import subprocess
from .consts import DEFAULT_USERNAME
def setup_uid(uid: int, gid: int):
user_pwinfo = pwd.getpwnam(DEFAULT_USERNAME)
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_dir(dir_path: str):
if not os.path.exists(dir_path):
os.mkdir(dir_path)
user_pwinfo = pwd.getpwnam(DEFAULT_USERNAME)
os.chown(dir_path, user_pwinfo.pw_uid, user_pwinfo.pw_gid)
else:
if not os.path.isdir(dir_path):
raise RuntimeError(f"Data dir {dir_path} is not a directory")
def tail_f(fpath):
os.system(f"tail -f {fpath}")
+163 -18
View File
@@ -1,35 +1,180 @@
#!/usr/bin/env python3
import argparse
import logging
import os
import os.path
import signal
import sys
from seafile_client import SeafileClient, start_seaf_daemon
from seafile_client.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"), type=int)
parser.add_argument("--gid", default=os.getenv("SEAFILE_GID"), type=int)
parser.add_argument("--data-dir", default=os.getenv("DATA_DIR"))
parser.add_argument("--host", default=os.getenv("SERVER_HOST"))
parser.add_argument("--port", default=os.getenv("SERVER_PORT"), type=int)
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)
start_seaf_daemon()
create_dir(args.data_dir)
client = SeafileClient(args.host, args.port, args.username, args.password)
for lib_id in args.libs.split(sep=":"):
client.sync_lib(lib_id, args.data_dir)
client.watch_status()
create_dir(const.DEFAULT_APP_DIR)
drop_privileges(args.uid, args.gid)
return 0
client = SeafileClient(args.server, args.username, password,
const.DEFAULT_APP_DIR, token=token)
# 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
return run(client, args, libs_dir)
if __name__ == "__main__":
+53
View File
@@ -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
View File
@@ -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))
+306
View File
@@ -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
+120
View File
@@ -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)
+186
View File
@@ -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)
+40
View File
@@ -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
+73
View File
@@ -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
+56
View File
@@ -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"}
+111
View File
@@ -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"}
+82
View File
@@ -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
+70
View File
@@ -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