13 Commits
Author SHA1 Message Date
orrisroot 1cce7cf3e0 build: release 2.0.4
Release / build-linux-x86_64 (push) Successful in 2m32s
Release / build-linux-aarch64 (push) Successful in 2m30s
2026-11-27 17:23:53 +09:00
orrisroot 4069581098 fix(folders): handle locked folder access consistently
Recognize the server's short locked-folder response and preserve the
password proof required by subsequent folder and file requests.

- Report locked short records with a typed folder error
- Share the folder-auth cookie across connections and token refreshes
- Authenticate a locked folder selected as the root of a recursive
  download
- Remove DOI-specific password authentication in favor of common
  folder access routines
2026-11-27 17:19:24 +09:00
orrisroot 05051dd307 feat(acl): compose access levels from their bits
Replace the fixed access-level table so new project levels are
labelled correctly and configurable through the CLI, matching the
Python client's project-aware behavior.

- Build labels from restrict, project, and password bits, and show
  meaningless values as Unknown (0x...)
- Read project names from users/current once for each ls run and use
  them in plain and JSON output
- Parse composable chacl keys, list available projects on invalid
  input, and reject public and storage before API requests
- Remove the obsolete 5kikan access-level key
2026-11-27 17:19:14 +09:00
orrisroot 22330d2b88 chore(deps): update dependencies and resolve url advisory
Refresh dependencies to resolve RUSTSEC-2026-0592 and keep the
direct dependency requirements aligned with the resolved lockfile.

- Update compatible dependencies, including url 2.5.9
- Migrate reqwest to 0.13 and dirs to 7
- Enable the reqwest form, query, and renamed rustls features
- Align Cargo.toml dependency versions with Cargo.lock
2026-11-27 16:23:29 +09:00
orrisroot a036d3ef46 fix(scripts): report Gitea API errors in release uploads
The macOS and Linux release scripts called the Gitea API with
`curl -sf`, which discards the response on failure. A rejected token
surfaced only as a JSON decode error from the release id lookup.

- Route API calls through gitea_api, which keeps the HTTP status and
  the response body
- On failure print the status and Gitea's message, with a hint about
  the token scope on 401/403, and exit
- Look up the release first and create it only on 404 instead of
  ignoring every creation error
- Check the status of each asset upload
2026-11-04 20:15:15 +09:00
orrisroot e1081aeff4 fix(scripts): keep .env values out of the PowerShell session
A .ps1 runs inside the caller's PowerShell process, so the values the
Windows release script exported from .env outlived the script. A
later run in the same session kept the old GITEA_TOKEN even after .env
was edited, because existing environment variables take precedence.

- Read .env into a script-local table and resolve settings through
  Get-Setting, with environment variables still taking precedence
- Stop changing the caller's current location; build and archive
  with paths anchored at the repository root
- Skip .env lines without "=" instead of failing under StrictMode
2026-11-04 20:15:14 +09:00
orrisroot 2de331ad29 build: bump to 2.0.3 and update dependencies
Release / build-linux-x86_64 (push) Successful in 2m3s
Release / build-linux-aarch64 (push) Successful in 1m53s
Clear the advisories that cargo audit reports against the lockfile.

- Update rustls, quinn-proto and ctutils to their fixed releases.
- Move zip to 9, whose ZipFile::name() now returns a Result.
- Add the 2.0.3 entry to the changelog.
2026-11-04 16:35:59 +09:00
orrisroot 663956ead7 docs: add a changelog
Release / build-linux-x86_64 (push) Successful in 2m20s
Release / build-linux-aarch64 (push) Successful in 1m57s
The project kept no change history of its own, so the tags were the
only record of what each release contained.

- Summarise 2.0.0, 2.0.1 and 2.0.2 by what changed for the user.
- Link the changelog from the README.
2026-09-04 18:23:33 +09:00
orrisroot cb5cff7b64 build: bump to 2.0.2 and update dependencies
- Raise tokio, base64, serde_json and anyhow to the releases they are
  tested against, and refresh the lockfile.
- base64 0.23 needed no change to the code that uses it.
2026-09-04 18:23:33 +09:00
orrisroot a16f73543d fix: stream transfers and close gaps against the Python client
A review against the Python client, which shares this client's config
and login cache, found the transfers holding whole files in memory and
several commands answering differently from their Python counterparts.

- Stream uploads and downloads instead of buffering the whole file, so
  memory no longer scales with file size times concurrency. Uploads
  still declare a Content-Length rather than going out chunked.
- Write a download beside its destination and move it into place once
  complete, and refuse a destination that cannot be written, so a
  failed transfer leaves what was already there untouched.
- Report the server's own error detail instead of the bare status.
- List locked sub-folders in `ls --json --recursive` using the given
  password and skip only those that cannot be unlocked, instead of
  failing the whole listing.
- Name each folder's laboratory in JSON output and sort its entries,
  matching the Python client's schema and order.
- Ask the server who is logged in for `whoami`, rather than trusting
  the cached name.
- Collapse repeated separators and refuse `..` in remote paths.
- Fall back to the API when a laboratory is missing from the cache, so
  a newly added one no longer needs a fresh login.
- Verify the login cache digest on read, as the Python client does.
- Accept `-e` as the short form of `--exclude`.
- Satisfy clippy and rustfmt across the crate.
2026-09-04 16:31:14 +09:00
orrisroot c24a285cf5 fix(selfupdate): verify the archive before replacing the binary
`mdrs selfupdate` replaced the running binary with whatever the release
endpoint returned, checking only that the transport succeeded. Nothing
proved the archive was the one the release publishes.

- Compare the downloaded archive against the release's `.sha256` asset
  and abort the update on a mismatch.
- Report a release that publishes no checksum as unverified, rather
  than letting its absence pass for a verified download.
- Exclude `.sha256` assets when matching the archive for the build
  target: those assets carry the target name too.
- Write and upload a checksum beside every archive, from the Gitea
  release workflow and the three local build scripts.
2026-09-04 16:31:02 +09:00
orrisroot e3026bdfcf feat(auth): send a request again when its token lapsed in the queue
A request can wait to be served for longer than the access token it was
sent with lives, and comes back refused for a token that was valid when
it left. Uploads that take minutes make that wait ordinary.

- send once more when a refusal is answered by a different token, which
  is the only refusal a second attempt can help; a wrong folder
  password, an anonymous request and an ended session all leave the
  token untouched and stay with the caller who knows what they mean
- rebuild the upload and read the file again for its retry, but only
  once the token has moved on: any other refusal would cost a second
  full transfer to be told the same
- say the server may be overloaded when the second attempt is refused
  too, rather than sending the user off to log in over a session that
  is fine
2026-08-14 18:37:40 +09:00
orrisroot bcf99dd6d7 fix(auth): keep the refresh token the provider hands back
The reply to a refresh carries a new refresh token and the provider
stops honouring the one that was sent. Only the access half was read,
so the cache kept re-sending a token the server had already retired.

- deserialize the refresh half and write it back to the cache, as an
  Option so a provider that does not rotate leaves the stored one be
- bound the refresh request on its own: the caller holds a lock that
  spans processes while it runs, so a provider that goes quiet would
  stall every other request on the machine
- give config create/update one rule for what a remote URL is, and
  store it without the trailing slash, matching the Python client so
  the two can share config.ini; this drops the validators crate and
  77 transitive dependencies with it
- join the base URL and the API's relative download path with the
  separator neither of them carries, as download.rs already does
2026-08-14 16:36:43 +09:00
34 changed files with 2943 additions and 1881 deletions
+10 -2
View File
@@ -26,12 +26,16 @@ jobs:
TARGET=x86_64-unknown-linux-musl TARGET=x86_64-unknown-linux-musl
ARCHIVE="mdrs-${VERSION}-${TARGET}.tar.gz" ARCHIVE="mdrs-${VERSION}-${TARGET}.tar.gz"
tar -czf "${ARCHIVE}" -C target/${TARGET}/release mdrs tar -czf "${ARCHIVE}" -C target/${TARGET}/release mdrs
# Published alongside the archive so `mdrs selfupdate` can check what it fetched.
sha256sum "${ARCHIVE}" > "${ARCHIVE}.sha256"
echo "ARCHIVE=${ARCHIVE}" >> "$GITHUB_ENV" echo "ARCHIVE=${ARCHIVE}" >> "$GITHUB_ENV"
- name: Create release and upload asset - name: Create release and upload asset
uses: akkuman/gitea-release-action@v1 uses: akkuman/gitea-release-action@v1
with: with:
token: ${{ github.token }} token: ${{ github.token }}
files: ${{ env.ARCHIVE }} files: |
${{ env.ARCHIVE }}
${{ env.ARCHIVE }}.sha256
build-linux-aarch64: build-linux-aarch64:
runs-on: ubuntu-latest runs-on: ubuntu-latest
@@ -55,9 +59,13 @@ jobs:
TARGET=aarch64-unknown-linux-musl TARGET=aarch64-unknown-linux-musl
ARCHIVE="mdrs-${VERSION}-${TARGET}.tar.gz" ARCHIVE="mdrs-${VERSION}-${TARGET}.tar.gz"
tar -czf "${ARCHIVE}" -C target/${TARGET}/release mdrs tar -czf "${ARCHIVE}" -C target/${TARGET}/release mdrs
# Published alongside the archive so `mdrs selfupdate` can check what it fetched.
sha256sum "${ARCHIVE}" > "${ARCHIVE}.sha256"
echo "ARCHIVE=${ARCHIVE}" >> "$GITHUB_ENV" echo "ARCHIVE=${ARCHIVE}" >> "$GITHUB_ENV"
- name: Create release and upload asset - name: Create release and upload asset
uses: akkuman/gitea-release-action@v1 uses: akkuman/gitea-release-action@v1
with: with:
token: ${{ github.token }} token: ${{ github.token }}
files: ${{ env.ARCHIVE }} files: |
${{ env.ARCHIVE }}
${{ env.ARCHIVE }}.sha256
+67
View File
@@ -0,0 +1,67 @@
# Changelog
All notable changes to this project will be documented in this file.
## [2.0.4] - 2026-11-27
### Changed
- Updated dependencies and migrated to `reqwest` 0.13 and `dirs` 7.
- Built access-level labels from their bits and named project levels using the projects returned by the server. `chacl` accepts composable keys such as `project0_open` and `cbs_or_pw_open`, and an invalid key lists the user's available project keys. The obsolete `5kikan_open` key is no longer accepted; `public` and `storage` are refused before any request.
### Fixed
- Labelled meaningless access levels as `Unknown (0x…)` rather than `Storage` or an unrelated combination.
- Recognized a locked folder's short retrieve response as a lock instead of malformed JSON. DOI resolution only maps the DOI to a folder id; subsequent access uses the same folder and file routines as ordinary paths, without DOI-specific password authentication.
- Preserved the cookie returned by folder-password authentication for subsequent folder and file requests, including connections using refreshed access tokens.
- Authenticated a locked folder selected as the root of a recursive download, rather than authenticating only its descendants.
### Security
- Updated `url` to 2.5.9 to resolve RUSTSEC-2026-0592.
## [2.0.3] - 2026-11-04
### Changed
- Updated dependencies, including `zip` 9.
### Security
- Updated `rustls`, `quinn-proto` and `ctutils` to releases that fix known vulnerabilities.
- Moved to `zip` 9, which fixes known vulnerabilities in archive extraction. `selfupdate` reads the binary out of the archive directly and was not affected.
## [2.0.2] - 2026-09-04
### Added
- Accepted `-e` as the short form of `download --exclude`.
### Changed
- Transferred files larger than the memory available, in both directions.
- Left an existing local file intact when a download fails part way through.
- Showed the reason the server gave when it refused a request.
- Updated dependencies.
### Fixed
- Kept a session working across concurrent runs, long server queues, and providers that rotate refresh tokens.
- Listed a tree containing locked folders with `ls --json --recursive` instead of failing on the first one.
- Other minor fixes to `ls --json` output, remote path handling, and the login cache.
### Security
- Verified the downloaded archive against the release checksum before `selfupdate` replaces the binary.
## [2.0.1] - 2026-06-12
### Added
- Accepted a DOI in place of a path, as `remote:10.xxxx/prefix.ID[/sub/path]`.
- Allowed `download` and the read-only commands to run without signing in.
## [2.0.0] - 2026-04-20
First release of the command-line client.
### Added
- Commands `config`, `login`, `logout`, `whoami`, `labs`, `ls`, `mkdir`, `upload`, `download`, `mv`, `cp`, `rm`, `chacl`, `metadata`, `file-metadata`, `version`, and `selfupdate`.
- Release build scripts for Linux, macOS, and Windows.
### Changed
- Sped up transfers by working on folders and files in parallel, bounded by `MDRS_CLIENT_CONCURRENT`.
### Fixed
- Kept the session valid throughout a long-running transfer, and across concurrent runs.
- Handled file and folder names with combining characters consistently.
Generated
+691 -1343
View File
File diff suppressed because it is too large Load Diff
+22 -22
View File
@@ -1,6 +1,6 @@
[package] [package]
name = "mdrs-client-rust" name = "mdrs-client-rust"
version = "2.0.1" version = "2.0.4"
edition = "2024" edition = "2024"
license = "MIT" license = "MIT"
authors = ["Neuroinformatics Unit, RIKEN CBS"] authors = ["Neuroinformatics Unit, RIKEN CBS"]
@@ -11,26 +11,26 @@ name = "mdrs"
path = "src/main.rs" path = "src/main.rs"
[dependencies] [dependencies]
clap = { version = "4.5", features = ["derive"] } clap = { version = "4.6.10", features = ["derive"] }
reqwest = { version = "0.12", default-features = false, features = ["json", "multipart", "rustls-tls"] } reqwest = { version = "0.13.5", default-features = false, features = ["cookies", "form", "json", "multipart", "query", "rustls", "stream"] }
serde = { version = "1.0", features = ["derive"] } serde = { version = "1.0.229", features = ["derive"] }
serde_json = "1.0.150" serde_json = "1.0.154"
tokio = { version = "1.52.3", features = ["full"] } tokio = { version = "1.54.1", features = ["full"] }
futures = "0.3" tokio-util = { version = "0.7.20", features = ["io"] }
dirs = "6.0.0" futures = "0.3.34"
anyhow = "1.0.102" dirs = "7.0.0"
configparser = "3.2.0" anyhow = "1.0.105"
validators = "0.25.3" configparser = "3.3.0"
sha2 = "0.11.0" sha2 = "0.11.2"
rpassword = "7.5.4" rpassword = "7.5.5"
base64 = "0.22" base64 = "0.23.1"
fs2 = "0.4" fs2 = "0.4.3"
ctrlc = "3" ctrlc = "3.5.3"
os_info = "3.15.0" os_info = "3.15.0"
dotenvy = "0.15" dotenvy = "0.15.7"
unicode-normalization = "0.1" unicode-normalization = "0.1.26"
self-replace = "1" self-replace = "1.5.1"
tar = "0.4.46" tar = "0.4.46"
flate2 = "1" flate2 = "1.1.11"
zip = "8.6.0" zip = "9.8.2"
tempfile = "3" tempfile = "3.27.0"
+11 -6
View File
@@ -103,7 +103,7 @@ mdrs labs neurodata:
### ls ### ls
List the contents of a remote folder. You can also specify a DOI path in the form `remote:10.xxxx/yyy.ID[/optional/subpath]`. List the contents of a remote folder. You can also specify a DOI path in the form `remote:10.xxxx/yyy.ID[/optional/subpath]`. DOI paths always refer to public datasets and do not use folder passwords.
```shell ```shell
mdrs ls neurodata:/NIU/Repository/ mdrs ls neurodata:/NIU/Repository/
@@ -143,7 +143,7 @@ Download a file or folder from a remote path. You can also specify a DOI path.
mdrs download neurodata:/NIU/Repository/TEST/sample.dat ./ mdrs download neurodata:/NIU/Repository/TEST/sample.dat ./
mdrs download -r neurodata:/NIU/Repository/TEST/dataset/ ./ mdrs download -r neurodata:/NIU/Repository/TEST/dataset/ ./
mdrs download -p SHARING_PASSWORD neurodata:/NIU/Repository/PW_Open/Readme.dat ./ mdrs download -p SHARING_PASSWORD neurodata:/NIU/Repository/PW_Open/Readme.dat ./
mdrs download -r --exclude /NIU/Repository/TEST/dataset/skip neurodata:/NIU/Repository/TEST/dataset/ ./ mdrs download -r -e /NIU/Repository/TEST/dataset/skip neurodata:/NIU/Repository/TEST/dataset/ ./
mdrs download -r --skip-if-exists neurodata:/NIU/Repository/TEST/dataset/ ./ mdrs download -r --skip-if-exists neurodata:/NIU/Repository/TEST/dataset/ ./
# DOI access examples: # DOI access examples:
@@ -179,16 +179,16 @@ mdrs rm -r neurodata:/NIU/Repository/TEST/dataset
### chacl ### chacl
Change the access level of a remote folder. Change the access level of a remote folder. The level is `private`, `pw_open`, `cbs_open`, `project<n>_open`, or several open levels joined by `_or_`. `<n>` is the project's bit position; an invalid level lists the projects you belong to with their keys. Project names returned by the server are also used in `ls` access-level labels.
```shell ```shell
mdrs chacl private neurodata:/NIU/Repository/Private mdrs chacl private neurodata:/NIU/Repository/Private
mdrs chacl cbs_open -r neurodata:/NIU/Repository/CBS_Open mdrs chacl cbs_open -r neurodata:/NIU/Repository/CBS_Open
mdrs chacl pw_open -r -p SHARING_PASSWORD neurodata:/NIU/Repository/PW_Open mdrs chacl pw_open -r -p SHARING_PASSWORD neurodata:/NIU/Repository/PW_Open
mdrs chacl cbs_or_pw_open -p SHARING_PASSWORD neurodata:/NIU/Repository/CBS_or_PW_Open
mdrs chacl project0_open neurodata:/NIU/Repository/Project_Open
``` ```
Available access levels: `private`, `public`, `pw_open`, `cbs_open`, `5kikan_open`, `cbs_pw_open`, `5kikan_pw_open`
### metadata ### metadata
Show metadata for a remote folder. You can also specify a DOI path. Show metadata for a remote folder. You can also specify a DOI path.
@@ -224,7 +224,8 @@ mdrs version
### selfupdate ### selfupdate
Update the current `mdrs` binary to the latest published release for Update the current `mdrs` binary to the latest published release for
the same build target. the same build target. The downloaded archive is checked against the `.sha256`
asset the release publishes; a release without one is reported as unverified.
```shell ```shell
mdrs selfupdate mdrs selfupdate
@@ -240,6 +241,10 @@ mdrs --help
mdrs upload --help mdrs upload --help
``` ```
## Changelog
See [CHANGELOG.md](./CHANGELOG.md) for the full change history.
## License ## License
[MIT](LICENSE) © 2026- Neuroinformatics Unit, RIKEN CBS [MIT](LICENSE) © 2026- Neuroinformatics Unit, RIKEN CBS
+46 -16
View File
@@ -58,7 +58,10 @@ for TARGET in "${TARGETS[@]}"; do
ARCHIVE="mdrs-${VERSION}-${TARGET}.tar.gz" ARCHIVE="mdrs-${VERSION}-${TARGET}.tar.gz"
tar -czf "${ARCHIVE}" -C "target/${TARGET}/release" mdrs tar -czf "${ARCHIVE}" -C "target/${TARGET}/release" mdrs
ARCHIVES+=("${ARCHIVE}") # Uploaded alongside the archive so `mdrs selfupdate` can check what it fetched.
sha256sum "${ARCHIVE}" > "${ARCHIVE}.sha256" 2>/dev/null \
|| shasum -a 256 "${ARCHIVE}" > "${ARCHIVE}.sha256"
ARCHIVES+=("${ARCHIVE}" "${ARCHIVE}.sha256")
echo " Created: ${ARCHIVE}" echo " Created: ${ARCHIVE}"
done done
@@ -77,26 +80,53 @@ fi
: "${GITEA_SERVER_URL:?GITEA_SERVER_URL is required for upload}" : "${GITEA_SERVER_URL:?GITEA_SERVER_URL is required for upload}"
: "${GITEA_REPOSITORY:?GITEA_REPOSITORY is required for upload}" : "${GITEA_REPOSITORY:?GITEA_REPOSITORY is required for upload}"
echo "" API_BODY="$(mktemp)"
echo "==> Creating Gitea release ${TAG} ..." trap 'rm -f "${API_BODY}"' EXIT
curl -sf -X POST \
-H "Authorization: Bearer ${GITEA_TOKEN}" \
-H "Content-Type: application/json" \
"${GITEA_SERVER_URL}/api/v1/repos/${GITEA_REPOSITORY}/releases" \
-d "{\"tag_name\": \"${TAG}\", \"name\": \"${TAG}\"}" > /dev/null || true
RELEASE_ID="$(curl -sf \ # Call the Gitea repository API. The HTTP status is left in API_STATUS and
-H "Authorization: Bearer ${GITEA_TOKEN}" \ # the response body in ${API_BODY}; curl itself failing (DNS, TLS, ...)
"${GITEA_SERVER_URL}/api/v1/repos/${GITEA_REPOSITORY}/releases/tags/${TAG}" \ # aborts the script with curl's own message.
| python3 -c 'import sys,json; print(json.load(sys.stdin)["id"])')" gitea_api() {
local method="$1" path="$2"
shift 2
API_STATUS="$(curl -sS -o "${API_BODY}" -w '%{http_code}' -X "${method}" \
-H "Authorization: Bearer ${GITEA_TOKEN}" "$@" \
"${GITEA_SERVER_URL}/api/v1/repos/${GITEA_REPOSITORY}${path}")"
}
# Abort with the HTTP status and the error message Gitea returned
api_fail() {
local message
message="$(python3 -c 'import sys,json; print(json.load(sys.stdin)["message"])' \
< "${API_BODY}" 2>/dev/null || head -c 500 "${API_BODY}")"
echo "Error: $1 failed (HTTP ${API_STATUS}): ${message}" >&2
if [[ "${API_STATUS}" == 401 || "${API_STATUS}" == 403 ]]; then
echo "Check GITEA_TOKEN: it must be valid and have the write:repository scope." >&2
fi
exit 1
}
echo ""
gitea_api GET "/releases/tags/${TAG}"
if [[ "${API_STATUS}" == 200 ]]; then
echo "==> Using existing Gitea release ${TAG}"
elif [[ "${API_STATUS}" == 404 ]]; then
echo "==> Creating Gitea release ${TAG} ..."
gitea_api POST "/releases" \
-H "Content-Type: application/json" \
-d "{\"tag_name\": \"${TAG}\", \"name\": \"${TAG}\"}"
[[ "${API_STATUS}" == 201 ]] || api_fail "Creating release ${TAG}"
else
api_fail "Looking up release ${TAG}"
fi
RELEASE_ID="$(python3 -c 'import sys,json; print(json.load(sys.stdin)["id"])' < "${API_BODY}")"
echo "==> Uploading assets (release id: ${RELEASE_ID}) ..." echo "==> Uploading assets (release id: ${RELEASE_ID}) ..."
for ARCHIVE in "${ARCHIVES[@]}"; do for ARCHIVE in "${ARCHIVES[@]}"; do
echo " Uploading ${ARCHIVE} ..." echo " Uploading ${ARCHIVE} ..."
curl -sf -X POST \ gitea_api POST "/releases/${RELEASE_ID}/assets" -F "attachment=@${ARCHIVE}"
-H "Authorization: Bearer ${GITEA_TOKEN}" \ [[ "${API_STATUS}" == 201 ]] || api_fail "Uploading ${ARCHIVE}"
-F "attachment=@${ARCHIVE}" \
"${GITEA_SERVER_URL}/api/v1/repos/${GITEA_REPOSITORY}/releases/${RELEASE_ID}/assets" > /dev/null
echo " Done." echo " Done."
done done
+46 -16
View File
@@ -46,7 +46,10 @@ for TARGET in "${TARGETS[@]}"; do
ARCHIVE="mdrs-${VERSION}-${TARGET}.tar.gz" ARCHIVE="mdrs-${VERSION}-${TARGET}.tar.gz"
tar -czf "${ARCHIVE}" -C "target/${TARGET}/release" mdrs tar -czf "${ARCHIVE}" -C "target/${TARGET}/release" mdrs
ARCHIVES+=("${ARCHIVE}") # Uploaded alongside the archive so `mdrs selfupdate` can check what it fetched.
sha256sum "${ARCHIVE}" > "${ARCHIVE}.sha256" 2>/dev/null \
|| shasum -a 256 "${ARCHIVE}" > "${ARCHIVE}.sha256"
ARCHIVES+=("${ARCHIVE}" "${ARCHIVE}.sha256")
echo " Created: ${ARCHIVE}" echo " Created: ${ARCHIVE}"
done done
@@ -65,26 +68,53 @@ fi
: "${GITEA_SERVER_URL:?GITEA_SERVER_URL is required for upload}" : "${GITEA_SERVER_URL:?GITEA_SERVER_URL is required for upload}"
: "${GITEA_REPOSITORY:?GITEA_REPOSITORY is required for upload}" : "${GITEA_REPOSITORY:?GITEA_REPOSITORY is required for upload}"
echo "" API_BODY="$(mktemp)"
echo "==> Creating Gitea release ${TAG} ..." trap 'rm -f "${API_BODY}"' EXIT
curl -sf -X POST \
-H "Authorization: Bearer ${GITEA_TOKEN}" \
-H "Content-Type: application/json" \
"${GITEA_SERVER_URL}/api/v1/repos/${GITEA_REPOSITORY}/releases" \
-d "{\"tag_name\": \"${TAG}\", \"name\": \"${TAG}\"}" > /dev/null || true
RELEASE_ID="$(curl -sf \ # Call the Gitea repository API. The HTTP status is left in API_STATUS and
-H "Authorization: Bearer ${GITEA_TOKEN}" \ # the response body in ${API_BODY}; curl itself failing (DNS, TLS, ...)
"${GITEA_SERVER_URL}/api/v1/repos/${GITEA_REPOSITORY}/releases/tags/${TAG}" \ # aborts the script with curl's own message.
| python3 -c 'import sys,json; print(json.load(sys.stdin)["id"])')" gitea_api() {
local method="$1" path="$2"
shift 2
API_STATUS="$(curl -sS -o "${API_BODY}" -w '%{http_code}' -X "${method}" \
-H "Authorization: Bearer ${GITEA_TOKEN}" "$@" \
"${GITEA_SERVER_URL}/api/v1/repos/${GITEA_REPOSITORY}${path}")"
}
# Abort with the HTTP status and the error message Gitea returned
api_fail() {
local message
message="$(python3 -c 'import sys,json; print(json.load(sys.stdin)["message"])' \
< "${API_BODY}" 2>/dev/null || head -c 500 "${API_BODY}")"
echo "Error: $1 failed (HTTP ${API_STATUS}): ${message}" >&2
if [[ "${API_STATUS}" == 401 || "${API_STATUS}" == 403 ]]; then
echo "Check GITEA_TOKEN: it must be valid and have the write:repository scope." >&2
fi
exit 1
}
echo ""
gitea_api GET "/releases/tags/${TAG}"
if [[ "${API_STATUS}" == 200 ]]; then
echo "==> Using existing Gitea release ${TAG}"
elif [[ "${API_STATUS}" == 404 ]]; then
echo "==> Creating Gitea release ${TAG} ..."
gitea_api POST "/releases" \
-H "Content-Type: application/json" \
-d "{\"tag_name\": \"${TAG}\", \"name\": \"${TAG}\"}"
[[ "${API_STATUS}" == 201 ]] || api_fail "Creating release ${TAG}"
else
api_fail "Looking up release ${TAG}"
fi
RELEASE_ID="$(python3 -c 'import sys,json; print(json.load(sys.stdin)["id"])' < "${API_BODY}")"
echo "==> Uploading assets (release id: ${RELEASE_ID}) ..." echo "==> Uploading assets (release id: ${RELEASE_ID}) ..."
for ARCHIVE in "${ARCHIVES[@]}"; do for ARCHIVE in "${ARCHIVES[@]}"; do
echo " Uploading ${ARCHIVE} ..." echo " Uploading ${ARCHIVE} ..."
curl -sf -X POST \ gitea_api POST "/releases/${RELEASE_ID}/assets" -F "attachment=@${ARCHIVE}"
-H "Authorization: Bearer ${GITEA_TOKEN}" \ [[ "${API_STATUS}" == 201 ]] || api_fail "Uploading ${ARCHIVE}"
-F "attachment=@${ARCHIVE}" \
"${GITEA_SERVER_URL}/api/v1/repos/${GITEA_REPOSITORY}/releases/${RELEASE_ID}/assets" > /dev/null
echo " Done." echo " Done."
done done
+33 -20
View File
@@ -18,20 +18,28 @@ $ErrorActionPreference = "Stop"
$ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path $ScriptDir = Split-Path -Parent $MyInvocation.MyCommand.Path
$RepoRoot = Split-Path -Parent $ScriptDir $RepoRoot = Split-Path -Parent $ScriptDir
# Load .env if present (existing env vars take precedence) # Load .env if present. The values are kept in a script-local table rather
# than written to the process environment: a .ps1 runs inside the caller's
# PowerShell process, so anything set there would outlive the script and
# shadow later edits to .env in the same session.
$DotEnv = @{}
$EnvFile = Join-Path $ScriptDir ".env" $EnvFile = Join-Path $ScriptDir ".env"
if (Test-Path $EnvFile) { if (Test-Path $EnvFile) {
Get-Content $EnvFile | ForEach-Object { Get-Content $EnvFile | ForEach-Object {
if ($_ -match '^\s*#' -or $_ -match '^\s*$') { return } if ($_ -match '^\s*#' -or $_ -notmatch '=') { return }
$parts = $_ -split '=', 2 $parts = $_ -split '=', 2
$key = $parts[0].Trim() $DotEnv[$parts[0].Trim()] = $parts[1].Trim()
$value = $parts[1].Trim()
if (-not [System.Environment]::GetEnvironmentVariable($key)) {
[System.Environment]::SetEnvironmentVariable($key, $value, "Process")
}
} }
} }
# Resolve a setting: an environment variable takes precedence over .env
function Get-Setting([string]$Name) {
$value = [System.Environment]::GetEnvironmentVariable($Name)
if ($value) { return $value }
if ($DotEnv.ContainsKey($Name)) { return $DotEnv[$Name] }
return $null
}
# Determine version # Determine version
if (-not $Version) { if (-not $Version) {
$cargoToml = Get-Content (Join-Path $RepoRoot "Cargo.toml") -Raw $cargoToml = Get-Content (Join-Path $RepoRoot "Cargo.toml") -Raw
@@ -46,19 +54,22 @@ if (-not $Version) {
$Tag = "v$Version" $Tag = "v$Version"
$Target = "x86_64-pc-windows-msvc" $Target = "x86_64-pc-windows-msvc"
Set-Location $RepoRoot
Write-Host "==> Building mdrs $Version for Windows ($Target)" Write-Host "==> Building mdrs $Version for Windows ($Target)"
rustup target add $Target rustup target add $Target
cargo build --release --target $Target cargo build --release --target $Target --manifest-path (Join-Path $RepoRoot "Cargo.toml")
$Archive = "mdrs-$Version-$Target.zip" $Archive = "mdrs-$Version-$Target.zip"
Compress-Archive -Force -Path "target\$Target\release\mdrs.exe" -DestinationPath $Archive $ArchivePath = Join-Path $RepoRoot $Archive
Compress-Archive -Force -Path (Join-Path $RepoRoot "target\$Target\release\mdrs.exe") -DestinationPath $ArchivePath
# Written alongside the archive so `mdrs selfupdate` can check what it fetched.
$Checksum = "$Archive.sha256"
$Hash = (Get-FileHash -Algorithm SHA256 -Path $ArchivePath).Hash.ToLower()
"$Hash $Archive" | Set-Content -NoNewline -Encoding ascii (Join-Path $RepoRoot $Checksum)
Write-Host " Created: $Archive" Write-Host " Created: $Archive"
# Upload to Gitea if token is provided # Upload to Gitea if token is provided
$GiteaToken = [System.Environment]::GetEnvironmentVariable("GITEA_TOKEN") $GiteaToken = Get-Setting "GITEA_TOKEN"
if (-not $GiteaToken) { if (-not $GiteaToken) {
Write-Host "" Write-Host ""
Write-Host "GITEA_TOKEN not set -- skipping upload." Write-Host "GITEA_TOKEN not set -- skipping upload."
@@ -66,8 +77,8 @@ if (-not $GiteaToken) {
exit 0 exit 0
} }
$ServerUrl = [System.Environment]::GetEnvironmentVariable("GITEA_SERVER_URL") $ServerUrl = Get-Setting "GITEA_SERVER_URL"
$Repository = [System.Environment]::GetEnvironmentVariable("GITEA_REPOSITORY") $Repository = Get-Setting "GITEA_REPOSITORY"
if (-not $ServerUrl) { Write-Error "GITEA_SERVER_URL is required for upload"; exit 1 } if (-not $ServerUrl) { Write-Error "GITEA_SERVER_URL is required for upload"; exit 1 }
if (-not $Repository) { Write-Error "GITEA_REPOSITORY is required for upload"; exit 1 } if (-not $Repository) { Write-Error "GITEA_REPOSITORY is required for upload"; exit 1 }
@@ -87,14 +98,16 @@ $Release = Invoke-RestMethod -Method Get -Uri "$ServerUrl/api/v1/repos/$Reposito
-Headers @{ Authorization = "Bearer $GiteaToken" } -Headers @{ Authorization = "Bearer $GiteaToken" }
$ReleaseId = $Release.id $ReleaseId = $Release.id
Write-Host "==> Uploading $Archive (release id: $ReleaseId) ..." foreach ($Name in @($Archive, $Checksum)) {
$ArchivePath = Join-Path $RepoRoot $Archive Write-Host "==> Uploading $Name (release id: $ReleaseId) ..."
& curl.exe -sf -X POST ` $AssetPath = Join-Path $RepoRoot $Name
& curl.exe -sf -X POST `
-H "Authorization: Bearer $GiteaToken" ` -H "Authorization: Bearer $GiteaToken" `
-F "attachment=@$ArchivePath" ` -F "attachment=@$AssetPath" `
"$ServerUrl/api/v1/repos/$Repository/releases/$ReleaseId/assets" | Out-Null "$ServerUrl/api/v1/repos/$Repository/releases/$ReleaseId/assets" | Out-Null
if ($LASTEXITCODE -ne 0) { Write-Error "Upload failed (exit code $LASTEXITCODE)"; exit 1 } if ($LASTEXITCODE -ne 0) { Write-Error "Upload failed (exit code $LASTEXITCODE)"; exit 1 }
Write-Host " Done." Write-Host " Done."
}
Write-Host "" Write-Host ""
Write-Host "==> Upload complete: $ServerUrl/$Repository/releases/tag/$Tag" Write-Host "==> Upload complete: $ServerUrl/$Repository/releases/tag/$Tag"
+2 -2
View File
@@ -1,6 +1,6 @@
use crate::connection::MDRSConnection; use crate::connection::MDRSConnection;
use crate::error::response_error;
use crate::models::doi::DoiResponse; use crate::models::doi::DoiResponse;
use anyhow::bail;
impl MDRSConnection { impl MDRSConnection {
/// Retrieve the folder associated with a DOI suffix ID (GET v3/doi/{id}/). /// Retrieve the folder associated with a DOI suffix ID (GET v3/doi/{id}/).
@@ -10,7 +10,7 @@ impl MDRSConnection {
pub async fn retrieve_doi(&self, id: &str) -> Result<DoiResponse, anyhow::Error> { pub async fn retrieve_doi(&self, id: &str) -> Result<DoiResponse, anyhow::Error> {
let resp = self.get(&format!("v3/doi/{}/", id)).await?; let resp = self.get(&format!("v3/doi/{}/", id)).await?;
if !resp.status().is_success() { if !resp.status().is_success() {
bail!("DOI lookup failed: {}", resp.status()); return Err(response_error("DOI lookup failed", resp).await);
} }
Ok(resp.json::<DoiResponse>().await?) Ok(resp.json::<DoiResponse>().await?)
} }
+368 -14
View File
@@ -1,8 +1,30 @@
use crate::connection::{ApiRequestLimiter, MDRSConnection}; use crate::connection::{ApiRequestLimiter, MDRSConnection};
use crate::error::response_error;
pub use crate::models::file::File; pub use crate::models::file::File;
use anyhow::bail;
use unicode_normalization::UnicodeNormalization; use unicode_normalization::UnicodeNormalization;
/// Read and write size for a streamed transfer. Large enough that the syscalls are not
/// what limits the transfer, small enough that ten of them in flight cost little.
const TRANSFER_CHUNK_BYTES: usize = 64 * 1024;
/// Name a scratch file beside the destination for a download in progress.
///
/// Beside it, so the move into place is a rename within one directory and cannot fail
/// half way. Unique, so two transfers heading for the same name cannot clear up after
/// each other.
fn partial_path(dest: &std::path::Path) -> std::path::PathBuf {
use std::sync::atomic::{AtomicU64, Ordering};
static COUNTER: AtomicU64 = AtomicU64::new(0);
let mut name = dest.file_name().unwrap_or_default().to_os_string();
name.push(format!(
".{}-{}.mdrspart",
std::process::id(),
COUNTER.fetch_add(1, Ordering::Relaxed)
));
dest.with_file_name(name)
}
#[derive(serde::Deserialize)] #[derive(serde::Deserialize)]
struct FileListResponse { struct FileListResponse {
pub next: Option<String>, pub next: Option<String>,
@@ -21,7 +43,7 @@ impl MDRSConnection {
]; ];
let resp = self.get_with_query("v3/files/", &params).await?; let resp = self.get_with_query("v3/files/", &params).await?;
if !resp.status().is_success() { if !resp.status().is_success() {
anyhow::bail!("List files failed: {}", resp.status()); return Err(response_error("List files failed", resp).await);
} }
let list: FileListResponse = resp.json().await?; let list: FileListResponse = resp.json().await?;
let has_next = list.next.is_some(); let has_next = list.next.is_some();
@@ -50,7 +72,7 @@ impl MDRSConnection {
let _permit = limiter.acquire().await?; let _permit = limiter.acquire().await?;
let resp = self.get_with_query("v3/files/", &params).await?; let resp = self.get_with_query("v3/files/", &params).await?;
if !resp.status().is_success() { if !resp.status().is_success() {
anyhow::bail!("List files failed: {}", resp.status()); return Err(response_error("List files failed", resp).await);
} }
let list: FileListResponse = resp.json().await?; let list: FileListResponse = resp.json().await?;
let has_next = list.next.is_some(); let has_next = list.next.is_some();
@@ -79,15 +101,51 @@ impl MDRSConnection {
.to_string_lossy() .to_string_lossy()
.nfc() .nfc()
.collect(); .collect();
let file_bytes = tokio::fs::read(file_path).await?; // The file is handed to the request as a stream rather than a buffer: a
let part = multipart::Part::bytes(file_bytes).file_name(file_name.clone()); // repository holds recordings far larger than the machine's memory, and ten of
let form = multipart::Form::new() // them may be in flight at once. The length travels with it so the request keeps
// a Content-Length and does not have to be sent chunked.
let build_form = || async {
let file = tokio::fs::File::open(file_path).await?;
let length = file.metadata().await?.len();
let stream = tokio_util::io::ReaderStream::with_capacity(file, TRANSFER_CHUNK_BYTES);
let part =
multipart::Part::stream_with_length(reqwest::Body::wrap_stream(stream), length)
.file_name(file_name.clone());
Ok::<_, anyhow::Error>(
multipart::Form::new()
.text("folder_id", folder_id.to_string()) .text("folder_id", folder_id.to_string())
.part("file", part); .part("file", part),
)
};
let _permit = limiter.acquire().await?; let _permit = limiter.acquire().await?;
let resp = self.post_multipart("v3/files/", form).await?; let sent_with = self.token.clone();
let resp = self
.post_multipart("v3/files/", build_form().await?)
.await?;
if resp.status() != reqwest::StatusCode::UNAUTHORIZED {
if !resp.status().is_success() { if !resp.status().is_success() {
bail!("Upload failed: {}", resp.status()); return Err(response_error("Upload failed", resp).await);
}
return Ok(());
}
// The body reached the server, but it may have waited to be served for longer
// than the access token it was sent with lived. Re-reading the file and sending
// it again is only worth it if the token has actually moved on: any other reason
// for the refusal would just cost a second full transfer to be told the same.
let retry_conn = self.connection_with_fresh_token_for_retry().await?;
if retry_conn.token == sent_with {
return Err(response_error("Upload failed", resp).await);
}
let resp = retry_conn
.post_multipart("v3/files/", build_form().await?)
.await?;
if resp.status() == reqwest::StatusCode::UNAUTHORIZED {
// Refused twice, the second time with a token that was current when it left.
bail!(crate::connection::SERVER_BUSY_MESSAGE);
}
if !resp.status().is_success() {
return Err(response_error("Upload failed", resp).await);
} }
Ok(()) Ok(())
} }
@@ -99,14 +157,310 @@ impl MDRSConnection {
dest: &str, dest: &str,
limiter: &ApiRequestLimiter, limiter: &ApiRequestLimiter,
) -> Result<(), anyhow::Error> { ) -> Result<(), anyhow::Error> {
use futures::StreamExt;
use tokio::io::AsyncWriteExt;
let _permit = limiter.acquire().await?; let _permit = limiter.acquire().await?;
let dest_path = std::path::Path::new(dest);
// Checked before anything is fetched. The finished file is moved into place, and
// a rename would replace a destination the mode says is protected, which is not
// what this client or the Python one has ever done.
if dest_path.exists() {
tokio::fs::OpenOptions::new()
.write(true)
.open(dest_path)
.await
.map_err(|e| anyhow::anyhow!("Cannot write `{}`: {}", dest, e))?;
}
let resp = self.get_url(url).await?; let resp = self.get_url(url).await?;
if !resp.status().is_success() { if !resp.status().is_success() {
bail!("Download failed: {}", resp.status()); return Err(response_error("Download failed", resp).await);
}
// Written as it arrives, into a scratch file that is moved into place only once
// the whole body has landed. Holding the body in memory first would cost the size
// of the file, times however many transfers are running; writing straight to the
// destination would destroy whatever is already there the moment the transfer
// starts, and leave a truncated file behind if it does not finish.
let part_path = partial_path(dest_path);
let result = async {
let mut file = tokio::io::BufWriter::with_capacity(
TRANSFER_CHUNK_BYTES,
tokio::fs::File::create(&part_path).await?,
);
let mut stream = resp.bytes_stream();
while let Some(chunk) = stream.next().await {
file.write_all(&chunk?).await?;
}
file.flush().await?;
Ok::<(), anyhow::Error>(())
}
.await;
match result {
Ok(()) => Ok(tokio::fs::rename(&part_path, dest_path).await?),
Err(err) => {
// Only the scratch file goes. Anything already at the destination was not
// written by this transfer and is not this transfer's to remove.
let _ = tokio::fs::remove_file(&part_path).await;
Err(err)
}
} }
let bytes = resp.bytes().await?; }
drop(_permit); }
tokio::fs::write(dest, &bytes).await?;
Ok(()) #[cfg(test)]
mod transfer_tests {
use super::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
/// Read one HTTP request in full, using its Content-Length to know where it ends.
async fn read_request(stream: &mut tokio::net::TcpStream) -> (String, Vec<u8>) {
let mut buf = Vec::new();
let mut chunk = [0u8; 8192];
let header_end = loop {
let n = stream.read(&mut chunk).await.unwrap();
buf.extend_from_slice(&chunk[..n]);
if let Some(pos) = buf.windows(4).position(|w| w == b"\r\n\r\n") {
break pos + 4;
}
assert!(n > 0, "connection closed before the headers ended");
};
let head = String::from_utf8_lossy(&buf[..header_end]).to_string();
let length: usize = head
.lines()
.find_map(|l| {
l.to_ascii_lowercase()
.strip_prefix("content-length:")
.map(|v| v.trim().to_string())
})
.expect("request must carry a Content-Length")
.parse()
.unwrap();
while buf.len() < header_end + length {
let n = stream.read(&mut chunk).await.unwrap();
assert!(n > 0, "connection closed before the body ended");
buf.extend_from_slice(&chunk[..n]);
}
(head, buf[header_end..].to_vec())
}
/// The file goes out as a stream, and the request still declares its length, so the
/// server is not asked to accept a chunked upload.
#[tokio::test]
async fn an_upload_streams_the_file_with_a_declared_length() {
let payload: Vec<u8> = (0..300_000u32).map(|i| (i % 251) as u8).collect();
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("recording.dat");
std::fs::write(&path, &payload).unwrap();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let expected = payload.clone();
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let (head, body) = read_request(&mut stream).await;
stream
.write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 15\r\nconnection: close\r\n\r\n{\"id\":\"new\"}")
.await
.unwrap();
(head, body, expected)
});
let conn = MDRSConnection::new(&format!("http://{addr}"));
let limiter = ApiRequestLimiter::new(1);
conn.upload_file_limited("folder-1", path.to_str().unwrap(), &limiter)
.await
.unwrap();
let (head, body, expected) = server.await.unwrap();
assert!(
!head
.to_ascii_lowercase()
.contains("transfer-encoding: chunked"),
"the upload must not be chunked:\n{head}"
);
assert!(
body.windows(expected.len()).any(|w| w == expected),
"the file bytes must reach the server"
);
assert!(
body.windows(8).any(|w| w == b"folder-1"),
"the folder id must reach the server"
);
assert!(
String::from_utf8_lossy(&body).contains("recording.dat"),
"the file name must reach the server"
);
}
/// The body is written to disk as it arrives rather than being held whole.
#[tokio::test]
async fn a_download_writes_what_the_server_sent() {
let payload: Vec<u8> = (0..300_000u32).map(|i| (i % 241) as u8).collect();
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let served = payload.clone();
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut chunk = [0u8; 4096];
let _ = stream.read(&mut chunk).await.unwrap();
let head = format!(
"HTTP/1.1 200 OK\r\ncontent-length: {}\r\nconnection: close\r\n\r\n",
served.len()
);
stream.write_all(head.as_bytes()).await.unwrap();
stream.write_all(&served).await.unwrap();
});
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("out.dat");
let conn = MDRSConnection::new(&format!("http://{addr}"));
let limiter = ApiRequestLimiter::new(1);
conn.download_file_limited(
&format!("http://{addr}/v3/files/1/download/"),
dest.to_str().unwrap(),
&limiter,
)
.await
.unwrap();
server.await.unwrap();
assert_eq!(std::fs::read(&dest).unwrap(), payload);
}
/// A transfer that dies part way must not take the copy already on disk with it.
#[tokio::test]
async fn an_interrupted_download_leaves_the_existing_file_intact() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut chunk = [0u8; 4096];
let _ = stream.read(&mut chunk).await.unwrap();
// Promises 300000 bytes, sends 1000, then hangs up.
stream
.write_all(
b"HTTP/1.1 200 OK\r\ncontent-length: 300000\r\nconnection: close\r\n\r\n",
)
.await
.unwrap();
stream.write_all(&vec![b'x'; 1000]).await.unwrap();
stream.shutdown().await.unwrap();
});
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("existing.dat");
std::fs::write(&dest, b"the copy already here").unwrap();
let conn = MDRSConnection::new(&format!("http://{addr}"));
let limiter = ApiRequestLimiter::new(1);
let outcome = conn
.download_file_limited(
&format!("http://{addr}/v3/files/1/download/"),
dest.to_str().unwrap(),
&limiter,
)
.await;
server.await.unwrap();
assert!(outcome.is_err(), "a truncated body is a failed download");
assert_eq!(std::fs::read(&dest).unwrap(), b"the copy already here");
let leftovers: Vec<_> = std::fs::read_dir(dir.path())
.unwrap()
.map(|e| e.unwrap().file_name().to_string_lossy().to_string())
.filter(|name| name != "existing.dat")
.collect();
assert!(
leftovers.is_empty(),
"no scratch file may be left: {leftovers:?}"
);
}
/// A destination this call could not even open is not a file it may delete.
#[cfg(unix)]
#[tokio::test]
async fn a_download_that_cannot_be_written_leaves_the_existing_file_intact() {
use std::os::unix::fs::PermissionsExt;
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut chunk = [0u8; 4096];
let _ = stream.read(&mut chunk).await.unwrap();
stream
.write_all(b"HTTP/1.1 200 OK\r\ncontent-length: 2\r\nconnection: close\r\n\r\nhi")
.await
.unwrap();
});
// A writable directory holding a file this process may not open for writing.
// That is what separates "could not write it" from "may delete it": unlink needs
// the directory, not the file.
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("precious.dat");
std::fs::write(&dest, b"do not touch").unwrap();
let mut perms = std::fs::metadata(&dest).unwrap().permissions();
perms.set_mode(0o444);
std::fs::set_permissions(&dest, perms).unwrap();
if std::fs::OpenOptions::new().write(true).open(&dest).is_ok() {
// Running with rights that ignore the mode, so there is nothing to observe.
return;
}
let conn = MDRSConnection::new(&format!("http://{addr}"));
let limiter = ApiRequestLimiter::new(1);
let outcome = conn
.download_file_limited(
&format!("http://{addr}/v3/files/1/download/"),
dest.to_str().unwrap(),
&limiter,
)
.await;
// Nothing was fetched, so the stub is still waiting to be connected to.
server.abort();
let message = outcome.unwrap_err().to_string();
assert!(
message.starts_with("Cannot write "),
"the refusal must name the problem, got: {message}"
);
assert_eq!(std::fs::read(&dest).unwrap(), b"do not touch");
}
/// A refused download leaves nothing behind that a later run could mistake for the file.
#[tokio::test]
async fn a_refused_download_leaves_no_file() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut chunk = [0u8; 4096];
let _ = stream.read(&mut chunk).await.unwrap();
let body = r#"{"type":"client_error","errors":[{"code":"permission_denied","detail":"Access is denied.","attr":null}]}"#;
let head = format!(
"HTTP/1.1 403 Forbidden\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
body.len(),
body
);
stream.write_all(head.as_bytes()).await.unwrap();
});
let dir = tempfile::tempdir().unwrap();
let dest = dir.path().join("out.dat");
let conn = MDRSConnection::new(&format!("http://{addr}"));
let limiter = ApiRequestLimiter::new(1);
let err = conn
.download_file_limited(
&format!("http://{addr}/v3/files/1/download/"),
dest.to_str().unwrap(),
&limiter,
)
.await
.unwrap_err();
server.await.unwrap();
assert_eq!(err.to_string(), "Download failed: Access is denied.");
assert!(!dest.exists());
} }
} }
+72 -9
View File
@@ -1,7 +1,23 @@
use crate::connection::{ApiRequestLimiter, MDRSConnection}; use crate::connection::{ApiRequestLimiter, MDRSConnection};
use crate::error::{FolderLockedError, response_error};
pub use crate::models::folder::{FolderDetail, FolderSimple}; pub use crate::models::folder::{FolderDetail, FolderSimple};
use anyhow::{anyhow, bail}; use anyhow::{anyhow, bail};
fn parse_folder_response(data: serde_json::Value, id: &str) -> Result<FolderDetail, anyhow::Error> {
// Without its password, a locked folder comes back with 200 and only its listing
// fields. It is not a malformed full folder: the caller must authenticate and retry.
if data.get("lock").and_then(serde_json::Value::as_bool) == Some(true)
&& data.get("sub_folders").is_none()
{
let name = data
.get("name")
.and_then(serde_json::Value::as_str)
.unwrap_or(id);
return Err(FolderLockedError::new(name).into());
}
Ok(serde_json::from_value(data)?)
}
impl MDRSConnection { impl MDRSConnection {
/// List folders matching the given path under a laboratory (GET v3/folders/?path=...&laboratory_id=...) /// List folders matching the given path under a laboratory (GET v3/folders/?path=...&laboratory_id=...)
pub async fn list_folders_by_path( pub async fn list_folders_by_path(
@@ -15,7 +31,7 @@ impl MDRSConnection {
]; ];
let resp = self.get_with_query("v3/folders/", &params).await?; let resp = self.get_with_query("v3/folders/", &params).await?;
if !resp.status().is_success() { if !resp.status().is_success() {
bail!("List folders failed: {}", resp.status()); return Err(response_error("List folders failed", resp).await);
} }
Ok(resp.json::<Vec<FolderSimple>>().await?) Ok(resp.json::<Vec<FolderSimple>>().await?)
} }
@@ -34,7 +50,7 @@ impl MDRSConnection {
let _permit = limiter.acquire().await?; let _permit = limiter.acquire().await?;
let resp = self.get_with_query("v3/folders/", &params).await?; let resp = self.get_with_query("v3/folders/", &params).await?;
if !resp.status().is_success() { if !resp.status().is_success() {
bail!("List folders failed: {}", resp.status()); return Err(response_error("List folders failed", resp).await);
} }
Ok(resp.json::<Vec<FolderSimple>>().await?) Ok(resp.json::<Vec<FolderSimple>>().await?)
} }
@@ -43,9 +59,9 @@ impl MDRSConnection {
pub async fn retrieve_folder(&self, id: &str) -> Result<FolderDetail, anyhow::Error> { pub async fn retrieve_folder(&self, id: &str) -> Result<FolderDetail, anyhow::Error> {
let resp = self.get(&format!("v3/folders/{}/", id)).await?; let resp = self.get(&format!("v3/folders/{}/", id)).await?;
if !resp.status().is_success() { if !resp.status().is_success() {
bail!("Retrieve folder failed: {}", resp.status()); return Err(response_error("Retrieve folder failed", resp).await);
} }
Ok(resp.json::<FolderDetail>().await?) parse_folder_response(resp.json().await?, id)
} }
/// Retrieve folder details while consuming the shared API concurrency budget. /// Retrieve folder details while consuming the shared API concurrency budget.
@@ -57,9 +73,9 @@ impl MDRSConnection {
let _permit = limiter.acquire().await?; let _permit = limiter.acquire().await?;
let resp = self.get(&format!("v3/folders/{}/", id)).await?; let resp = self.get(&format!("v3/folders/{}/", id)).await?;
if !resp.status().is_success() { if !resp.status().is_success() {
bail!("Retrieve folder failed: {}", resp.status()); return Err(response_error("Retrieve folder failed", resp).await);
} }
Ok(resp.json::<FolderDetail>().await?) parse_folder_response(resp.json().await?, id)
} }
/// Create a new folder under `parent_id` (POST v3/folders/). /// Create a new folder under `parent_id` (POST v3/folders/).
@@ -94,7 +110,11 @@ impl MDRSConnection {
let _permit = limiter.acquire().await?; let _permit = limiter.acquire().await?;
let resp = self.post_json("v3/folders/", &body).await?; let resp = self.post_json("v3/folders/", &body).await?;
if !resp.status().is_success() { if !resp.status().is_success() {
bail!("Failed to create remote folder: {}", folder_name); return Err(response_error(
&format!("Failed to create remote folder `{}`", folder_name),
resp,
)
.await);
} }
let json: serde_json::Value = resp.json().await?; let json: serde_json::Value = resp.json().await?;
json["id"] json["id"]
@@ -116,7 +136,7 @@ impl MDRSConnection {
bail!("Password is incorrect."); bail!("Password is incorrect.");
} }
if !resp.status().is_success() { if !resp.status().is_success() {
bail!("Folder auth failed: {}", resp.status()); return Err(response_error("Folder auth failed", resp).await);
} }
Ok(()) Ok(())
} }
@@ -140,8 +160,51 @@ impl MDRSConnection {
bail!("Password is incorrect."); bail!("Password is incorrect.");
} }
if !resp.status().is_success() { if !resp.status().is_success() {
bail!("Folder auth failed: {}", resp.status()); return Err(response_error("Folder auth failed", resp).await);
} }
Ok(()) Ok(())
} }
} }
#[cfg(test)]
mod tests {
use super::*;
use serde_json::json;
fn short_locked_record() -> serde_json::Value {
json!({
"id": "f1",
"pid": null,
"name": "root",
"access_level": 4,
"lock": true,
"size": 0,
"laboratory_id": 1,
"description": "",
"created_at": "2026-01-01T00:00:00+09:00",
"updated_at": "2026-01-01T00:00:00+09:00",
"restrict_opened_at": null,
"application": {"id": 0, "status": 0}
})
}
#[test]
fn short_record_of_a_locked_folder_is_reported_as_locked() {
let err = parse_folder_response(short_locked_record(), "f1").unwrap_err();
assert!(err.downcast_ref::<FolderLockedError>().is_some());
assert_eq!(err.to_string(), "Folder `root` is locked.");
}
#[test]
fn full_record_of_a_locked_folder_still_deserializes() {
let mut data = short_locked_record();
data["metadata"] = json!([]);
data["sub_folders"] = json!([]);
data["path"] = json!("/root/");
let folder = parse_folder_response(data, "f1").unwrap();
assert_eq!(folder.path, "/root/");
assert!(folder.lock);
}
}
+2 -1
View File
@@ -1,4 +1,5 @@
use crate::connection::MDRSConnection; use crate::connection::MDRSConnection;
use crate::error::response_error;
use crate::models::laboratory::{Laboratories, Laboratory}; use crate::models::laboratory::{Laboratories, Laboratory};
use serde::Deserialize; use serde::Deserialize;
@@ -12,7 +13,7 @@ impl MDRSConnection {
pub async fn list_laboratories(&self) -> Result<Laboratories, anyhow::Error> { pub async fn list_laboratories(&self) -> Result<Laboratories, anyhow::Error> {
let resp = self.get("v3/laboratories/").await?; let resp = self.get("v3/laboratories/").await?;
if !resp.status().is_success() { if !resp.status().is_success() {
anyhow::bail!("List laboratories failed: {}", resp.status()); return Err(response_error("List laboratories failed", resp).await);
} }
// The API may return a paginated object or a direct array // The API may return a paginated object or a direct array
let text = resp.text().await?; let text = resp.text().await?;
+186 -9
View File
@@ -1,7 +1,16 @@
use crate::connection::MDRSConnection; use crate::connection::MDRSConnection;
use crate::error::response_error;
use crate::models::folder::ProjectNames;
use crate::models::user::User as ModelUser; use crate::models::user::User as ModelUser;
use anyhow::bail;
use serde::Deserialize; use serde::Deserialize;
use std::collections::BTreeMap;
use std::time::Duration;
/// Bound the refresh on its own: the caller holds a lock that spans processes while this
/// runs, so a provider that accepts the connection and then goes quiet would stall every
/// other request on this machine rather than just this one. Uploads are served by a
/// separate instance, so this one is not queued behind them and has no reason to be slow.
const TOKEN_REFRESH_TIMEOUT: Duration = Duration::from_secs(30);
/// Full API response shape from GET v3/users/current/ /// Full API response shape from GET v3/users/current/
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
@@ -10,6 +19,8 @@ struct UsersApiCurrentResponse {
username: String, username: String,
laboratories: Vec<UsersCurrentResponseLaboratory>, laboratories: Vec<UsersCurrentResponseLaboratory>,
is_reviewer: bool, is_reviewer: bool,
#[serde(default)]
projects: Vec<UsersCurrentResponseProject>,
} }
#[derive(Debug, Deserialize)] #[derive(Debug, Deserialize)]
@@ -17,19 +28,39 @@ struct UsersCurrentResponseLaboratory {
id: u32, id: u32,
} }
#[derive(Debug, Deserialize)]
struct UsersCurrentResponseProject {
name: Option<String>,
bit_position: u32,
}
#[derive(Deserialize)] #[derive(Deserialize)]
struct TokenRefreshResponse { struct TokenRefreshResponse {
access: String, access: String,
/// Present when the provider rotates refresh tokens, absent when it does not,
/// so the caller keeps the token it already holds if nothing new arrives.
#[serde(default)]
refresh: Option<String>,
}
/// The token pair a refresh yields.
pub struct RefreshedToken {
pub access: String,
pub refresh: Option<String>,
} }
impl MDRSConnection { impl MDRSConnection {
/// Fetch current user and return the slim 4-field model matching the Python cache format. async fn current_user_response(&self) -> Result<UsersApiCurrentResponse, anyhow::Error> {
pub async fn get_current_user(&self) -> Result<ModelUser, anyhow::Error> {
let resp = self.get("v3/users/current/").await?; let resp = self.get("v3/users/current/").await?;
if !resp.status().is_success() { if !resp.status().is_success() {
bail!("Get current user failed: {}", resp.status()); return Err(response_error("Get current user failed", resp).await);
} }
let obj = resp.json::<UsersApiCurrentResponse>().await?; Ok(resp.json::<UsersApiCurrentResponse>().await?)
}
/// Fetch current user and return the slim 4-field model matching the Python cache format.
pub async fn get_current_user(&self) -> Result<ModelUser, anyhow::Error> {
let obj = self.current_user_response().await?;
let laboratory_ids = obj.laboratories.into_iter().map(|l| l.id).collect(); let laboratory_ids = obj.laboratories.into_iter().map(|l| l.id).collect();
Ok(ModelUser { Ok(ModelUser {
id: obj.id, id: obj.id,
@@ -39,20 +70,166 @@ impl MDRSConnection {
}) })
} }
/// Fetch project names by access-level bit position. Project names are visible only
/// to their members, so an anonymous connection needs no request and returns none.
pub async fn get_project_names(&self) -> Result<ProjectNames, anyhow::Error> {
if self.token.is_none() {
return Ok(ProjectNames::new());
}
let obj = self.current_user_response().await?;
let mut names: BTreeMap<u32, Vec<String>> = BTreeMap::new();
for project in obj.projects {
if let Some(name) = project.name.filter(|name| !name.is_empty()) {
names.entry(project.bit_position).or_default().push(name);
}
}
Ok(names
.into_iter()
.map(|(bit, mut names)| {
names.sort();
(bit, names.join(", "))
})
.collect())
}
/// Refresh the access token using the refresh token. /// Refresh the access token using the refresh token.
/// POST v3/users/token/refresh/ {refresh: ...} -> {access: new_access} /// POST v3/users/token/refresh/ {refresh: ...} -> {access, refresh?}
pub async fn token_refresh(&self, refresh_token: &str) -> Result<String, anyhow::Error> { ///
/// A rotating provider answers with a new refresh token and stops honouring the one
/// that was sent, so both halves of the reply have to be kept.
pub async fn token_refresh(
&self,
refresh_token: &str,
) -> Result<RefreshedToken, anyhow::Error> {
let body = serde_json::json!({ "refresh": refresh_token }); let body = serde_json::json!({ "refresh": refresh_token });
let resp = self let resp = self
.client .client
.post(self.build_url("v3/users/token/refresh/")) .post(self.build_url("v3/users/token/refresh/"))
.json(&body) .json(&body)
.timeout(TOKEN_REFRESH_TIMEOUT)
.send() .send()
.await?; .await?;
if !resp.status().is_success() { if !resp.status().is_success() {
bail!("Token refresh failed: {}", resp.status()); return Err(response_error("Token refresh failed", resp).await);
} }
let r: TokenRefreshResponse = resp.json().await?; let r: TokenRefreshResponse = resp.json().await?;
Ok(r.access) Ok(RefreshedToken {
access: r.access,
refresh: r.refresh,
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
async fn refresh_against_stub(body: &'static str) -> RefreshedToken {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut buf = [0u8; 4096];
let n = stream.read(&mut buf).await.unwrap();
let req = String::from_utf8_lossy(&buf[..n]);
assert!(req.starts_with("POST /v3/users/token/refresh/ HTTP/1.1"));
assert!(req.contains("\"refresh\":\"old-refresh\""));
let response = format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
body.len(),
body
);
stream.write_all(response.as_bytes()).await.unwrap();
});
let conn = MDRSConnection::new(&format!("http://{addr}"));
let refreshed = conn.token_refresh("old-refresh").await.unwrap();
server.await.unwrap();
refreshed
}
/// A rotating provider stops honouring the token that was sent, so the reply's
/// refresh token has to reach the caller rather than being dropped.
#[tokio::test]
async fn token_refresh_returns_the_rotated_refresh_token() {
let refreshed =
refresh_against_stub(r#"{"access":"new-access","refresh":"new-refresh"}"#).await;
assert_eq!(refreshed.access, "new-access");
assert_eq!(refreshed.refresh.as_deref(), Some("new-refresh"));
}
/// A provider that does not rotate answers with the access token alone, and the
/// caller keeps the refresh token it already holds.
#[tokio::test]
async fn token_refresh_reports_no_rotation_when_the_reply_omits_it() {
let refreshed = refresh_against_stub(r#"{"access":"new-access"}"#).await;
assert_eq!(refreshed.access, "new-access");
assert_eq!(refreshed.refresh, None);
}
async fn project_names_against_stub(projects: Option<&str>) -> ProjectNames {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let projects = projects
.map(|projects| format!(r#","projects":{projects}"#))
.unwrap_or_default();
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut buf = [0u8; 4096];
let n = stream.read(&mut buf).await.unwrap();
let req = String::from_utf8_lossy(&buf[..n]);
assert!(req.starts_with("GET /v3/users/current/ HTTP/1.1"));
let body = format!(
r#"{{"id":1,"username":"user","laboratories":[],"is_reviewer":false{projects}}}"#
);
let response = format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
body.len(),
body
);
stream.write_all(response.as_bytes()).await.unwrap();
});
let conn = MDRSConnection::new(&format!("http://{addr}")).with_token("token".to_string());
let names = conn.get_project_names().await.unwrap();
server.await.unwrap();
names
}
#[tokio::test]
async fn project_names_combines_all_names_at_a_shared_bit_position() {
let names = project_names_against_stub(Some(
r#"[
{"id":1,"name":"Brain/MINDS 2.0","bit_position":0},
{"id":2,"name":"B","bit_position":3},
{"id":3,"name":"A","bit_position":3},
{"id":4,"name":null,"bit_position":5},
{"id":5,"name":"","bit_position":5}
]"#,
))
.await;
assert_eq!(names.get(&0).map(String::as_str), Some("Brain/MINDS 2.0"));
assert_eq!(names.get(&3).map(String::as_str), Some("A, B"));
assert!(!names.contains_key(&5));
}
#[tokio::test]
async fn project_names_is_empty_when_the_server_has_no_projects_field() {
assert!(project_names_against_stub(None).await.is_empty());
}
#[tokio::test]
async fn anonymous_project_names_require_no_request() {
let conn = MDRSConnection::new("http://127.0.0.1:9");
assert!(conn.get_project_names().await.unwrap().is_empty());
} }
} }
+72 -8
View File
@@ -139,14 +139,32 @@ fn write_cache_file(cache_path: &Path, cache: &Cache) -> Result<(), anyhow::Erro
} }
fn parse_cache(remote: &str, data: &str) -> Result<Cache, anyhow::Error> { fn parse_cache(remote: &str, data: &str) -> Result<Cache, anyhow::Error> {
serde_json::from_str::<Cache>(data).map_err(|e| { let cache = serde_json::from_str::<Cache>(data).map_err(|e| {
anyhow!( anyhow!(
"Cache for `{}` is invalid or outdated ({}). Run `mdrs login {}` to refresh it.", "Cache for `{}` is invalid or outdated ({}). Run `mdrs login {}` to refresh it.",
remote, remote,
e, e,
remote remote
) )
}) })?;
// The digest is what says the file is still the one this client wrote. The Python
// client checks it on every read and the two share the file, so a cache one of them
// would refuse must not be honoured by the other.
let expected = compute_digest(
cache.user.as_ref(),
&cache.token.access,
&cache.token.refresh,
&cache.laboratories,
);
if cache.digest != expected {
bail!(
"Cache for `{}` has been altered or was written by an incompatible version. \
Run `mdrs login {}` to refresh it.",
remote,
remote
);
}
Ok(cache)
} }
fn load_cache_from_dir(remote: &str, config_dir: &Path) -> Result<Cache, anyhow::Error> { fn load_cache_from_dir(remote: &str, config_dir: &Path) -> Result<Cache, anyhow::Error> {
@@ -213,7 +231,11 @@ fn load_cache_if_present_from_dir(
}; };
let cache = match parse_cache(remote, &data) { let cache = match parse_cache(remote, &data) {
Ok(cache) => cache, Ok(cache) => cache,
Err(_) => { Err(e) => {
// Said out loud before the credentials go. The alternative is a command that
// quietly carries on anonymously and fails later for a reason that looks
// unrelated to the cache it just threw away.
eprintln!("{e}");
remove_cache_in_dir(remote, config_dir)?; remove_cache_in_dir(remote, config_dir)?;
return Ok(None); return Ok(None);
} }
@@ -290,6 +312,9 @@ pub async fn load_cache_with_token_refresh(remote: &str) -> Result<Cache, anyhow
let lock_file = fs::OpenOptions::new() let lock_file = fs::OpenOptions::new()
.write(true) .write(true)
.create(true) .create(true)
// Nothing is ever written into it: the file exists only to be flocked, and
// truncating it would touch a file other processes are holding open.
.truncate(false)
.open(&lock_path)?; .open(&lock_path)?;
lock_file.lock_exclusive()?; lock_file.lock_exclusive()?;
@@ -331,6 +356,9 @@ async fn load_cache_with_token_refresh_optional_from_dir(
let lock_file = fs::OpenOptions::new() let lock_file = fs::OpenOptions::new()
.write(true) .write(true)
.create(true) .create(true)
// Nothing is ever written into it: the file exists only to be flocked, and
// truncating it would touch a file other processes are holding open.
.truncate(false)
.open(&lock_path)?; .open(&lock_path)?;
lock_file.lock_exclusive()?; lock_file.lock_exclusive()?;
@@ -387,10 +415,13 @@ async fn refresh_and_persist_in_dir(
.ok_or_else(|| anyhow!("Remote `{}` is not configured.", remote))?; .ok_or_else(|| anyhow!("Remote `{}` is not configured.", remote))?;
let conn = MDRSConnection::new(&url); let conn = MDRSConnection::new(&url);
let new_access = conn.token_refresh(&cache.token.refresh).await?; let refreshed = conn.token_refresh(&cache.token.refresh).await?;
let mut updated_cache = cache.clone(); let mut updated_cache = cache.clone();
updated_cache.token.access = new_access; updated_cache.token.access = refreshed.access;
if let Some(refresh) = refreshed.refresh {
updated_cache.token.refresh = refresh;
}
updated_cache.digest = compute_digest( updated_cache.digest = compute_digest(
updated_cache.user.as_ref(), updated_cache.user.as_ref(),
&updated_cache.token.access, &updated_cache.token.access,
@@ -440,7 +471,7 @@ mod tests {
use tempfile::tempdir; use tempfile::tempdir;
fn sample_cache(username: &str) -> Cache { fn sample_cache(username: &str) -> Cache {
Cache { let mut cache = Cache {
user: Some(CacheUser { user: Some(CacheUser {
id: 1, id: 1,
username: username.to_string(), username: username.to_string(),
@@ -459,8 +490,15 @@ mod tests {
full_name: "Laboratory".to_string(), full_name: "Laboratory".to_string(),
}], }],
}, },
digest: format!("digest-{username}"), digest: String::new(),
} };
cache.digest = compute_digest(
cache.user.as_ref(),
&cache.token.access,
&cache.token.refresh,
&cache.laboratories,
);
cache
} }
fn remote_name(prefix: &str, config_dir: &Path) -> String { fn remote_name(prefix: &str, config_dir: &Path) -> String {
@@ -572,6 +610,25 @@ mod tests {
assert!(loaded.is_none()); assert!(loaded.is_none());
} }
/// A cache whose contents no longer match its digest is not a session to act on.
#[test]
fn load_cache_refuses_a_tampered_cache() {
let dir = tempdir().unwrap();
let remote = remote_name("tampered", dir.path());
let mut cache = sample_cache("alice");
persist_cache_in_dir(&remote, dir.path(), &cache).unwrap();
// Someone edits the stored token but leaves the digest as it was.
cache.token.access = "someone-elses-access".to_string();
let cache_path = cache_file_path_in(dir.path(), &remote);
fs::write(&cache_path, serde_json::to_vec_pretty(&cache).unwrap()).unwrap();
invalidate_cached_entry(dir.path(), &remote);
let err = load_cache_from_dir(&remote, dir.path()).unwrap_err();
assert!(err.to_string().contains("has been altered"));
}
#[test] #[test]
fn load_cache_if_present_clears_invalid_cache() { fn load_cache_if_present_clears_invalid_cache() {
let dir = tempdir().unwrap(); let dir = tempdir().unwrap();
@@ -594,6 +651,13 @@ mod tests {
let mut cache = sample_cache("alice"); let mut cache = sample_cache("alice");
cache.token.access = make_jwt_with_exp(0); cache.token.access = make_jwt_with_exp(0);
cache.token.refresh = make_jwt_with_exp(0); cache.token.refresh = make_jwt_with_exp(0);
// Re-stamped, so this exercises the expired session rather than the digest check.
cache.digest = compute_digest(
cache.user.as_ref(),
&cache.token.access,
&cache.token.refresh,
&cache.laboratories,
);
persist_cache_in_dir(&remote, dir.path(), &cache).unwrap(); persist_cache_in_dir(&remote, dir.path(), &cache).unwrap();
let loaded = load_cache_with_token_refresh_optional_from_dir(&remote, dir.path()) let loaded = load_cache_with_token_refresh_optional_from_dir(&remote, dir.path())
+5 -3
View File
@@ -41,7 +41,7 @@ pub enum Commands {
skip_if_exists: bool, skip_if_exists: bool,
#[arg(short = 'p', long)] #[arg(short = 'p', long)]
password: Option<String>, password: Option<String>,
#[arg(long)] #[arg(short = 'e', long)]
exclude: Vec<String>, exclude: Vec<String>,
remote_path: String, remote_path: String,
local_path: String, local_path: String,
@@ -64,11 +64,13 @@ pub enum Commands {
remote: String, remote: String,
}, },
Chacl { Chacl {
/// Access level key: private, public, pw_open, cbs_open, 5kikan_open, /// Access level: private, pw_open, cbs_open, project<n>_open,
/// cbs_or_pw_open, 5kikan_or_pw_open, storage /// or several open levels joined by `_or_` (e.g. cbs_or_pw_open).
/// An invalid level lists the projects you belong to.
access_level_key: String, access_level_key: String,
#[arg(short, long)] #[arg(short, long)]
recursive: bool, recursive: bool,
/// Password to set when the access level includes `pw` (e.g. pw_open)
#[arg(short = 'p', long)] #[arg(short = 'p', long)]
password: Option<String>, password: Option<String>,
remote_path: String, remote_path: String,
+89 -14
View File
@@ -1,29 +1,33 @@
use crate::cache::{create_authenticated_conn, load_cache_with_token_refresh}; use crate::cache::{
use crate::commands::shared::{find_folder, find_lab_in_cache, parse_remote_path}; create_authenticated_conn, create_readonly_conn, load_cache_with_token_refresh,
};
use crate::commands::shared::{find_folder, find_laboratory, parse_remote_path};
use crate::error::response_error;
use crate::models::folder::{
PUBLIC_ACCESS_LEVEL, ProjectNames, STORAGE_ACCESS_LEVEL, access_level_from_key,
};
use anyhow::bail; use anyhow::bail;
const INVALID_ACCESS_LEVEL_MESSAGE: &str = "Invalid `access_level` parameter. must be `private`, `pw_open`, `cbs_open`, `project<n>_open` or open levels joined by `_or_` (e.g. `cbs_or_pw_open`).";
pub async fn chacl( pub async fn chacl(
remote_path: &str, remote_path: &str,
access_level_key: &str, access_level_key: &str,
recursive: bool, recursive: bool,
password: Option<&str>, password: Option<&str>,
) -> Result<(), anyhow::Error> { ) -> Result<(), anyhow::Error> {
let access_level_id: u32 = match access_level_key { let Some(access_level_id) = access_level_from_key(access_level_key) else {
"private" => 0x0001, bail!("{}", invalid_access_level_message(remote_path).await);
"public" => 0x0002,
"pw_open" => 0x0004,
"cbs_open" => 0x0100,
"5kikan_open" => 0x0200,
"cbs_or_pw_open" => 0x0104,
"5kikan_or_pw_open" => 0x0204,
"storage" => 0x0000,
_ => bail!("Unknown access level key: '{}'", access_level_key),
}; };
if access_level_id == STORAGE_ACCESS_LEVEL || access_level_id == PUBLIC_ACCESS_LEVEL {
// The server refuses both; report the invalid operation before making a request.
bail!("`{access_level_key}` cannot be set as an access level.");
}
let (remote, labname, folder_path) = parse_remote_path(remote_path)?; let (remote, labname, folder_path) = parse_remote_path(remote_path)?;
let cache = load_cache_with_token_refresh(&remote).await?; let cache = load_cache_with_token_refresh(&remote).await?;
let conn = create_authenticated_conn(&remote, &cache)?; let conn = create_authenticated_conn(&remote, &cache)?;
let lab = find_lab_in_cache(&cache, &labname)?; let lab = find_laboratory(&conn, Some(&cache), &labname).await?;
let folder = find_folder(&conn, lab.id, &folder_path, None).await?; let folder = find_folder(&conn, lab.id, &folder_path, None).await?;
let mut data = serde_json::Map::new(); let mut data = serde_json::Map::new();
@@ -45,7 +49,78 @@ pub async fn chacl(
.await?; .await?;
if !resp.status().is_success() { if !resp.status().is_success() {
bail!("ACL change failed: {}", resp.status()); return Err(response_error("ACL change failed", resp).await);
} }
Ok(()) Ok(())
} }
async fn invalid_access_level_message(remote_path: &str) -> String {
// Project numbers exist only on the server. Failure to fetch them must not hide the
// original error: the access-level key was invalid independently of the connection.
let projects = async {
let (remote, _, _) = parse_remote_path(remote_path)?;
let (conn, _) = create_readonly_conn(&remote).await?;
conn.get_project_names().await
}
.await
.unwrap_or_default();
format_invalid_access_level_message(&projects)
}
fn format_invalid_access_level_message(projects: &ProjectNames) -> String {
let mut message = INVALID_ACCESS_LEVEL_MESSAGE.to_string();
if !projects.is_empty() {
message.push_str("\nProjects you belong to:");
for (bit, name) in projects {
message.push_str(&format!("\n project{bit}_open: {name}"));
}
}
message
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeMap;
#[test]
fn invalid_level_message_lists_project_keys_and_names() {
let message = format_invalid_access_level_message(&BTreeMap::from([(
0,
"Brain/MINDS 2.0".to_string(),
)]));
assert!(message.contains("project<n>_open"));
assert!(message.contains("project0_open: Brain/MINDS 2.0"));
}
#[test]
fn invalid_level_message_stands_alone_without_project_names() {
assert_eq!(
format_invalid_access_level_message(&ProjectNames::new()),
INVALID_ACCESS_LEVEL_MESSAGE
);
}
#[tokio::test]
async fn an_invalid_key_keeps_its_own_error_without_a_usable_remote() {
let err = chacl("not-a-remote-path", "5kikan_open", false, None)
.await
.unwrap_err();
assert_eq!(err.to_string(), INVALID_ACCESS_LEVEL_MESSAGE);
}
#[tokio::test]
async fn public_and_storage_are_refused_before_using_a_remote_path() {
for level in ["public", "storage"] {
let err = chacl("not-a-remote-path", level, false, None)
.await
.unwrap_err();
assert_eq!(
err.to_string(),
format!("`{level}` cannot be set as an access level.")
);
}
}
}
+59 -9
View File
@@ -13,8 +13,9 @@ fn sanitize_config_file(path: &PathBuf) -> Result<(), anyhow::Error> {
} }
let text = fs::read_to_string(path)?; let text = fs::read_to_string(path)?;
let lines: Vec<&str> = text.lines().collect(); let lines: Vec<&str> = text.lines().collect();
if let Some(first) = lines.first() { if let Some(first) = lines.first()
if first.trim() == path.to_string_lossy() { && first.trim() == path.to_string_lossy()
{
// remove the first line and write atomically // remove the first line and write atomically
let new_text = if lines.len() > 1 { let new_text = if lines.len() > 1 {
lines[1..].join("\n") lines[1..].join("\n")
@@ -25,7 +26,6 @@ fn sanitize_config_file(path: &PathBuf) -> Result<(), anyhow::Error> {
fs::write(&tmp, new_text.as_bytes())?; fs::write(&tmp, new_text.as_bytes())?;
fs::rename(&tmp, path)?; fs::rename(&tmp, path)?;
} }
}
Ok(()) Ok(())
} }
@@ -49,9 +49,10 @@ pub fn get_remote_url(remote: &str) -> Result<Option<String>, anyhow::Error> {
} }
pub fn config_create(remote: &str, url: &str) -> Result<(), anyhow::Error> { pub fn config_create(remote: &str, url: &str) -> Result<(), anyhow::Error> {
if !validate_url(url) { let Some(url) = normalize_url(url) else {
bail!("Malformed URL"); bail!("Malformed URL");
} };
let url = url.as_str();
let path = config_path(); let path = config_path();
sanitize_config_file(&path)?; sanitize_config_file(&path)?;
let path_str = path.to_string_lossy().to_string(); let path_str = path.to_string_lossy().to_string();
@@ -78,9 +79,10 @@ pub fn config_create(remote: &str, url: &str) -> Result<(), anyhow::Error> {
} }
pub fn config_update(remote: &str, url: &str) -> Result<(), anyhow::Error> { pub fn config_update(remote: &str, url: &str) -> Result<(), anyhow::Error> {
if !validate_url(url) { let Some(url) = normalize_url(url) else {
bail!("Malformed URL"); bail!("Malformed URL");
} };
let url = url.as_str();
let path = config_path(); let path = config_path();
sanitize_config_file(&path)?; sanitize_config_file(&path)?;
let path_str = path.to_string_lossy().to_string(); let path_str = path.to_string_lossy().to_string();
@@ -145,6 +147,54 @@ pub fn config_delete(remote: &str) -> Result<(), anyhow::Error> {
Ok(()) Ok(())
} }
fn validate_url(url: &str) -> bool { /// Check a remote URL and put it in the one form every client agrees on.
validators::url::Url::parse(url).is_ok() ///
/// A bare hostname is accepted, so a development server on `localhost` is as acceptable
/// as a deployment behind a domain name. The trailing slash goes because the URL is
/// joined with a path that brings its own.
fn normalize_url(url: &str) -> Option<String> {
let parsed = reqwest::Url::parse(url).ok()?;
if !matches!(parsed.scheme(), "http" | "https") {
return None;
}
parsed.host_str()?;
Some(url.trim_end_matches('/').to_string())
}
#[cfg(test)]
mod url_tests {
use super::normalize_url;
/// Both clients share config.ini, so they have to agree on what a remote URL is.
#[test]
fn trailing_slash_is_dropped() {
assert_eq!(
normalize_url("http://127.0.0.1:8000/api/").as_deref(),
Some("http://127.0.0.1:8000/api")
);
assert_eq!(
normalize_url("https://neurodata.riken.jp/api/").as_deref(),
Some("https://neurodata.riken.jp/api")
);
}
#[test]
fn bare_hostname_is_accepted() {
assert_eq!(
normalize_url("http://localhost:8000/api").as_deref(),
Some("http://localhost:8000/api")
);
}
#[test]
fn only_http_schemes_are_accepted() {
for url in [
"ftp://x.example.com/",
"file:///etc/passwd",
"not-a-url",
"http://",
] {
assert_eq!(normalize_url(url), None, "{url} should be rejected");
}
}
} }
+5 -5
View File
@@ -1,8 +1,8 @@
use crate::cache::{create_authenticated_conn, load_cache_with_token_refresh}; use crate::cache::{create_authenticated_conn, load_cache_with_token_refresh};
use crate::commands::shared::{ use crate::commands::shared::{
find_file_by_name, find_folder, find_lab_in_cache, find_subfolder_by_name, nfc, find_file_by_name, find_folder, find_laboratory, find_subfolder_by_name, nfc, parse_remote_path,
parse_remote_path,
}; };
use crate::error::response_error;
use anyhow::bail; use anyhow::bail;
pub async fn cp(src_path: &str, dest_path: &str, recursive: bool) -> Result<(), anyhow::Error> { pub async fn cp(src_path: &str, dest_path: &str, recursive: bool) -> Result<(), anyhow::Error> {
@@ -19,7 +19,7 @@ pub async fn cp(src_path: &str, dest_path: &str, recursive: bool) -> Result<(),
let cache = load_cache_with_token_refresh(&s_remote).await?; let cache = load_cache_with_token_refresh(&s_remote).await?;
let conn = create_authenticated_conn(&s_remote, &cache)?; let conn = create_authenticated_conn(&s_remote, &cache)?;
let lab = find_lab_in_cache(&cache, &s_lab)?; let lab = find_laboratory(&conn, Some(&cache), &s_lab).await?;
let lab_id = lab.id; let lab_id = lab.id;
// Split source path into parent directory and target name // Split source path into parent directory and target name
@@ -62,7 +62,7 @@ pub async fn cp(src_path: &str, dest_path: &str, recursive: bool) -> Result<(),
.post_json(&format!("v3/files/{}/copy/", src_file_id), &body) .post_json(&format!("v3/files/{}/copy/", src_file_id), &body)
.await?; .await?;
if !resp.status().is_success() { if !resp.status().is_success() {
bail!("Copy failed: {}", resp.status()); return Err(response_error("Copy failed", resp).await);
} }
return Ok(()); return Ok(());
} }
@@ -102,7 +102,7 @@ pub async fn cp(src_path: &str, dest_path: &str, recursive: bool) -> Result<(),
.post_json(&format!("v3/folders/{}/copy/", src_folder_id), &body) .post_json(&format!("v3/folders/{}/copy/", src_folder_id), &body)
.await?; .await?;
if !resp.status().is_success() { if !resp.status().is_success() {
bail!("Copy failed: {}", resp.status()); return Err(response_error("Copy failed", resp).await);
} }
Ok(()) Ok(())
} }
+181 -153
View File
@@ -4,6 +4,8 @@ use crate::commands::shared::{
find_subfolder_by_name, is_doi, parse_doi_remote_path, parse_remote_path, find_subfolder_by_name, is_doi, parse_doi_remote_path, parse_remote_path,
}; };
use crate::connection::{ApiRequestLimiter, MDRSConnection}; use crate::connection::{ApiRequestLimiter, MDRSConnection};
use crate::error::FolderLockedError;
use crate::models::folder::FolderSimple;
use anyhow::{anyhow, bail}; use anyhow::{anyhow, bail};
use std::path::PathBuf; use std::path::PathBuf;
use std::sync::Arc; use std::sync::Arc;
@@ -27,10 +29,10 @@ pub async fn download(
} }
// Detect DOI path: "remote:10.xxxx/prefix.ID[/optional/sub/path]" // Detect DOI path: "remote:10.xxxx/prefix.ID[/optional/sub/path]"
if is_doi(remote_path.splitn(2, ':').nth(1).unwrap_or("")) { if is_doi(remote_path.split_once(':').map(|x| x.1).unwrap_or("")) {
let (remote, doi, subpath) = parse_doi_remote_path(remote_path)?; let (remote, doi, subpath) = parse_doi_remote_path(remote_path)?;
let (raw_conn, _cache) = create_readonly_conn(&remote).await?; let (raw_conn, _cache) = create_readonly_conn(&remote).await?;
let (doi_folder, lab) = find_folder_by_doi(&raw_conn, &doi, password).await?; let (doi_folder, lab) = find_folder_by_doi(&raw_conn, &doi).await?;
let abs_path = format!("{}{}", doi_folder.path.trim_end_matches('/'), subpath); let abs_path = format!("{}{}", doi_folder.path.trim_end_matches('/'), subpath);
let abs_path_clean = abs_path.trim_end_matches('/'); let abs_path_clean = abs_path.trim_end_matches('/');
@@ -84,16 +86,14 @@ pub async fn download(
continue; continue;
} }
let dest = local_real.join(&file.name); let dest = local_real.join(&file.name);
if skip_if_exists { if skip_if_exists
if dest.exists() { && dest.exists()
if let Ok(meta) = std::fs::metadata(&dest) { && let Ok(meta) = std::fs::metadata(&dest)
if meta.len() == file.size { && meta.len() == file.size
{
println!("{}", dest.display()); println!("{}", dest.display());
continue; continue;
} }
}
}
}
let url = make_absolute_url(&conn, &file.download_url); let url = make_absolute_url(&conn, &file.download_url);
conn.download_file_limited(&url, &dest.to_string_lossy(), &limiter) conn.download_file_limited(&url, &dest.to_string_lossy(), &limiter)
.await?; .await?;
@@ -102,29 +102,22 @@ pub async fn download(
return Ok(()); return Ok(());
} }
spawn_download_folder_task( let session = DownloadSession {
&mut folder_tasks, conn: conn.clone(),
conn.clone(),
limiter.clone(),
lab_name.clone(),
excludes.clone(),
folder.id.clone(),
top_local,
password_owned.clone(),
skip_if_exists,
);
drive_download_tasks(
&mut folder_tasks,
&mut download_tasks,
&mut errors,
conn.clone(),
limiter, limiter,
lab_name, lab_name,
excludes, excludes,
password_owned, password: password_owned,
skip_if_exists, skip_if_exists,
) };
spawn_download_folder_task(
&mut folder_tasks,
session.clone(),
folder.id.clone(),
top_local,
);
drive_download_tasks(&mut folder_tasks, &mut download_tasks, &mut errors, session)
.await; .await;
if !errors.is_empty() { if !errors.is_empty() {
@@ -146,16 +139,14 @@ pub async fn download(
return Ok(()); return Ok(());
} }
let dest = local_real.join(&file.name); let dest = local_real.join(&file.name);
if skip_if_exists { if skip_if_exists
if dest.exists() { && dest.exists()
if let Ok(meta) = std::fs::metadata(&dest) { && let Ok(meta) = std::fs::metadata(&dest)
if meta.len() == file.size { && meta.len() == file.size
{
println!("{}", dest.display()); println!("{}", dest.display());
return Ok(()); return Ok(());
} }
}
}
}
let url = make_absolute_url(&conn, &file.download_url); let url = make_absolute_url(&conn, &file.download_url);
conn.download_file_limited(&url, &dest.to_string_lossy(), &limiter) conn.download_file_limited(&url, &dest.to_string_lossy(), &limiter)
.await?; .await?;
@@ -169,6 +160,7 @@ pub async fn download(
if !recursive { if !recursive {
bail!("Cannot download `{}`: Is a folder.", abs_path_clean); bail!("Cannot download `{}`: Is a folder.", abs_path_clean);
} }
authenticate_download_root(&conn, &limiter, sub, password).await?;
let top_local = local_real.join(&sub.name); let top_local = local_real.join(&sub.name);
let mut folder_tasks: JoinSet<Result<DownloadFolderTaskResult, anyhow::Error>> = let mut folder_tasks: JoinSet<Result<DownloadFolderTaskResult, anyhow::Error>> =
JoinSet::new(); JoinSet::new();
@@ -177,29 +169,22 @@ pub async fn download(
let lab_name = Arc::new(lab.name.clone()); let lab_name = Arc::new(lab.name.clone());
let password_owned = password.map(str::to_string); let password_owned = password.map(str::to_string);
spawn_download_folder_task( let session = DownloadSession {
&mut folder_tasks, conn: conn.clone(),
conn.clone(),
limiter.clone(),
lab_name.clone(),
excludes.clone(),
sub.id.clone(),
top_local,
password_owned.clone(),
skip_if_exists,
);
drive_download_tasks(
&mut folder_tasks,
&mut download_tasks,
&mut errors,
conn.clone(),
limiter, limiter,
lab_name, lab_name,
excludes, excludes,
password_owned, password: password_owned,
skip_if_exists, skip_if_exists,
) };
spawn_download_folder_task(
&mut folder_tasks,
session.clone(),
sub.id.clone(),
top_local,
);
drive_download_tasks(&mut folder_tasks, &mut download_tasks, &mut errors, session)
.await; .await;
if !errors.is_empty() { if !errors.is_empty() {
@@ -242,16 +227,14 @@ pub async fn download(
} }
// Python always places the downloaded file inside the local directory. // Python always places the downloaded file inside the local directory.
let dest = local_real.join(&file.name); let dest = local_real.join(&file.name);
if skip_if_exists { if skip_if_exists
if dest.exists() { && dest.exists()
if let Ok(meta) = std::fs::metadata(&dest) { && let Ok(meta) = std::fs::metadata(&dest)
if meta.len() == file.size { && meta.len() == file.size
{
println!("{}", dest.display()); println!("{}", dest.display());
return Ok(()); return Ok(());
} }
}
}
}
let url = make_absolute_url(&conn, &file.download_url); let url = make_absolute_url(&conn, &file.download_url);
conn.download_file_limited(&url, &dest.to_string_lossy(), &limiter) conn.download_file_limited(&url, &dest.to_string_lossy(), &limiter)
.await?; .await?;
@@ -265,6 +248,7 @@ pub async fn download(
if !recursive { if !recursive {
bail!("Cannot download `{}`: Is a folder.", r_path_clean); bail!("Cannot download `{}`: Is a folder.", r_path_clean);
} }
authenticate_download_root(&conn, &limiter, sub, password).await?;
// Python downloads into local_path/<remote_folder_name>/ (not directly into local_path). // Python downloads into local_path/<remote_folder_name>/ (not directly into local_path).
// We create that subdirectory first, then recurse into it. // We create that subdirectory first, then recurse into it.
let top_local = local_real.join(&sub.name); let top_local = local_real.join(&sub.name);
@@ -277,30 +261,22 @@ pub async fn download(
let lab_name = Arc::new(lab.name.clone()); let lab_name = Arc::new(lab.name.clone());
let password = password.map(str::to_string); let password = password.map(str::to_string);
spawn_download_folder_task( let session = DownloadSession {
&mut folder_tasks, conn: conn.clone(),
conn.clone(),
limiter.clone(),
lab_name.clone(),
excludes.clone(),
sub.id.clone(),
top_local,
password.clone(),
skip_if_exists,
);
drive_download_tasks(
&mut folder_tasks,
&mut download_tasks,
&mut errors,
conn.clone(),
limiter, limiter,
lab_name, lab_name,
excludes, excludes,
password, password,
skip_if_exists, skip_if_exists,
) };
.await; spawn_download_folder_task(
&mut folder_tasks,
session.clone(),
sub.id.clone(),
top_local,
);
drive_download_tasks(&mut folder_tasks, &mut download_tasks, &mut errors, session).await;
if !errors.is_empty() { if !errors.is_empty() {
bail!(errors.join("\n")); bail!(errors.join("\n"));
@@ -311,6 +287,23 @@ pub async fn download(
Err(anyhow!("File or folder `{}` not found.", r_path_clean)) Err(anyhow!("File or folder `{}` not found.", r_path_clean))
} }
/// The recursive workers authenticate descendants, but the selected root is not a
/// descendant of itself and must be opened before its first retrieve.
async fn authenticate_download_root(
conn: &MDRSConnection,
limiter: &ApiRequestLimiter,
folder: &FolderSimple,
password: Option<&str>,
) -> Result<(), anyhow::Error> {
if !folder.lock {
return Ok(());
}
let password =
password.ok_or_else(|| FolderLockedError::new(&folder.name).with_password_hint())?;
conn.folder_auth_limited(&folder.id, password, limiter)
.await
}
/// Return true if the given lab/folder/file path matches any exclude pattern. /// Return true if the given lab/folder/file path matches any exclude pattern.
/// Constructs: `/{lab_name}{folder_path}{file_name}` lowercased, trailing slash stripped. /// Constructs: `/{lab_name}{folder_path}{file_name}` lowercased, trailing slash stripped.
/// `folder_path` is expected to already start (and end) with "/". /// `folder_path` is expected to already start (and end) with "/".
@@ -353,30 +346,26 @@ struct DownloadJob {
dest_path: PathBuf, dest_path: PathBuf,
} }
fn spawn_download_folder_task( /// What every folder of one recursive download shares: the connection and its request
folder_tasks: &mut JoinSet<Result<DownloadFolderTaskResult, anyhow::Error>>, /// budget, the laboratory the paths are named against, what to leave out, the password
/// for locked folders, and whether files already on disk may be left alone.
#[derive(Clone)]
struct DownloadSession {
conn: Arc<MDRSConnection>, conn: Arc<MDRSConnection>,
limiter: ApiRequestLimiter, limiter: ApiRequestLimiter,
lab_name: Arc<String>, lab_name: Arc<String>,
excludes: Arc<Vec<String>>, excludes: Arc<Vec<String>>,
folder_id: String,
local_dir: PathBuf,
password: Option<String>, password: Option<String>,
skip_if_exists: bool, skip_if_exists: bool,
}
fn spawn_download_folder_task(
folder_tasks: &mut JoinSet<Result<DownloadFolderTaskResult, anyhow::Error>>,
session: DownloadSession,
folder_id: String,
local_dir: PathBuf,
) { ) {
folder_tasks.spawn(async move { folder_tasks.spawn(async move { process_download_folder(session, folder_id, local_dir).await });
process_download_folder(
conn,
limiter,
lab_name,
excludes,
folder_id,
local_dir,
password,
skip_if_exists,
)
.await
});
} }
fn spawn_download_task( fn spawn_download_task(
@@ -396,9 +385,8 @@ fn spawn_download_task(
Ok(()) Ok(())
} }
Err(err) => { Err(err) => {
if job.dest_path.is_file() { // Nothing to clear up: a failed transfer writes only to its own scratch
let _ = std::fs::remove_file(&job.dest_path); // file, and removes that itself.
}
Err(anyhow!( Err(anyhow!(
"Failed to download {}: {}", "Failed to download {}: {}",
job.dest_path.display(), job.dest_path.display(),
@@ -410,15 +398,18 @@ fn spawn_download_task(
} }
async fn process_download_folder( async fn process_download_folder(
conn: Arc<MDRSConnection>, session: DownloadSession,
limiter: ApiRequestLimiter,
lab_name: Arc<String>,
excludes: Arc<Vec<String>>,
folder_id: String, folder_id: String,
local_dir: PathBuf, local_dir: PathBuf,
password: Option<String>,
skip_if_exists: bool,
) -> Result<DownloadFolderTaskResult, anyhow::Error> { ) -> Result<DownloadFolderTaskResult, anyhow::Error> {
let DownloadSession {
conn,
limiter,
lab_name,
excludes,
password,
skip_if_exists,
} = session;
let folder = conn.retrieve_folder_limited(&folder_id, &limiter).await?; let folder = conn.retrieve_folder_limited(&folder_id, &limiter).await?;
if is_excluded(excludes.as_slice(), lab_name.as_str(), &folder.path, None) { if is_excluded(excludes.as_slice(), lab_name.as_str(), &folder.path, None) {
@@ -443,14 +434,14 @@ async fn process_download_folder(
continue; continue;
} }
let dest_path = local_dir.join(&file.name); let dest_path = local_dir.join(&file.name);
if skip_if_exists && dest_path.exists() { if skip_if_exists
if let Ok(meta) = std::fs::metadata(&dest_path) { && dest_path.exists()
if meta.len() == file.size { && let Ok(meta) = std::fs::metadata(&dest_path)
&& meta.len() == file.size
{
println!("{}", dest_path.display()); println!("{}", dest_path.display());
continue; continue;
} }
}
}
download_jobs.push(DownloadJob { download_jobs.push(DownloadJob {
url: make_absolute_url(&conn, &file.download_url), url: make_absolute_url(&conn, &file.download_url),
dest_path, dest_path,
@@ -500,12 +491,7 @@ async fn drive_download_tasks(
folder_tasks: &mut JoinSet<Result<DownloadFolderTaskResult, anyhow::Error>>, folder_tasks: &mut JoinSet<Result<DownloadFolderTaskResult, anyhow::Error>>,
download_tasks: &mut JoinSet<Result<(), anyhow::Error>>, download_tasks: &mut JoinSet<Result<(), anyhow::Error>>,
errors: &mut Vec<String>, errors: &mut Vec<String>,
conn: Arc<MDRSConnection>, session: DownloadSession,
limiter: ApiRequestLimiter,
lab_name: Arc<String>,
excludes: Arc<Vec<String>>,
password: Option<String>,
skip_if_exists: bool,
) { ) {
loop { loop {
match (folder_tasks.is_empty(), download_tasks.is_empty()) { match (folder_tasks.is_empty(), download_tasks.is_empty()) {
@@ -517,22 +503,17 @@ async fn drive_download_tasks(
folder_tasks, folder_tasks,
download_tasks, download_tasks,
errors, errors,
conn.clone(), &session,
limiter.clone(),
lab_name.clone(),
excludes.clone(),
password.clone(),
skip_if_exists,
); );
} }
} }
(true, false) => { (true, false) => {
if let Some(result) = download_tasks.join_next().await { if let Some(result) = download_tasks.join_next().await
if let Err(err) = flatten_join_result(result) { && let Err(err) = flatten_join_result(result)
{
errors.push(err.to_string()); errors.push(err.to_string());
} }
} }
}
(false, false) => { (false, false) => {
tokio::select! { tokio::select! {
result = folder_tasks.join_next() => { result = folder_tasks.join_next() => {
@@ -542,18 +523,13 @@ async fn drive_download_tasks(
folder_tasks, folder_tasks,
download_tasks, download_tasks,
errors, errors,
conn.clone(), &session,
limiter.clone(),
lab_name.clone(),
excludes.clone(),
password.clone(),
skip_if_exists,
); );
} }
} }
result = download_tasks.join_next() => { result = download_tasks.join_next() => {
if let Some(result) = result { if let Some(result) = result
if let Err(err) = flatten_join_result(result) { && let Err(err) = flatten_join_result(result) {
errors.push(err.to_string()); errors.push(err.to_string());
} }
} }
@@ -561,7 +537,6 @@ async fn drive_download_tasks(
} }
} }
} }
}
} }
fn handle_download_folder_result( fn handle_download_folder_result(
@@ -569,30 +544,20 @@ fn handle_download_folder_result(
folder_tasks: &mut JoinSet<Result<DownloadFolderTaskResult, anyhow::Error>>, folder_tasks: &mut JoinSet<Result<DownloadFolderTaskResult, anyhow::Error>>,
download_tasks: &mut JoinSet<Result<(), anyhow::Error>>, download_tasks: &mut JoinSet<Result<(), anyhow::Error>>,
errors: &mut Vec<String>, errors: &mut Vec<String>,
conn: Arc<MDRSConnection>, session: &DownloadSession,
limiter: ApiRequestLimiter,
lab_name: Arc<String>,
excludes: Arc<Vec<String>>,
password: Option<String>,
skip_if_exists: bool,
) { ) {
match flatten_join_result(result) { match flatten_join_result(result) {
Ok(task_result) => { Ok(task_result) => {
for (folder_id, local_dir) in task_result.child_folders { for (folder_id, local_dir) in task_result.child_folders {
spawn_download_folder_task( spawn_download_folder_task(folder_tasks, session.clone(), folder_id, local_dir);
folder_tasks,
conn.clone(),
limiter.clone(),
lab_name.clone(),
excludes.clone(),
folder_id,
local_dir,
password.clone(),
skip_if_exists,
);
} }
for job in task_result.download_jobs { for job in task_result.download_jobs {
spawn_download_task(download_tasks, conn.clone(), limiter.clone(), job); spawn_download_task(
download_tasks,
session.conn.clone(),
session.limiter.clone(),
job,
);
} }
} }
Err(err) => errors.push(err.to_string()), Err(err) => errors.push(err.to_string()),
@@ -607,3 +572,66 @@ fn flatten_join_result<T>(
Err(err) => Err(anyhow!("Task join failed: {}", err)), Err(err) => Err(anyhow!("Task join failed: {}", err)),
} }
} }
#[cfg(test)]
mod tests {
use super::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
fn folder(lock: bool) -> FolderSimple {
FolderSimple {
id: "locked-root".to_string(),
pid: None,
name: "dataset".to_string(),
access_level: 4,
lock,
size: 0,
laboratory_id: 1,
description: String::new(),
created_at: "2026-01-01T00:00:00+09:00".to_string(),
updated_at: "2026-01-01T00:00:00+09:00".to_string(),
}
}
#[tokio::test]
async fn download_root_authentication_is_needed_only_for_a_locked_folder() {
let conn = MDRSConnection::new("http://127.0.0.1:9");
let limiter = ApiRequestLimiter::new(1);
authenticate_download_root(&conn, &limiter, &folder(false), None)
.await
.unwrap();
let err = authenticate_download_root(&conn, &limiter, &folder(true), None)
.await
.unwrap_err();
assert!(err.downcast_ref::<FolderLockedError>().is_some());
}
#[tokio::test]
async fn locked_download_root_is_authenticated_before_its_worker_starts() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut buf = [0u8; 4096];
let n = stream.read(&mut buf).await.unwrap();
let request = String::from_utf8_lossy(&buf[..n]);
assert!(request.starts_with("POST /v3/folders/locked-root/auth/ HTTP/1.1"));
assert!(request.contains(r#"{"password":"secret"}"#));
stream
.write_all(
b"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: 2\r\nconnection: close\r\n\r\n{}",
)
.await
.unwrap();
});
let conn = MDRSConnection::new(&format!("http://{addr}"));
let limiter = ApiRequestLimiter::new(1);
authenticate_download_root(&conn, &limiter, &folder(true), Some("secret"))
.await
.unwrap();
server.await.unwrap();
}
}
+5 -1
View File
@@ -1,10 +1,11 @@
use crate::cache::create_readonly_conn; use crate::cache::create_readonly_conn;
use crate::commands::shared::{find_file_by_name, resolve_remote_file}; use crate::commands::shared::{find_file_by_name, resolve_remote_file};
use crate::error::response_error;
use anyhow::anyhow; use anyhow::anyhow;
pub async fn file_metadata(remote_path: &str, password: Option<&str>) -> Result<(), anyhow::Error> { pub async fn file_metadata(remote_path: &str, password: Option<&str>) -> Result<(), anyhow::Error> {
let remote = remote_path let remote = remote_path
.splitn(2, ':') .split(':')
.next() .next()
.ok_or_else(|| anyhow!("Invalid remote path"))?; .ok_or_else(|| anyhow!("Invalid remote path"))?;
let (conn, cache) = create_readonly_conn(remote).await?; let (conn, cache) = create_readonly_conn(remote).await?;
@@ -17,6 +18,9 @@ pub async fn file_metadata(remote_path: &str, password: Option<&str>) -> Result<
.ok_or_else(|| anyhow!("File `{}` not found.", basename))?; .ok_or_else(|| anyhow!("File `{}` not found.", basename))?;
let resp = conn.get(&format!("v3/files/{}/metadata/", file.id)).await?; let resp = conn.get(&format!("v3/files/{}/metadata/", file.id)).await?;
if !resp.status().is_success() {
return Err(response_error("Failed to get file metadata", resp).await);
}
let json: serde_json::Value = resp.json().await?; let json: serde_json::Value = resp.json().await?;
println!("{}", serde_json::to_string(&json)?); println!("{}", serde_json::to_string(&json)?);
Ok(()) Ok(())
+114 -29
View File
@@ -1,12 +1,19 @@
use crate::cache::create_readonly_conn; use crate::cache::{Cache, create_readonly_conn};
use crate::commands::shared::{fmt_datetime, resolve_remote_folder}; use crate::commands::shared::{fmt_datetime, resolve_remote_folder};
use crate::connection::MDRSConnection; use crate::connection::MDRSConnection;
use crate::models::file::File; use crate::models::file::File;
use crate::models::folder::{FolderDetail, FolderSimple}; use crate::models::folder::{FolderDetail, FolderSimple, ProjectNames};
use serde_json::{Value, json}; use serde_json::{Value, json};
use std::collections::HashMap;
use std::future::Future; use std::future::Future;
use std::pin::Pin; use std::pin::Pin;
/// Laboratory names by id, for the JSON output's per-folder `laboratory` field.
type LaboratoryNames = HashMap<u32, String>;
/// Shown for a folder whose laboratory the client cannot name, matching the Python client.
const UNKNOWN_LABORATORY: &str = "(invalid)";
pub async fn ls( pub async fn ls(
remote_path: &str, remote_path: &str,
password: Option<&str>, password: Option<&str>,
@@ -15,35 +22,39 @@ pub async fn ls(
is_quiet: bool, is_quiet: bool,
) -> Result<(), anyhow::Error> { ) -> Result<(), anyhow::Error> {
let remote = remote_path let remote = remote_path
.splitn(2, ':') .split(':')
.next() .next()
.ok_or_else(|| anyhow::anyhow!("Invalid remote path"))?; .ok_or_else(|| anyhow::anyhow!("Invalid remote path"))?;
let (conn, cache) = create_readonly_conn(remote).await?; let (conn, cache) = create_readonly_conn(remote).await?;
let (folder, lab) = let (folder, lab) =
resolve_remote_folder(&conn, cache.as_ref(), None, remote_path, password).await?; resolve_remote_folder(&conn, cache.as_ref(), None, remote_path, password).await?;
let labname = lab.name; let labname = lab.name;
let projects = conn.get_project_names().await?;
if is_json { if is_json {
let names = laboratory_names(&conn, cache.as_ref()).await;
let output = if is_recursive { let output = if is_recursive {
build_folder_json_recursive(&conn, folder, &labname).await? build_folder_json_recursive(&conn, folder, &names, &projects, password).await?
} else { } else {
build_folder_json_flat(&conn, &folder, &labname).await? build_folder_json_flat(&conn, &folder, &names, &projects).await?
}; };
println!("{}", serde_json::to_string(&output)?); println!("{}", serde_json::to_string(&output)?);
} else if is_recursive { } else if is_recursive {
let prefix = format!("{}:/{}", conn.remote.as_deref().unwrap_or(""), labname); let prefix = format!("{}:/{}", conn.remote.as_deref().unwrap_or(""), labname);
ls_plain_recursive(&conn, folder, &labname, &prefix, password).await?; ls_plain_recursive(&conn, folder, &labname, &prefix, &projects, password).await?;
} else { } else {
let files = conn.list_all_files(&folder.id).await?; let files = conn.list_all_files(&folder.id).await?;
let mut sub_folders = folder.sub_folders.clone(); let mut sub_folders = folder.sub_folders.clone();
sub_folders.sort_by(|a, b| a.name.cmp(&b.name)); sub_folders.sort_by(|a, b| a.name.cmp(&b.name));
let mut files_sorted = files; let mut files_sorted = files;
files_sorted.sort_by(|a, b| a.name.cmp(&b.name)); files_sorted.sort_by(|a, b| a.name.cmp(&b.name));
let access = folder.access_level_label(&projects);
print_folder_plain( print_folder_plain(
&sub_folders, &sub_folders,
&files_sorted, &files_sorted,
folder.access_level_name(), &access,
&labname, &labname,
&projects,
!is_quiet, !is_quiet,
); );
} }
@@ -60,6 +71,7 @@ fn print_folder_plain(
files: &[File], files: &[File],
folder_access: &str, folder_access: &str,
labname: &str, labname: &str,
projects: &ProjectNames,
show_header: bool, show_header: bool,
) { ) {
let header = ("Type", "Access", "Laboratory", "Size", "Date", "Name"); let header = ("Type", "Access", "Laboratory", "Size", "Date", "Name");
@@ -74,7 +86,7 @@ fn print_folder_plain(
w_type = w_type.max(3); w_type = w_type.max(3);
for sf in sub_folders { for sf in sub_folders {
w_access = w_access.max(sf.access_level_name().len()); w_access = w_access.max(sf.access_level_label(projects).len());
w_size = w_size.max(sf.size.to_string().len()); w_size = w_size.max(sf.size.to_string().len());
w_date = w_date.max(fmt_datetime(&sf.updated_at).len()); w_date = w_date.max(fmt_datetime(&sf.updated_at).len());
w_name = w_name.max(sf.name.len()); w_name = w_name.max(sf.name.len());
@@ -111,7 +123,7 @@ fn print_folder_plain(
println!( println!(
"{:<w_type$} {:<w_access$} {:<w_lab$} {:>w_size$} {:<w_date$} {:<w_name$}", "{:<w_type$} {:<w_access$} {:<w_lab$} {:>w_size$} {:<w_date$} {:<w_name$}",
folder_type, folder_type,
sf.access_level_name(), sf.access_level_label(projects),
labname, labname,
sf.size, sf.size,
fmt_datetime(&sf.updated_at), fmt_datetime(&sf.updated_at),
@@ -150,6 +162,7 @@ fn ls_plain_recursive<'a>(
folder: FolderDetail, folder: FolderDetail,
labname: &'a str, labname: &'a str,
prefix: &'a str, prefix: &'a str,
projects: &'a ProjectNames,
password: Option<&'a str>, password: Option<&'a str>,
) -> Pin<Box<dyn Future<Output = Result<(), anyhow::Error>> + 'a>> { ) -> Pin<Box<dyn Future<Output = Result<(), anyhow::Error>> + 'a>> {
Box::pin(async move { Box::pin(async move {
@@ -159,13 +172,20 @@ fn ls_plain_recursive<'a>(
println!("{}{}:", prefix, folder.path); println!("{}{}:", prefix, folder.path);
println!("total {}", total_size); println!("total {}", total_size);
let access = folder.access_level_name(); let access = folder.access_level_label(projects);
let mut sub_folders = folder.sub_folders.clone(); let mut sub_folders = folder.sub_folders.clone();
sub_folders.sort_by(|a, b| a.name.cmp(&b.name)); sub_folders.sort_by(|a, b| a.name.cmp(&b.name));
let mut files_sorted = files; let mut files_sorted = files;
files_sorted.sort_by(|a, b| a.name.cmp(&b.name)); files_sorted.sort_by(|a, b| a.name.cmp(&b.name));
print_folder_plain(&sub_folders, &files_sorted, access, labname, false); print_folder_plain(
&sub_folders,
&files_sorted,
&access,
labname,
projects,
false,
);
println!(); println!();
@@ -182,7 +202,8 @@ fn ls_plain_recursive<'a>(
} }
match conn.retrieve_folder(&sf.id).await { match conn.retrieve_folder(&sf.id).await {
Ok(sub_detail) => { Ok(sub_detail) => {
ls_plain_recursive(conn, sub_detail, labname, prefix, password).await?; ls_plain_recursive(conn, sub_detail, labname, prefix, projects, password)
.await?;
} }
Err(_) => continue, Err(_) => continue,
} }
@@ -214,7 +235,13 @@ fn file_to_json(f: &File, base_url: &str) -> Value {
let download_url = if f.download_url.starts_with("http") { let download_url = if f.download_url.starts_with("http") {
f.download_url.clone() f.download_url.clone()
} else { } else {
format!("{}{}", base_url.trim_end_matches('/'), f.download_url) // The API answers with a relative path and no leading separator, so supply one
// rather than running the two together.
format!(
"{}/{}",
base_url.trim_end_matches('/'),
f.download_url.trim_start_matches('/')
)
}; };
json!({ json!({
"id": f.id, "id": f.id,
@@ -229,34 +256,71 @@ fn file_to_json(f: &File, base_url: &str) -> Value {
}) })
} }
fn folder_simple_to_json(sf: &FolderSimple) -> Value { fn folder_simple_to_json(
sf: &FolderSimple,
names: &LaboratoryNames,
projects: &ProjectNames,
) -> Value {
json!({ json!({
"id": sf.id, "id": sf.id,
"pid": sf.pid, "pid": sf.pid,
"name": sf.name, "name": sf.name,
"access_level": sf.access_level_name(), "access_level": sf.access_level_label(projects),
"lock": sf.lock, "lock": sf.lock,
"size": sf.size, "size": sf.size,
"laboratory_id": sf.laboratory_id, "laboratory": laboratory_name(names, sf.laboratory_id),
"description": sf.description, "description": sf.description,
"created_at": sf.created_at, "created_at": sf.created_at,
"updated_at": sf.updated_at, "updated_at": sf.updated_at,
}) })
} }
/// Name the laboratory a folder belongs to, so a listing does not hand out an id the
/// reader has no way to resolve.
fn laboratory_name(names: &LaboratoryNames, id: u32) -> String {
names
.get(&id)
.cloned()
.unwrap_or_else(|| UNKNOWN_LABORATORY.to_string())
}
/// Collect laboratory names, preferring what the login cache already holds so a listing
/// does not pay for a request it does not need.
async fn laboratory_names(conn: &MDRSConnection, cache: Option<&Cache>) -> LaboratoryNames {
if let Some(cache) = cache.filter(|c| !c.laboratories.items.is_empty()) {
return cache
.laboratories
.items
.iter()
.map(|lab| (lab.id, lab.name.clone()))
.collect();
}
match conn.list_laboratories().await {
Ok(labs) => labs
.items
.into_iter()
.map(|lab| (lab.id, lab.name))
.collect(),
Err(_) => LaboratoryNames::new(),
}
}
/// Build JSON for the top-level folder without recursing into sub-folders. /// Build JSON for the top-level folder without recursing into sub-folders.
async fn build_folder_json_flat( async fn build_folder_json_flat(
conn: &MDRSConnection, conn: &MDRSConnection,
folder: &FolderDetail, folder: &FolderDetail,
labname: &str, names: &LaboratoryNames,
projects: &ProjectNames,
) -> Result<Value, anyhow::Error> { ) -> Result<Value, anyhow::Error> {
let metadata = get_folder_metadata(conn, &folder.id).await?; let metadata = get_folder_metadata(conn, &folder.id).await?;
let files = conn.list_all_files(&folder.id).await?; let mut files = conn.list_all_files(&folder.id).await?;
files.sort_by(|a, b| a.name.cmp(&b.name));
let files_json: Vec<Value> = files.iter().map(|f| file_to_json(f, &conn.url)).collect(); let files_json: Vec<Value> = files.iter().map(|f| file_to_json(f, &conn.url)).collect();
let sub_folders_json: Vec<Value> = folder let mut sub_folders = folder.sub_folders.clone();
.sub_folders sub_folders.sort_by(|a, b| a.name.cmp(&b.name));
let sub_folders_json: Vec<Value> = sub_folders
.iter() .iter()
.map(folder_simple_to_json) .map(|sf| folder_simple_to_json(sf, names, projects))
.collect(); .collect();
Ok(json!({ Ok(json!({
@@ -264,9 +328,9 @@ async fn build_folder_json_flat(
"pid": folder.pid, "pid": folder.pid,
"name": folder.name, "name": folder.name,
"size": folder.size, "size": folder.size,
"access_level": folder.access_level_name(), "access_level": folder.access_level_label(projects),
"lock": folder.lock, "lock": folder.lock,
"laboratory": labname, "laboratory": laboratory_name(names, folder.laboratory_id),
"description": folder.description, "description": folder.description,
"created_at": folder.created_at, "created_at": folder.created_at,
"updated_at": folder.updated_at, "updated_at": folder.updated_at,
@@ -280,17 +344,38 @@ async fn build_folder_json_flat(
fn build_folder_json_recursive<'a>( fn build_folder_json_recursive<'a>(
conn: &'a MDRSConnection, conn: &'a MDRSConnection,
folder: FolderDetail, folder: FolderDetail,
labname: &'a str, names: &'a LaboratoryNames,
projects: &'a ProjectNames,
password: Option<&'a str>,
) -> Pin<Box<dyn Future<Output = Result<Value, anyhow::Error>> + 'a>> { ) -> Pin<Box<dyn Future<Output = Result<Value, anyhow::Error>> + 'a>> {
Box::pin(async move { Box::pin(async move {
let metadata = get_folder_metadata(conn, &folder.id).await?; let metadata = get_folder_metadata(conn, &folder.id).await?;
let files = conn.list_all_files(&folder.id).await?; let mut files = conn.list_all_files(&folder.id).await?;
files.sort_by(|a, b| a.name.cmp(&b.name));
let files_json: Vec<Value> = files.iter().map(|f| file_to_json(f, &conn.url)).collect(); let files_json: Vec<Value> = files.iter().map(|f| file_to_json(f, &conn.url)).collect();
let mut sub_folders = folder.sub_folders.clone();
sub_folders.sort_by(|a, b| a.name.cmp(&b.name));
let mut sub_folders_json = Vec::new(); let mut sub_folders_json = Vec::new();
for sf in &folder.sub_folders { for sf in &sub_folders {
// A folder the caller cannot unlock is left out rather than ending the whole
// listing: a tree usually holds a locked folder or two, and the rest of it is
// still what the user asked to see. Anything else is reported, because a
// listing that quietly drops a branch cannot be told from one where the
// branch is empty, and this output is read by programs.
if sf.lock {
match password {
None => continue,
Some(pw) => {
if conn.folder_auth(&sf.id, pw).await.is_err() {
continue;
}
}
}
}
let sf_detail = conn.retrieve_folder(&sf.id).await?; let sf_detail = conn.retrieve_folder(&sf.id).await?;
let sf_json = build_folder_json_recursive(conn, sf_detail, labname).await?; let sf_json =
build_folder_json_recursive(conn, sf_detail, names, projects, password).await?;
sub_folders_json.push(sf_json); sub_folders_json.push(sf_json);
} }
@@ -299,9 +384,9 @@ fn build_folder_json_recursive<'a>(
"pid": folder.pid, "pid": folder.pid,
"name": folder.name, "name": folder.name,
"size": folder.size, "size": folder.size,
"access_level": folder.access_level_name(), "access_level": folder.access_level_label(projects),
"lock": folder.lock, "lock": folder.lock,
"laboratory": labname, "laboratory": laboratory_name(names, folder.laboratory_id),
"description": folder.description, "description": folder.description,
"created_at": folder.created_at, "created_at": folder.created_at,
"updated_at": folder.updated_at, "updated_at": folder.updated_at,
+5 -1
View File
@@ -1,9 +1,10 @@
use crate::cache::create_readonly_conn; use crate::cache::create_readonly_conn;
use crate::commands::shared::resolve_remote_folder; use crate::commands::shared::resolve_remote_folder;
use crate::error::response_error;
pub async fn metadata(remote_path: &str, password: Option<&str>) -> Result<(), anyhow::Error> { pub async fn metadata(remote_path: &str, password: Option<&str>) -> Result<(), anyhow::Error> {
let remote = remote_path let remote = remote_path
.splitn(2, ':') .split(':')
.next() .next()
.ok_or_else(|| anyhow::anyhow!("Invalid remote path"))?; .ok_or_else(|| anyhow::anyhow!("Invalid remote path"))?;
let (conn, cache) = create_readonly_conn(remote).await?; let (conn, cache) = create_readonly_conn(remote).await?;
@@ -13,6 +14,9 @@ pub async fn metadata(remote_path: &str, password: Option<&str>) -> Result<(), a
let resp = conn let resp = conn
.get(&format!("v3/folders/{}/metadata/", folder.id)) .get(&format!("v3/folders/{}/metadata/", folder.id))
.await?; .await?;
if !resp.status().is_success() {
return Err(response_error("Failed to get folder metadata", resp).await);
}
let json: serde_json::Value = resp.json().await?; let json: serde_json::Value = resp.json().await?;
println!("{}", serde_json::to_string(&json)?); println!("{}", serde_json::to_string(&json)?);
Ok(()) Ok(())
+4 -4
View File
@@ -1,8 +1,8 @@
use crate::cache::{create_authenticated_conn, load_cache_with_token_refresh}; use crate::cache::{create_authenticated_conn, load_cache_with_token_refresh};
use crate::commands::shared::{ use crate::commands::shared::{
find_file_by_name, find_folder, find_lab_in_cache, find_subfolder_by_name, nfc, find_file_by_name, find_folder, find_laboratory, find_subfolder_by_name, nfc, parse_remote_path,
parse_remote_path,
}; };
use crate::error::response_error;
use anyhow::{anyhow, bail}; use anyhow::{anyhow, bail};
pub async fn mkdir(remote_path: &str) -> Result<(), anyhow::Error> { pub async fn mkdir(remote_path: &str) -> Result<(), anyhow::Error> {
@@ -25,7 +25,7 @@ pub async fn mkdir(remote_path: &str) -> Result<(), anyhow::Error> {
let cache = load_cache_with_token_refresh(&remote).await?; let cache = load_cache_with_token_refresh(&remote).await?;
let conn = create_authenticated_conn(&remote, &cache)?; let conn = create_authenticated_conn(&remote, &cache)?;
let lab = find_lab_in_cache(&cache, &labname)?; let lab = find_laboratory(&conn, Some(&cache), &labname).await?;
let parent_folder = find_folder(&conn, lab.id, parent_path, None).await?; let parent_folder = find_folder(&conn, lab.id, parent_path, None).await?;
// Check for name conflict in sub-folders or files // Check for name conflict in sub-folders or files
@@ -40,7 +40,7 @@ pub async fn mkdir(remote_path: &str) -> Result<(), anyhow::Error> {
.create_folder(&parent_folder.id, &nfc(new_folder_name)) .create_folder(&parent_folder.id, &nfc(new_folder_name))
.await?; .await?;
if !resp.status().is_success() { if !resp.status().is_success() {
bail!("Failed to create folder: {}", resp.status()); return Err(response_error("Failed to create folder", resp).await);
} }
Ok(()) Ok(())
} }
+5 -5
View File
@@ -1,8 +1,8 @@
use crate::cache::{create_authenticated_conn, load_cache_with_token_refresh}; use crate::cache::{create_authenticated_conn, load_cache_with_token_refresh};
use crate::commands::shared::{ use crate::commands::shared::{
find_file_by_name, find_folder, find_lab_in_cache, find_subfolder_by_name, nfc, find_file_by_name, find_folder, find_laboratory, find_subfolder_by_name, nfc, parse_remote_path,
parse_remote_path,
}; };
use crate::error::response_error;
use anyhow::bail; use anyhow::bail;
pub async fn mv(src_path: &str, dest_path: &str) -> Result<(), anyhow::Error> { pub async fn mv(src_path: &str, dest_path: &str) -> Result<(), anyhow::Error> {
@@ -19,7 +19,7 @@ pub async fn mv(src_path: &str, dest_path: &str) -> Result<(), anyhow::Error> {
let cache = load_cache_with_token_refresh(&s_remote).await?; let cache = load_cache_with_token_refresh(&s_remote).await?;
let conn = create_authenticated_conn(&s_remote, &cache)?; let conn = create_authenticated_conn(&s_remote, &cache)?;
let lab = find_lab_in_cache(&cache, &s_lab)?; let lab = find_laboratory(&conn, Some(&cache), &s_lab).await?;
let lab_id = lab.id; let lab_id = lab.id;
// Split source path into parent directory and target name // Split source path into parent directory and target name
@@ -62,7 +62,7 @@ pub async fn mv(src_path: &str, dest_path: &str) -> Result<(), anyhow::Error> {
.post_json(&format!("v3/files/{}/move/", src_file_id), &body) .post_json(&format!("v3/files/{}/move/", src_file_id), &body)
.await?; .await?;
if !resp.status().is_success() { if !resp.status().is_success() {
bail!("Move failed: {}", resp.status()); return Err(response_error("Move failed", resp).await);
} }
return Ok(()); return Ok(());
} }
@@ -99,7 +99,7 @@ pub async fn mv(src_path: &str, dest_path: &str) -> Result<(), anyhow::Error> {
.post_json(&format!("v3/folders/{}/move/", src_folder_id), &body) .post_json(&format!("v3/folders/{}/move/", src_folder_id), &body)
.await?; .await?;
if !resp.status().is_success() { if !resp.status().is_success() {
bail!("Move failed: {}", resp.status()); return Err(response_error("Move failed", resp).await);
} }
Ok(()) Ok(())
} }
+5 -4
View File
@@ -1,7 +1,8 @@
use crate::cache::{create_authenticated_conn, load_cache_with_token_refresh}; use crate::cache::{create_authenticated_conn, load_cache_with_token_refresh};
use crate::commands::shared::{ use crate::commands::shared::{
find_file_by_name, find_folder, find_lab_in_cache, find_subfolder_by_name, parse_remote_path, find_file_by_name, find_folder, find_laboratory, find_subfolder_by_name, parse_remote_path,
}; };
use crate::error::response_error;
use anyhow::{anyhow, bail}; use anyhow::{anyhow, bail};
pub async fn rm(remote_path: &str, recursive: bool) -> Result<(), anyhow::Error> { pub async fn rm(remote_path: &str, recursive: bool) -> Result<(), anyhow::Error> {
@@ -22,7 +23,7 @@ pub async fn rm(remote_path: &str, recursive: bool) -> Result<(), anyhow::Error>
let cache = load_cache_with_token_refresh(&remote).await?; let cache = load_cache_with_token_refresh(&remote).await?;
let conn = create_authenticated_conn(&remote, &cache)?; let conn = create_authenticated_conn(&remote, &cache)?;
let lab = find_lab_in_cache(&cache, &labname)?; let lab = find_laboratory(&conn, Some(&cache), &labname).await?;
let parent_folder = find_folder(&conn, lab.id, parent_path, None).await?; let parent_folder = find_folder(&conn, lab.id, parent_path, None).await?;
// Check if target is a file // Check if target is a file
@@ -30,7 +31,7 @@ pub async fn rm(remote_path: &str, recursive: bool) -> Result<(), anyhow::Error>
if let Some(file) = find_file_by_name(&files, target_name) { if let Some(file) = find_file_by_name(&files, target_name) {
let resp = conn.delete(&format!("v3/files/{}/", file.id)).await?; let resp = conn.delete(&format!("v3/files/{}/", file.id)).await?;
if !resp.status().is_success() { if !resp.status().is_success() {
bail!("Failed to delete file: {}", resp.status()); return Err(response_error("Failed to delete file", resp).await);
} }
return Ok(()); return Ok(());
} }
@@ -47,7 +48,7 @@ pub async fn rm(remote_path: &str, recursive: bool) -> Result<(), anyhow::Error>
) )
.await?; .await?;
if !resp.status().is_success() { if !resp.status().is_success() {
bail!("Failed to delete folder: {}", resp.status()); return Err(response_error("Failed to delete folder", resp).await);
} }
return Ok(()); return Ok(());
} }
+102 -2
View File
@@ -48,6 +48,25 @@ fn is_newer(current: &str, latest: &str) -> bool {
false false
} }
/// Read the digest out of a `sha256sum` line: the hex digest, then the file it covers.
fn parse_sha256_line(text: &str) -> Option<String> {
let digest = text.split_whitespace().next()?.to_ascii_lowercase();
let is_hex = digest.len() == 64 && digest.chars().all(|c| c.is_ascii_hexdigit());
is_hex.then_some(digest)
}
/// Hex SHA-256 of a slice, in the form `sha256sum` prints.
fn sha256_hex(bytes: &[u8]) -> String {
use sha2::{Digest, Sha256};
let mut hasher = Sha256::new();
hasher.update(bytes);
hasher
.finalize()
.iter()
.map(|b| format!("{:02x}", b))
.collect()
}
/// Extract the binary named `bin_name` from a `.tar.gz` archive at `archive_path` /// Extract the binary named `bin_name` from a `.tar.gz` archive at `archive_path`
/// and write it to `dest_path`. /// and write it to `dest_path`.
fn extract_from_tar_gz( fn extract_from_tar_gz(
@@ -84,7 +103,7 @@ fn extract_from_zip(archive_path: &Path, bin_name: &str, dest_path: &Path) -> an
for i in 0..archive.len() { for i in 0..archive.len() {
let mut entry = archive.by_index(i)?; let mut entry = archive.by_index(i)?;
let entry_name = entry.name().to_owned(); let entry_name = entry.name()?.into_owned();
let file_name = Path::new(&entry_name) let file_name = Path::new(&entry_name)
.file_name() .file_name()
.and_then(|n| n.to_str()) .and_then(|n| n.to_str())
@@ -138,10 +157,11 @@ pub async fn selfupdate(yes: bool) -> anyhow::Result<()> {
println!("New version available: {latest_version}"); println!("New version available: {latest_version}");
// Find the asset matching the current build target. // Find the asset matching the current build target.
// The checksum asset carries the target in its name too, so say which one is wanted.
let asset = release let asset = release
.assets .assets
.iter() .iter()
.find(|a| a.name.contains(BUILD_TARGET)) .find(|a| a.name.contains(BUILD_TARGET) && !a.name.ends_with(".sha256"))
.ok_or_else(|| { .ok_or_else(|| {
let names: Vec<&str> = release.assets.iter().map(|a| a.name.as_str()).collect(); let names: Vec<&str> = release.assets.iter().map(|a| a.name.as_str()).collect();
anyhow!( anyhow!(
@@ -186,6 +206,54 @@ pub async fn selfupdate(yes: bool) -> anyhow::Result<()> {
} }
let bytes = download_resp.bytes().await?; let bytes = download_resp.bytes().await?;
// This binary is about to replace the one the user is running, so what arrived has to
// be what the release says it is. Transport already proves who served it; the digest
// proves the archive was not swapped or truncated on the way.
match release
.assets
.iter()
.find(|a| a.name == format!("{}.sha256", asset.name))
{
Some(checksum_asset) => {
let mut checksum_req = client
.get(&checksum_asset.browser_download_url)
.header(USER_AGENT, format!("mdrs/{current_version}"));
if let Ok(token) = env::var("GITEA_TOKEN") {
checksum_req = checksum_req.header(AUTHORIZATION, format!("Bearer {token}"));
}
let checksum_resp = checksum_req.send().await?;
if !checksum_resp.status().is_success() {
bail!(
"Failed to download checksum: HTTP {}",
checksum_resp.status()
);
}
let expected = parse_sha256_line(&checksum_resp.text().await?)
.ok_or_else(|| anyhow!("Checksum asset '{}' is malformed", checksum_asset.name))?;
let actual = sha256_hex(&bytes);
if actual != expected {
bail!(
"Checksum mismatch for '{}': expected {}, got {}. The download was not what \
the release publishes, so this binary has not been replaced.",
asset.name,
expected,
actual
);
}
println!("Checksum verified.");
}
None => {
// Releases built before the workflow published checksums have none to check
// against. Say so rather than letting the absence pass for a verified download.
eprintln!(
"Warning: release {latest_version} publishes no checksum for '{}', \
so the download could not be verified.",
asset.name
);
}
}
std::fs::write(&archive_path, &bytes)?; std::fs::write(&archive_path, &bytes)?;
// Extract the binary from the archive. // Extract the binary from the archive.
@@ -216,3 +284,35 @@ pub async fn selfupdate(yes: bool) -> anyhow::Result<()> {
println!("Successfully updated to version {latest_version}."); println!("Successfully updated to version {latest_version}.");
Ok(()) Ok(())
} }
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_sha256sum_line_yields_its_digest() {
let digest = "a".repeat(64);
assert_eq!(
parse_sha256_line(&format!(
"{digest} mdrs-2.0.1-x86_64-unknown-linux-musl.tar.gz\n"
)),
Some(digest)
);
}
#[test]
fn a_line_that_is_not_a_digest_is_refused() {
for text in ["", "not-a-digest file", "abc123 file"] {
assert_eq!(parse_sha256_line(text), None, "{text:?} should be refused");
}
}
#[test]
fn the_digest_matches_what_sha256sum_prints() {
// Verified against `printf mdrs | sha256sum`.
assert_eq!(
sha256_hex(b"mdrs"),
"bd9845248df877e411ec8bef10b823bd4c0900a530157eedfdfbfb63ccbde2fa"
);
}
}
+156 -41
View File
@@ -1,6 +1,7 @@
use crate::cache::{Cache, CacheLaboratory}; use crate::cache::{Cache, CacheLaboratory};
use crate::connection::ApiRequestLimiter; use crate::connection::ApiRequestLimiter;
use crate::connection::MDRSConnection; use crate::connection::MDRSConnection;
use crate::error::FolderLockedError;
use crate::models::file::File; use crate::models::file::File;
use crate::models::folder::{FolderDetail, FolderSimple}; use crate::models::folder::{FolderDetail, FolderSimple};
use crate::models::laboratory::Laboratory; use crate::models::laboratory::Laboratory;
@@ -94,14 +95,11 @@ pub fn parse_doi_remote_path(remote_path: &str) -> Result<(String, String, Strin
Ok((remote, doi.to_string(), subpath.to_string())) Ok((remote, doi.to_string(), subpath.to_string()))
} }
/// Resolve a DOI string to a (FolderDetail, Laboratory) pair. /// Resolve a DOI string to a (FolderDetail, Laboratory) pair. Only the DOI-to-folder-id
/// /// lookup is DOI-specific; subsequent folder and file access uses the common API methods.
/// Calls GET v3/doi/{id}/ to look up the folder ID, then fetches the full
/// folder detail (which carries `laboratory_id`) and resolves the laboratory.
pub async fn find_folder_by_doi( pub async fn find_folder_by_doi(
conn: &MDRSConnection, conn: &MDRSConnection,
doi: &str, doi: &str,
password: Option<&str>,
) -> Result<(FolderDetail, Laboratory), anyhow::Error> { ) -> Result<(FolderDetail, Laboratory), anyhow::Error> {
// Strip any trailing slash from the DOI before extracting the suffix ID. // Strip any trailing slash from the DOI before extracting the suffix ID.
let doi_clean = doi.trim_end_matches('/'); let doi_clean = doi.trim_end_matches('/');
@@ -120,26 +118,11 @@ pub async fn find_folder_by_doi(
} }
let folder_id = &doi_resp.folder.id; let folder_id = &doi_resp.folder.id;
// Fetch the full folder detail; laboratory_id is available here.
let folder = conn let folder = conn
.retrieve_folder(folder_id) .retrieve_folder(folder_id)
.await .await
.map_err(|e| anyhow!("Failed to retrieve folder for DOI `{}`: {}", doi_clean, e))?; .map_err(|e| anyhow!("Failed to retrieve folder for DOI `{}`: {}", doi_clean, e))?;
// Handle password-locked folder.
if folder.lock {
match password {
None => {
bail!(
"Folder for DOI `{}` is locked. Use -p/--password to provide a password.",
doi_clean
);
}
Some(pw) => conn.folder_auth(folder_id, pw).await?,
}
}
// Resolve laboratory using the laboratory_id from the folder detail. // Resolve laboratory using the laboratory_id from the folder detail.
let lab_id = folder.laboratory_id; let lab_id = folder.laboratory_id;
let lab = conn let lab = conn
@@ -158,6 +141,10 @@ pub async fn find_folder_by_doi(
// --------------------------------------------------------------------------- // ---------------------------------------------------------------------------
/// Parse "remote:/labname/path/" into (remote, labname, folder_path). /// Parse "remote:/labname/path/" into (remote, labname, folder_path).
///
/// The path is put in one form before anything is done with it: repeated and trailing
/// separators go, `.` segments go, and a `..` is refused rather than sent on. The Python
/// client does the same, and both talk to the same server.
pub fn parse_remote_path(remote_path: &str) -> Result<(String, String, String), anyhow::Error> { pub fn parse_remote_path(remote_path: &str) -> Result<(String, String, String), anyhow::Error> {
let parts: Vec<&str> = remote_path.splitn(2, ':').collect(); let parts: Vec<&str> = remote_path.splitn(2, ':').collect();
if parts.len() != 2 { if parts.len() != 2 {
@@ -168,12 +155,22 @@ pub fn parse_remote_path(remote_path: &str) -> Result<(String, String, String),
if !rest.starts_with('/') { if !rest.starts_with('/') {
bail!("Path must be absolute (start with '/')"); bail!("Path must be absolute (start with '/')");
} }
let folder_parts: Vec<&str> = rest.trim_start_matches('/').splitn(2, '/').collect(); let mut segments = Vec::new();
let labname = folder_parts[0].to_string(); for segment in rest.split('/') {
let path = if folder_parts.len() > 1 && !folder_parts[1].is_empty() { match segment {
format!("/{}", folder_parts[1].trim_end_matches('/')) "" | "." => continue,
} else { ".." => bail!("Path traversal found."),
other => segments.push(other),
}
}
if segments.is_empty() {
bail!("Laboratory name is missing from `{}`.", remote_path);
}
let labname = segments.remove(0).to_string();
let path = if segments.is_empty() {
"/".to_string() "/".to_string()
} else {
format!("/{}", segments.join("/"))
}; };
Ok((remote, labname, path)) Ok((remote, labname, path))
} }
@@ -202,8 +199,9 @@ pub async fn find_laboratory(
cache: Option<&Cache>, cache: Option<&Cache>,
labname: &str, labname: &str,
) -> Result<Laboratory, anyhow::Error> { ) -> Result<Laboratory, anyhow::Error> {
if let Some(cache) = cache { if let Some(cache) = cache
if let Ok(lab) = find_lab_in_cache(cache, labname) { && let Ok(lab) = find_lab_in_cache(cache, labname)
{
return Ok(Laboratory { return Ok(Laboratory {
id: lab.id, id: lab.id,
name: lab.name.clone(), name: lab.name.clone(),
@@ -211,7 +209,6 @@ pub async fn find_laboratory(
full_name: lab.full_name.clone(), full_name: lab.full_name.clone(),
}); });
} }
}
conn.list_laboratories() conn.list_laboratories()
.await? .await?
@@ -257,10 +254,7 @@ pub async fn find_folder(
if folder_simple.lock { if folder_simple.lock {
match password { match password {
None => { None => {
bail!( return Err(FolderLockedError::new(path).with_password_hint().into());
"Folder `{}` is locked. Use -p/--password to provide a password.",
path
);
} }
Some(pw) => conn.folder_auth(&folder_simple.id, pw).await?, Some(pw) => conn.folder_auth(&folder_simple.id, pw).await?,
} }
@@ -295,10 +289,7 @@ pub async fn find_folder_limited(
if folder_simple.lock { if folder_simple.lock {
match password { match password {
None => { None => {
bail!( return Err(FolderLockedError::new(path).with_password_hint().into());
"Folder `{}` is locked. Use -p/--password to provide a password.",
path
);
} }
Some(pw) => { Some(pw) => {
conn.folder_auth_limited(&folder_simple.id, pw, limiter) conn.folder_auth_limited(&folder_simple.id, pw, limiter)
@@ -338,7 +329,7 @@ pub fn find_subfolder_by_name<'a>(
/// Format an ISO 8601 timestamp as "YYYY/MM/DD HH:MM:SS". /// Format an ISO 8601 timestamp as "YYYY/MM/DD HH:MM:SS".
pub fn fmt_datetime(iso: &str) -> String { pub fn fmt_datetime(iso: &str) -> String {
let s = iso.trim(); let s = iso.trim();
let s = if let Some(pos) = s[10..].find(|c: char| c == '+' || c == '-') { let s = if let Some(pos) = s[10..].find(['+', '-']) {
&s[..10 + pos] &s[..10 + pos]
} else { } else {
s.trim_end_matches('Z') s.trim_end_matches('Z')
@@ -361,10 +352,10 @@ pub async fn resolve_remote_folder(
remote_path: &str, remote_path: &str,
password: Option<&str>, password: Option<&str>,
) -> Result<(FolderDetail, Laboratory), anyhow::Error> { ) -> Result<(FolderDetail, Laboratory), anyhow::Error> {
let path_component = remote_path.splitn(2, ':').nth(1).unwrap_or(""); let path_component = remote_path.split_once(':').map(|x| x.1).unwrap_or("");
if is_doi(path_component) { if is_doi(path_component) {
let (_, doi, subpath) = parse_doi_remote_path(remote_path)?; let (_, doi, subpath) = parse_doi_remote_path(remote_path)?;
let (doi_folder, lab) = find_folder_by_doi(conn, &doi, password).await?; let (doi_folder, lab) = find_folder_by_doi(conn, &doi).await?;
if subpath.is_empty() { if subpath.is_empty() {
Ok((doi_folder, lab)) Ok((doi_folder, lab))
} else { } else {
@@ -395,10 +386,10 @@ pub async fn resolve_remote_file(
remote_path: &str, remote_path: &str,
password: Option<&str>, password: Option<&str>,
) -> Result<(FolderDetail, String), anyhow::Error> { ) -> Result<(FolderDetail, String), anyhow::Error> {
let path_component = remote_path.splitn(2, ':').nth(1).unwrap_or(""); let path_component = remote_path.split_once(':').map(|x| x.1).unwrap_or("");
if is_doi(path_component) { if is_doi(path_component) {
let (_, doi, subpath) = parse_doi_remote_path(remote_path)?; let (_, doi, subpath) = parse_doi_remote_path(remote_path)?;
let (doi_folder, lab) = find_folder_by_doi(conn, &doi, password).await?; let (doi_folder, lab) = find_folder_by_doi(conn, &doi).await?;
let subpath_clean = subpath.trim_end_matches('/'); let subpath_clean = subpath.trim_end_matches('/');
if subpath_clean.is_empty() { if subpath_clean.is_empty() {
bail!("DOI path must point to a file, not a folder."); bail!("DOI path must point to a file, not a folder.");
@@ -441,6 +432,51 @@ mod tests {
use tokio::io::{AsyncReadExt, AsyncWriteExt}; use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener; use tokio::net::TcpListener;
fn json_server(
exchanges: Vec<(&'static str, &'static str)>,
) -> (MDRSConnection, tokio::task::JoinHandle<()>) {
let listener = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
listener.set_nonblocking(true).unwrap();
let addr = listener.local_addr().unwrap();
let listener = TcpListener::from_std(listener).unwrap();
let server = tokio::spawn(async move {
for (request_line, body) in exchanges {
let (mut stream, _) = listener.accept().await.unwrap();
let mut buf = [0u8; 8192];
let n = stream.read(&mut buf).await.unwrap();
let request = String::from_utf8_lossy(&buf[..n]);
assert!(request.starts_with(request_line), "request was: {request}");
let response = format!(
"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
body.len(),
body
);
stream.write_all(response.as_bytes()).await.unwrap();
}
});
(MDRSConnection::new(&format!("http://{addr}")), server)
}
const DOI: &str = "10.60178/cbs.20260429-001";
const DOI_RESPONSE: &str =
r#"{"id":"20260429-001","doi":"10.60178/cbs.20260429-001","folder":{"id":"f1"}}"#;
const LABORATORIES_RESPONSE: &str =
r#"[{"id":1,"name":"mylab","pi_name":"PI","full_name":"My Laboratory"}]"#;
const LOCKED_DOI_FOLDER: &str = r#"{
"id":"f1","pid":null,"name":"root","access_level":4,"lock":true,
"size":0,"laboratory_id":1,"description":"",
"created_at":"2026-01-01T00:00:00+09:00",
"updated_at":"2026-01-01T00:00:00+09:00"
}"#;
const PUBLIC_DOI_FOLDER: &str = r#"{
"id":"f1","pid":null,"name":"root","access_level":2,"lock":false,
"size":0,"laboratory_id":1,"description":"",
"created_at":"2026-01-01T00:00:00+09:00",
"updated_at":"2026-01-01T00:00:00+09:00",
"sub_folders":[],"path":"/mylab/root/"
}"#;
#[tokio::test] #[tokio::test]
async fn find_laboratory_falls_back_to_api_without_authorization() { async fn find_laboratory_falls_back_to_api_without_authorization() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap(); let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
@@ -473,6 +509,85 @@ mod tests {
server.await.unwrap(); server.await.unwrap();
} }
#[tokio::test]
async fn public_doi_folder_is_returned_without_folder_authentication() {
let (conn, server) = json_server(vec![
("GET /v3/doi/20260429-001/ HTTP/1.1", DOI_RESPONSE),
("GET /v3/folders/f1/ HTTP/1.1", PUBLIC_DOI_FOLDER),
("GET /v3/laboratories/ HTTP/1.1", LABORATORIES_RESPONSE),
]);
let (folder, lab) = find_folder_by_doi(&conn, DOI).await.unwrap();
server.await.unwrap();
assert_eq!(folder.id, "f1");
assert_eq!(folder.path, "/mylab/root/");
assert_eq!(lab.name, "mylab");
}
#[tokio::test]
async fn short_locked_record_after_doi_lookup_uses_the_common_folder_error() {
let (conn, server) = json_server(vec![
("GET /v3/doi/20260429-001/ HTTP/1.1", DOI_RESPONSE),
("GET /v3/folders/f1/ HTTP/1.1", LOCKED_DOI_FOLDER),
]);
let err = find_folder_by_doi(&conn, DOI).await.unwrap_err();
server.await.unwrap();
assert_eq!(
err.to_string(),
"Failed to retrieve folder for DOI `10.60178/cbs.20260429-001`: Folder `root` is locked."
);
}
// ------------------------------------------------------------------
// Remote path parsing
// ------------------------------------------------------------------
#[test]
fn parse_remote_path_splits_remote_lab_and_path() {
let (remote, lab, path) = parse_remote_path("neurodata:/mylab/a/b/").unwrap();
assert_eq!(
(remote.as_str(), lab.as_str(), path.as_str()),
("neurodata", "mylab", "/a/b")
);
}
#[test]
fn parse_remote_path_gives_the_lab_root_its_own_form() {
let (_, lab, path) = parse_remote_path("neurodata:/mylab").unwrap();
assert_eq!((lab.as_str(), path.as_str()), ("mylab", "/"));
}
/// Both clients talk to the same server, so a doubled separator or a `.` segment has
/// to reach it as the same path from either one.
#[test]
fn parse_remote_path_collapses_redundant_segments() {
let (_, lab, path) = parse_remote_path("neurodata://mylab//a/./b//").unwrap();
assert_eq!((lab.as_str(), path.as_str()), ("mylab", "/a/b"));
}
#[test]
fn parse_remote_path_refuses_a_parent_segment() {
for path in [
"neurodata:/mylab/../other",
"neurodata:/mylab/a/..",
"neurodata:/../mylab",
] {
let err = parse_remote_path(path).unwrap_err();
assert!(
err.to_string().contains("Path traversal found."),
"{path} should be refused"
);
}
}
#[test]
fn parse_remote_path_refuses_a_path_without_a_laboratory() {
assert!(parse_remote_path("neurodata:/").is_err());
}
// ------------------------------------------------------------------ // ------------------------------------------------------------------
// DOI helper unit tests // DOI helper unit tests
// ------------------------------------------------------------------ // ------------------------------------------------------------------
+16 -20
View File
@@ -1,6 +1,6 @@
use crate::cache::{create_authenticated_conn, load_cache_with_token_refresh}; use crate::cache::{create_authenticated_conn, load_cache_with_token_refresh};
use crate::commands::shared::{ use crate::commands::shared::{
find_file_by_name, find_folder_limited, find_lab_in_cache, nfc, parse_remote_path, find_file_by_name, find_folder_limited, find_laboratory, nfc, parse_remote_path,
}; };
use crate::connection::{ApiRequestLimiter, MDRSConnection}; use crate::connection::{ApiRequestLimiter, MDRSConnection};
use crate::models::folder::FolderSimple; use crate::models::folder::FolderSimple;
@@ -20,7 +20,7 @@ pub async fn upload(
let cache = load_cache_with_token_refresh(&remote).await?; let cache = load_cache_with_token_refresh(&remote).await?;
let conn = Arc::new(create_authenticated_conn(&remote, &cache)?); let conn = Arc::new(create_authenticated_conn(&remote, &cache)?);
let limiter = ApiRequestLimiter::new(crate::settings::SETTINGS.concurrent); let limiter = ApiRequestLimiter::new(crate::settings::SETTINGS.concurrent);
let lab = find_lab_in_cache(&cache, &labname)?; let lab = find_laboratory(&conn, Some(&cache), &labname).await?;
let dest_folder = find_folder_limited(&conn, &limiter, lab.id, &r_path, None).await?; let dest_folder = find_folder_limited(&conn, &limiter, lab.id, &r_path, None).await?;
// Normalize local_path: resolve to an absolute canonical path so that // Normalize local_path: resolve to an absolute canonical path so that
@@ -35,14 +35,13 @@ pub async fn upload(
let remote_files = conn let remote_files = conn
.list_all_files_limited(&dest_folder.id, &limiter) .list_all_files_limited(&dest_folder.id, &limiter)
.await?; .await?;
if skip_if_exists { if skip_if_exists
if let Some(rf) = find_file_by_name(&remote_files, &filename) { && let Some(rf) = find_file_by_name(&remote_files, &filename)
if rf.size == std::fs::metadata(local)?.len() { && rf.size == std::fs::metadata(local)?.len()
{
println!("{}{}", dest_folder.path, filename); println!("{}{}", dest_folder.path, filename);
return Ok(()); return Ok(());
} }
}
}
conn.upload_file_limited(&dest_folder.id, &local.to_string_lossy(), &limiter) conn.upload_file_limited(&dest_folder.id, &local.to_string_lossy(), &limiter)
.await?; .await?;
println!("{}{}", dest_folder.path, filename); println!("{}{}", dest_folder.path, filename);
@@ -219,16 +218,14 @@ async fn process_upload_folder(
let mut upload_jobs = Vec::new(); let mut upload_jobs = Vec::new();
for file_path in files { for file_path in files {
let filename = file_path.file_name().unwrap().to_string_lossy().to_string(); let filename = file_path.file_name().unwrap().to_string_lossy().to_string();
if skip_if_exists { if skip_if_exists
if let Some(rf) = find_file_by_name(&remote_files, &filename) { && let Some(rf) = find_file_by_name(&remote_files, &filename)
if let Ok(meta) = std::fs::metadata(&file_path) { && let Ok(meta) = std::fs::metadata(&file_path)
if rf.size == meta.len() { && rf.size == meta.len()
{
println!("{}{}", folder_detail.path, filename); println!("{}{}", folder_detail.path, filename);
continue; continue;
} }
}
}
}
upload_jobs.push(UploadJob { upload_jobs.push(UploadJob {
folder_id: remote_id.clone(), folder_id: remote_id.clone(),
file_path: file_path.to_string_lossy().to_string(), file_path: file_path.to_string_lossy().to_string(),
@@ -267,12 +264,12 @@ async fn drive_upload_tasks(
} }
} }
(true, false) => { (true, false) => {
if let Some(result) = upload_tasks.join_next().await { if let Some(result) = upload_tasks.join_next().await
if let Err(err) = flatten_join_result(result) { && let Err(err) = flatten_join_result(result)
{
errors.push(err.to_string()); errors.push(err.to_string());
} }
} }
}
(false, false) => { (false, false) => {
tokio::select! { tokio::select! {
result = folder_tasks.join_next() => { result = folder_tasks.join_next() => {
@@ -289,8 +286,8 @@ async fn drive_upload_tasks(
} }
} }
result = upload_tasks.join_next() => { result = upload_tasks.join_next() => {
if let Some(result) = result { if let Some(result) = result
if let Err(err) = flatten_join_result(result) { && let Err(err) = flatten_join_result(result) {
errors.push(err.to_string()); errors.push(err.to_string());
} }
} }
@@ -298,7 +295,6 @@ async fn drive_upload_tasks(
} }
} }
} }
}
} }
fn handle_upload_folder_result( fn handle_upload_folder_result(
+10 -5
View File
@@ -1,9 +1,14 @@
use crate::cache::create_readonly_conn;
/// Ask the server who it thinks is calling.
///
/// The cached name is only what was true at login: an account disabled or removed since
/// then would still answer from the cache, which is the one thing this command exists to
/// tell the user. A session the server no longer honours reads as anonymous.
pub async fn whoami(remote: &str) -> Result<(), anyhow::Error> { pub async fn whoami(remote: &str) -> Result<(), anyhow::Error> {
match crate::cache::load_cache(remote) { let (conn, _cache) = create_readonly_conn(remote).await?;
Ok(cache) => match cache.user { match conn.get_current_user().await {
Some(user) => println!("{}", user.username), Ok(user) => println!("{}", user.username),
None => println!("(Anonymous)"),
},
Err(_) => println!("(Anonymous)"), Err(_) => println!("(Anonymous)"),
} }
Ok(()) Ok(())
+162 -31
View File
@@ -1,9 +1,14 @@
use anyhow::bail;
use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, HeaderValue, USER_AGENT}; use reqwest::header::{ACCEPT, AUTHORIZATION, HeaderMap, HeaderValue, USER_AGENT};
use reqwest::{Client, Response}; use reqwest::{Client, Response};
use serde::Serialize; use serde::Serialize;
use std::sync::Arc; use std::sync::Arc;
use tokio::sync::{OwnedSemaphorePermit, Semaphore}; use tokio::sync::{OwnedSemaphorePermit, Semaphore};
/// Shown when a request was refused twice for a token that was current when it left.
pub const SERVER_BUSY_MESSAGE: &str = "The server took too long to start handling the request and may be overloaded. \
Try again, or reduce the number of parallel transfers.";
fn build_user_agent() -> String { fn build_user_agent() -> String {
let info = os_info::get(); let info = os_info::get();
let mut parts = vec![info.os_type().to_string()]; let mut parts = vec![info.os_type().to_string()];
@@ -64,7 +69,12 @@ impl MDRSConnection {
MDRSConnection { MDRSConnection {
remote: None, remote: None,
url: url.to_string(), url: url.to_string(),
client: Client::new(), // Folder authentication is returned in a cookie and must survive subsequent
// retrieves. Clones share the client, and therefore its cookie store.
client: Client::builder()
.cookie_store(true)
.build()
.expect("failed to build the HTTP client"),
token: None, token: None,
} }
} }
@@ -90,6 +100,12 @@ impl MDRSConnection {
} }
} }
/// Same as `connection_with_fresh_token`, for callers that manage their own retry
/// because the request body cannot simply be sent twice.
pub async fn connection_with_fresh_token_for_retry(&self) -> Result<Self, anyhow::Error> {
self.connection_with_fresh_token().await
}
async fn connection_with_fresh_token(&self) -> Result<Self, anyhow::Error> { async fn connection_with_fresh_token(&self) -> Result<Self, anyhow::Error> {
match (&self.remote, &self.token) { match (&self.remote, &self.token) {
(Some(remote), Some(_)) => { (Some(remote), Some(_)) => {
@@ -122,56 +138,87 @@ impl MDRSConnection {
headers headers
} }
pub async fn get(&self, path: &str) -> Result<Response, anyhow::Error> { /// Send a request, and send it once more if the server found the access token
/// expired. A request can wait in the server's queue for longer than the token it
/// was sent with lives, so a refusal here need not mean the session is over.
///
/// The retry goes back through `connection_with_fresh_token`, which re-reads the
/// cache under the lock: if another process refreshed while this request waited,
/// its token is reused rather than a second one being minted.
async fn send_with_retry<F>(&self, build: F) -> Result<Response, anyhow::Error>
where
F: Fn(&MDRSConnection) -> reqwest::RequestBuilder,
{
let conn = self.connection_with_fresh_token().await?; let conn = self.connection_with_fresh_token().await?;
Ok(conn let response = build(&conn).send().await?;
.client if response.status() != reqwest::StatusCode::UNAUTHORIZED {
return Ok(response);
}
// Only a stale access token is worth a second attempt, and the sign of one is a
// different token coming back. A wrong folder password, an anonymous request, or
// a session that has really ended all leave it untouched, and those refusals
// belong to the caller to report.
let retry_conn = self.connection_with_fresh_token().await?;
if retry_conn.token == conn.token {
return Ok(response);
}
let response = build(&retry_conn).send().await?;
if response.status() == reqwest::StatusCode::UNAUTHORIZED {
// Refused twice, the second time with a token that was current when it left.
// The session is fine; the server is not starting requests before their
// credentials lapse, which is worth saying plainly rather than sending the
// user off to log in again.
bail!(SERVER_BUSY_MESSAGE);
}
Ok(response)
}
pub async fn get(&self, path: &str) -> Result<Response, anyhow::Error> {
self.send_with_retry(|conn| {
conn.client
.get(conn.build_url(path)) .get(conn.build_url(path))
.headers(conn.prepare_headers()) .headers(conn.prepare_headers())
.send() })
.await?) .await
} }
pub async fn get_with_query<Q>(&self, path: &str, query: &Q) -> Result<Response, anyhow::Error> pub async fn get_with_query<Q>(&self, path: &str, query: &Q) -> Result<Response, anyhow::Error>
where where
Q: Serialize + ?Sized, Q: Serialize + ?Sized,
{ {
let conn = self.connection_with_fresh_token().await?; self.send_with_retry(|conn| {
Ok(conn conn.client
.client
.get(conn.build_url(path)) .get(conn.build_url(path))
.headers(conn.prepare_headers()) .headers(conn.prepare_headers())
.query(query) .query(query)
.send() })
.await?) .await
} }
pub async fn get_url(&self, url: &str) -> Result<Response, anyhow::Error> { pub async fn get_url(&self, url: &str) -> Result<Response, anyhow::Error> {
let conn = self.connection_with_fresh_token().await?; self.send_with_retry(|conn| {
Ok(conn conn.client
.client
.get(if url.starts_with("http") { .get(if url.starts_with("http") {
url.to_string() url.to_string()
} else { } else {
conn.build_url(url) conn.build_url(url)
}) })
.headers(conn.prepare_headers()) .headers(conn.prepare_headers())
.send() })
.await?) .await
} }
pub async fn post_json<B>(&self, path: &str, body: &B) -> Result<Response, anyhow::Error> pub async fn post_json<B>(&self, path: &str, body: &B) -> Result<Response, anyhow::Error>
where where
B: Serialize + ?Sized, B: Serialize + ?Sized,
{ {
let conn = self.connection_with_fresh_token().await?; self.send_with_retry(|conn| {
Ok(conn conn.client
.client
.post(conn.build_url(path)) .post(conn.build_url(path))
.headers(conn.prepare_headers()) .headers(conn.prepare_headers())
.json(body) .json(body)
.send() })
.await?) .await
} }
pub async fn post_multipart( pub async fn post_multipart(
@@ -190,13 +237,12 @@ impl MDRSConnection {
} }
pub async fn delete(&self, path: &str) -> Result<Response, anyhow::Error> { pub async fn delete(&self, path: &str) -> Result<Response, anyhow::Error> {
let conn = self.connection_with_fresh_token().await?; self.send_with_retry(|conn| {
Ok(conn conn.client
.client
.delete(conn.build_url(path)) .delete(conn.build_url(path))
.headers(conn.prepare_headers()) .headers(conn.prepare_headers())
.send() })
.await?) .await
} }
pub async fn delete_with_query<Q>( pub async fn delete_with_query<Q>(
@@ -207,13 +253,98 @@ impl MDRSConnection {
where where
Q: Serialize + ?Sized, Q: Serialize + ?Sized,
{ {
let conn = self.connection_with_fresh_token().await?; self.send_with_retry(|conn| {
Ok(conn conn.client
.client
.delete(conn.build_url(path)) .delete(conn.build_url(path))
.headers(conn.prepare_headers()) .headers(conn.prepare_headers())
.query(query) .query(query)
.send() })
.await?) .await
}
}
#[cfg(test)]
mod retry_tests {
use super::*;
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
/// A refusal that no new token could answer belongs to the caller: an anonymous
/// request, a wrong folder password and an ended session all look like this, and
/// sending the same thing twice would only repeat the refusal.
#[tokio::test]
async fn a_refusal_is_handed_back_when_the_token_cannot_change() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut buf = [0u8; 4096];
let _ = stream.read(&mut buf).await.unwrap();
stream
.write_all(
b"HTTP/1.1 401 Unauthorized\r\ncontent-length: 0\r\nconnection: close\r\n\r\n",
)
.await
.unwrap();
});
// No remote and no token, so nothing can be refreshed and the request must not
// be sent a second time. The stub answers once and would hang on a retry.
let conn = MDRSConnection::new(&format!("http://{addr}"));
let response = conn.get("v3/anything/").await.unwrap();
server.await.unwrap();
assert_eq!(response.status(), reqwest::StatusCode::UNAUTHORIZED);
}
#[tokio::test]
async fn folder_auth_cookie_is_shared_with_a_fresh_token_connection() {
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut buf = [0u8; 4096];
let _ = stream.read(&mut buf).await.unwrap();
stream
.write_all(
b"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\nset-cookie: dirtoken=unlocked; Path=/\r\ncontent-length: 2\r\nconnection: close\r\n\r\n{}",
)
.await
.unwrap();
let (mut stream, _) = listener.accept().await.unwrap();
let n = stream.read(&mut buf).await.unwrap();
let request = String::from_utf8_lossy(&buf[..n]);
assert!(
request
.to_ascii_lowercase()
.contains("cookie: dirtoken=unlocked"),
"the folder-auth cookie must be sent on the next retrieve: {request}"
);
stream
.write_all(
b"HTTP/1.1 200 OK\r\ncontent-type: application/json\r\ncontent-length: 2\r\nconnection: close\r\n\r\n{}",
)
.await
.unwrap();
});
let conn = MDRSConnection::new(&format!("http://{addr}"));
let auth = conn
.post_json(
"v3/folders/f1/auth/",
&serde_json::json!({"password": "secret"}),
)
.await
.unwrap();
assert!(auth.status().is_success());
let response = conn
.with_token("new-access-token".to_string())
.get("v3/folders/f1/")
.await
.unwrap();
assert!(response.status().is_success());
server.await.unwrap();
} }
} }
+110
View File
@@ -1,3 +1,63 @@
use anyhow::anyhow;
use serde::Deserialize;
use std::fmt;
/// A folder that cannot be opened until its password has been supplied. The retrieve
/// endpoint can also report this with a successful response containing only listing fields.
#[derive(Debug)]
pub struct FolderLockedError {
message: String,
}
impl FolderLockedError {
pub fn new(name: impl Into<String>) -> Self {
Self {
message: format!("Folder `{}` is locked.", name.into()),
}
}
pub fn with_password_hint(mut self) -> Self {
self.message
.push_str(" Use -p/--password to provide a password.");
self
}
}
impl fmt::Display for FolderLockedError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for FolderLockedError {}
/// The error envelope the API answers with (drf-standardized-errors).
#[derive(Deserialize)]
struct ApiErrors {
errors: Vec<ApiError>,
}
#[derive(Deserialize)]
struct ApiError {
detail: String,
}
/// Turn a refused response into an error carrying what the server actually said.
///
/// A status code on its own leaves the user guessing. The reason - a permission, a
/// quota, a name already taken - is in the body the API sends along with it, and that
/// is the part worth showing.
pub async fn response_error(context: &str, resp: reqwest::Response) -> anyhow::Error {
let status = resp.status();
let body = resp.text().await.unwrap_or_default();
match serde_json::from_str::<ApiErrors>(&body) {
Ok(parsed) if !parsed.errors.is_empty() => {
anyhow!("{}: {}", context, parsed.errors[0].detail)
}
_ => anyhow!("{}: {}", context, status),
}
}
/// Print the error message and exit with code 2. /// Print the error message and exit with code 2.
/// JSON deserialization errors produce a friendlier message matching Python's /// JSON deserialization errors produce a friendlier message matching Python's
/// JSONDecodeError handling. /// JSONDecodeError handling.
@@ -23,3 +83,53 @@ fn is_json_error(e: &(dyn std::error::Error + 'static)) -> bool {
} }
false false
} }
#[cfg(test)]
mod response_error_tests {
use super::*;
async fn refused_with(body: &'static str, content_type: &'static str) -> String {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
use tokio::net::TcpListener;
let listener = TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = listener.local_addr().unwrap();
let server = tokio::spawn(async move {
let (mut stream, _) = listener.accept().await.unwrap();
let mut buf = [0u8; 4096];
let _ = stream.read(&mut buf).await.unwrap();
let response = format!(
"HTTP/1.1 403 Forbidden\r\ncontent-type: {}\r\ncontent-length: {}\r\nconnection: close\r\n\r\n{}",
content_type,
body.len(),
body
);
stream.write_all(response.as_bytes()).await.unwrap();
});
let resp = reqwest::get(format!("http://{addr}/")).await.unwrap();
let message = response_error("Upload failed", resp).await.to_string();
server.await.unwrap();
message
}
/// The reason the server gave is what the user needs, not the number that carried it.
#[tokio::test]
async fn the_servers_own_message_is_reported() {
let message = refused_with(
r#"{"type":"client_error","errors":[{"code":"permission_denied","detail":"You do not have permission.","attr":null}]}"#,
"application/json",
)
.await;
assert_eq!(message, "Upload failed: You do not have permission.");
}
/// A gateway that answers in HTML has nothing to quote, so the status still stands in.
#[tokio::test]
async fn the_status_stands_in_when_the_body_says_nothing() {
let message = refused_with("<html>nope</html>", "text/html").await;
assert_eq!(message, "Upload failed: 403 Forbidden");
}
}
+1 -1
View File
@@ -201,7 +201,7 @@ fn run(cli: Cli) {
} }
Commands::SelfUpdate { yes } => { Commands::SelfUpdate { yes } => {
if let Err(e) = build_rt().block_on(commands::selfupdate::selfupdate(yes)) { if let Err(e) = build_rt().block_on(commands::selfupdate::selfupdate(yes)) {
handle_error(e.into()); handle_error(e);
} }
} }
} }
+221 -22
View File
@@ -1,4 +1,19 @@
use serde::{Deserialize, Serialize}; use serde::{Deserialize, Serialize};
use std::collections::BTreeMap;
/// Project names by the bit position used in their folder access levels.
pub type ProjectNames = BTreeMap<u32, String>;
// Bits 0-2 are private/public/password, bits 3-7 are reserved, bits 8-15 select
// restrict networks, and bit 16 onward selects projects by their server-assigned positions.
pub const STORAGE_ACCESS_LEVEL: i64 = 0x0000;
pub const PRIVATE_ACCESS_LEVEL: i64 = 0x0001;
pub const PUBLIC_ACCESS_LEVEL: i64 = 0x0002;
const PASSWORD_ACCESS_LEVEL: i64 = 0x0004;
const RESERVED_ACCESS_LEVEL: i64 = 0x00f8;
const RESTRICT_SHIFT: u32 = 8;
const RESTRICT_SLOTS: u32 = 8;
const PROJECT_SHIFT: u32 = 16;
/// Lightweight folder entry returned by the list endpoint (v3/folders/?path=...&laboratory_id=...) /// Lightweight folder entry returned by the list endpoint (v3/folders/?path=...&laboratory_id=...)
#[derive(Debug, Serialize, Deserialize, Clone)] #[derive(Debug, Serialize, Deserialize, Clone)]
@@ -6,7 +21,7 @@ pub struct FolderSimple {
pub id: String, pub id: String,
pub pid: Option<String>, pub pid: Option<String>,
pub name: String, pub name: String,
pub access_level: u32, pub access_level: i64,
pub lock: bool, pub lock: bool,
pub size: u64, pub size: u64,
pub laboratory_id: u32, pub laboratory_id: u32,
@@ -16,8 +31,8 @@ pub struct FolderSimple {
} }
impl FolderSimple { impl FolderSimple {
pub fn access_level_name(&self) -> &'static str { pub fn access_level_label(&self, projects: &ProjectNames) -> String {
access_level_label(self.access_level) access_level_label_or_unknown(self.access_level, projects)
} }
} }
@@ -27,7 +42,7 @@ pub struct FolderDetail {
pub id: String, pub id: String,
pub pid: Option<String>, pub pid: Option<String>,
pub name: String, pub name: String,
pub access_level: u32, pub access_level: i64,
pub lock: bool, pub lock: bool,
pub size: u64, pub size: u64,
pub laboratory_id: u32, pub laboratory_id: u32,
@@ -39,32 +54,216 @@ pub struct FolderDetail {
} }
impl FolderDetail { impl FolderDetail {
pub fn access_level_name(&self) -> &'static str { pub fn access_level_label(&self, projects: &ProjectNames) -> String {
access_level_label(self.access_level) access_level_label_or_unknown(self.access_level, projects)
} }
} }
pub fn access_level_label(level: u32) -> &'static str { /// Build an access-level label from its bits instead of a table of known combinations.
if (level & 0x0204) == 0x0204 { pub fn access_level_label(level: i64, projects: &ProjectNames) -> Option<String> {
return "5Kikan or PW Open"; match level {
STORAGE_ACCESS_LEVEL => return Some("Storage".to_string()),
PRIVATE_ACCESS_LEVEL => return Some("Private".to_string()),
PUBLIC_ACCESS_LEVEL => return Some("Public".to_string()),
_ => {}
} }
if (level & 0x0104) == 0x0104 { if level < 0
return "CBS or PW Open"; || level & (PRIVATE_ACCESS_LEVEL | PUBLIC_ACCESS_LEVEL | RESERVED_ACCESS_LEVEL) != 0
{
return None;
} }
if (level & 0x0200) == 0x0200 {
return "5Kikan Open"; let mut names = Vec::new();
for slot in 1..=RESTRICT_SLOTS {
if level & (1_i64 << (RESTRICT_SHIFT + slot - 1)) != 0 {
names.push(if slot == 1 {
"CBS".to_string()
} else {
format!("Restrict{slot}")
});
} }
if (level & 0x0100) == 0x0100 {
return "CBS Open";
} }
if (level & 0x0004) == 0x0004 {
return "PW Open"; let project_bits = (level >> PROJECT_SHIFT) as u64;
for bit in 0..u64::BITS {
if project_bits & (1_u64 << bit) != 0 {
names.push(
projects
.get(&bit)
.filter(|name| !name.is_empty())
.cloned()
.unwrap_or_else(|| format!("Project{bit}")),
);
} }
if (level & 0x0002) == 0x0002 {
return "Public";
} }
if (level & 0x0001) == 0x0001 { if level & PASSWORD_ACCESS_LEVEL != 0 {
return "Private"; names.push("PW".to_string());
}
Some(format!("{} Open", names.join(" or ")))
}
pub fn access_level_label_or_unknown(level: i64, projects: &ProjectNames) -> String {
access_level_label(level, projects).unwrap_or_else(|| {
if level < 0 {
format!("Unknown (0x-{:x})", level.unsigned_abs())
} else {
format!("Unknown (0x{level:x})")
}
})
}
/// Parse a CLI access-level key such as `cbs_or_project0_open`.
pub fn access_level_from_key(key: &str) -> Option<i64> {
match key {
"storage" => return Some(STORAGE_ACCESS_LEVEL),
"private" => return Some(PRIVATE_ACCESS_LEVEL),
"public" => return Some(PUBLIC_ACCESS_LEVEL),
_ => {}
}
let parts = key.strip_suffix("_open")?;
let mut level = 0_i64;
for part in parts.split("_or_") {
level |= access_level_part(part)?;
}
Some(level)
}
fn access_level_part(part: &str) -> Option<i64> {
if part == "pw" {
return Some(PASSWORD_ACCESS_LEVEL);
}
if part == "cbs" {
return Some(1_i64 << RESTRICT_SHIFT);
}
if let Some(slot) = part
.strip_prefix("restrict")
.and_then(parse_canonical_unsigned)
&& slot > 0
{
if slot > RESTRICT_SLOTS {
return None;
}
return Some(1_i64 << (RESTRICT_SHIFT + slot - 1));
}
if let Some(bit) = part
.strip_prefix("project")
.and_then(parse_canonical_unsigned)
{
let shift = PROJECT_SHIFT.checked_add(bit)?;
if shift >= i64::BITS - 1 {
return None;
}
return Some(1_i64 << shift);
}
None
}
fn parse_canonical_unsigned(value: &str) -> Option<u32> {
if value.is_empty()
|| !value.bytes().all(|byte| byte.is_ascii_digit())
|| (value.len() > 1 && value.starts_with('0'))
{
return None;
}
value.parse().ok()
}
#[cfg(test)]
mod tests {
use super::*;
fn projects() -> ProjectNames {
BTreeMap::from([(0, "Brain/MINDS 2.0".to_string())])
}
#[test]
fn labels_single_and_combined_levels_from_their_bits() {
let cases = [
(0x0000, "Storage"),
(0x0001, "Private"),
(0x0002, "Public"),
(0x0004, "PW Open"),
(0x0100, "CBS Open"),
(0x0104, "CBS or PW Open"),
(0x0200, "Restrict2 Open"),
(0x8000, "Restrict8 Open"),
];
for (level, expected) in cases {
assert_eq!(
access_level_label(level, &ProjectNames::new()).as_deref(),
Some(expected),
"level {level:#x}"
);
}
}
#[test]
fn labels_projects_with_server_names_or_bit_positions() {
assert_eq!(
access_level_label(0x10004, &projects()).as_deref(),
Some("Brain/MINDS 2.0 or PW Open")
);
assert_eq!(
access_level_label(0x10000, &ProjectNames::new()).as_deref(),
Some("Project0 Open")
);
assert_eq!(
access_level_label(0x10000, &BTreeMap::from([(0, String::new())])).as_deref(),
Some("Project0 Open")
);
assert_eq!(
access_level_label(0x20000, &projects()).as_deref(),
Some("Project1 Open")
);
assert_eq!(
access_level_label(0x30304, &projects()).as_deref(),
Some("CBS or Restrict2 or Brain/MINDS 2.0 or Project1 or PW Open")
);
}
#[test]
fn meaningless_levels_are_unknown_instead_of_storage() {
for level in [0x0003, 0x0006, 0x0102, 0x10001, 0x0008, 0x0080, -1] {
assert_eq!(access_level_label(level, &ProjectNames::new()), None);
}
assert_eq!(
access_level_label_or_unknown(0x0008, &ProjectNames::new()),
"Unknown (0x8)"
);
}
#[test]
fn parses_open_level_keys_from_their_parts() {
let cases = [
("storage", 0x0000),
("private", 0x0001),
("public", 0x0002),
("pw_open", 0x0004),
("cbs_open", 0x0100),
("cbs_or_pw_open", 0x0104),
("restrict1_open", 0x0100),
("restrict2_open", 0x0200),
("project0_open", 0x10000),
("project1_or_pw_open", 0x20004),
];
for (key, expected) in cases {
assert_eq!(access_level_from_key(key), Some(expected), "key {key}");
}
}
#[test]
fn rejects_unknown_or_ambiguous_keys() {
for key in [
"5kikan_open",
"restrict9_open",
"restrict0_open",
"project01_open",
"cbs",
"_open",
"pw_or_open",
] {
assert_eq!(access_level_from_key(key), None, "key {key}");
}
} }
"Storage"
} }
+4 -7
View File
@@ -13,14 +13,11 @@ impl Settings {
fn load() -> Self { fn load() -> Self {
let config_dirname = std::env::var("MDRS_CLIENT_CONFIG_DIRNAME") let config_dirname = std::env::var("MDRS_CLIENT_CONFIG_DIRNAME")
.ok() .ok()
.map(|s| { .map(|s| match s.strip_prefix("~/") {
if s.starts_with("~/") { Some(rest) => dirs::home_dir()
dirs::home_dir()
.unwrap_or_else(|| std::path::PathBuf::from(".")) .unwrap_or_else(|| std::path::PathBuf::from("."))
.join(&s[2..]) .join(rest),
} else { None => std::path::PathBuf::from(&s),
std::path::PathBuf::from(&s)
}
}) })
.unwrap_or_else(|| { .unwrap_or_else(|| {
dirs::home_dir() dirs::home_dir()