From 11d219961a7f7b3626c712eef42c65c74cd68cb3 Mon Sep 17 00:00:00 2001 From: William Gill Date: Fri, 27 Nov 2026 01:50:15 -0600 Subject: [PATCH] patches: add v1.11.0 no-symlinks patch and its leil-rig proof 0005-posix-no-symlinks.patch makes VersityGW's posix backend resolve every path below its root and versioning directory from a descriptor of that directory, opened once at start: each directory on the way with openat2 and RESOLVE_NO_SYMLINKS|RESOLVE_BENEATH (one O_NOFOLLOW open per element where openat2 is missing), the last element acted on without following it. Upstream followed a link anywhere on a key's way, so on a host that mounts more than one namespace a link planted in a bucket served, overwrote and deleted another namespace's objects (Norn M5 stage 13). A link, FIFO, socket or device is no object: at the end of a key it reads as missing (404) and is never opened, on the way it answers as a file there does (404, 409 ObjectParentIsFile), listings skip it and never enter it, and PUT, copy, complete and DELETE act on the entry itself, never on what a link points to (owner, 2026-11-27). --bucketlinks still follows a link at the bucket level only. Proven on leil-rig on 2026-11-27, against a stock 0001-0004 control: - tests/no-symlinks/proof.sh, throwaway gateways on leil-test-1: 87/87 (control 38/87). - tests/no-symlinks/rig-replay.sh, with the build pinned on the rig's four instances: 75/75 twice (control 17/75). - rig-gateway-check.sh 20/20 in both namespaces. - go test, every package but plugins/: 35/35. The rig was put back on 26e5a763. docs/no-symlinks.md has the rules, the proof and what it costs: GET +3-9%, HEAD +8-25%, listings 2x on a local disk and within noise on LeilFS. README.md and docs/multi-version-pipeline.md name the patch and how to check a rebase of it. Co-Authored-By: Claude Opus 5.5 --- README.md | 53 +- docs/multi-version-pipeline.md | 29 +- docs/no-symlinks.md | 186 + patches/v1.11.0/0005-posix-no-symlinks.patch | 3962 ++++++++++++++++++ tests/no-symlinks/bench.py | 67 + tests/no-symlinks/bench.sh | 56 + tests/no-symlinks/proof.sh | 252 ++ tests/no-symlinks/race.py | 98 + tests/no-symlinks/rig-replay.sh | 174 + 9 files changed, 4864 insertions(+), 13 deletions(-) create mode 100644 docs/no-symlinks.md create mode 100644 patches/v1.11.0/0005-posix-no-symlinks.patch create mode 100644 tests/no-symlinks/bench.py create mode 100644 tests/no-symlinks/bench.sh create mode 100644 tests/no-symlinks/proof.sh create mode 100644 tests/no-symlinks/race.py create mode 100644 tests/no-symlinks/rig-replay.sh diff --git a/README.md b/README.md index 8beb0da..b9f37ed 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ Artifact names are intentionally **unchanged** — the binary stays drop-in compatible with existing configs, systemd units, and the `versitygw` CLI. Only the embedded web UI is rebranded to "S3 Gateway". -The v1.11.0 series also carries two behavioural patches: +The v1.11.0 series also carries three behavioural patches: - **Owner-scoped bucket access**: a bucket's ACL and policy may name only the owner's own keys, public access is read-only, and deleting a @@ -26,6 +26,10 @@ The v1.11.0 series also carries two behavioural patches: instead of a delete and a create, so the account never goes missing and a failed update leaves it as it was. See [docs/vault-atomic-update.md](docs/vault-atomic-update.md). +- **No symbolic links**: the posix backend resolves every path without + following a symbolic link, so a link planted in a bucket never + reaches another namespace; a link, FIFO, socket or device is no + object. See [docs/no-symlinks.md](docs/no-symlinks.md). ``` upstream tag (vX.Y.Z) this repo @@ -55,7 +59,8 @@ s3-gateway/ │ │ ├── 0001-webui-debrand.patch │ │ ├── 0002-webui-dark-theme.patch │ │ ├── 0003-owner-scoped-access.patch -│ │ └── 0004-vault-atomic-update-user.patch +│ │ ├── 0004-vault-atomic-update-user.patch +│ │ └── 0005-posix-no-symlinks.patch │ └── archive/ # superseded; kept, not built │ ├── v1.10.0/ │ ├── v1.8.0/ @@ -64,12 +69,14 @@ s3-gateway/ │ └── v1.5.0/ ├── tests/ │ ├── owner-scope/ # leil-rig proof test for 0003 (proof.sh, s3req.py) -│ └── vault-update/ # leil-rig proof test for 0004 (proof.sh, watch.py, vaultproxy.py) +│ ├── vault-update/ # leil-rig proof test for 0004 (proof.sh, watch.py, vaultproxy.py) +│ └── no-symlinks/ # leil-rig proof tests for 0005 (proof.sh, race.py, rig-replay.sh, bench.sh/.py) ├── .gitea/workflows/build.yml └── docs/ ├── multi-version-pipeline.md ├── owner-scoped-access.md # what 0003 does, and its proof test - └── vault-atomic-update.md # what 0004 does, and its proof test + ├── vault-atomic-update.md # what 0004 does, and its proof test + └── no-symlinks.md # what 0005 does, its proof tests and its cost ``` ## Build locally @@ -109,7 +116,7 @@ Currently maintained: | Upstream tag | Patch set | Contents | |--------------|---------------|--------------------------------------------------------------------------------------------------------------------------------| -| `v1.11.0` | `v1.11.0/` | `0001-webui-debrand.patch`, `0002-webui-dark-theme.patch`, `0003-owner-scoped-access.patch`, `0004-vault-atomic-update-user.patch` | +| `v1.11.0` | `v1.11.0/` | `0001-webui-debrand.patch`, `0002-webui-dark-theme.patch`, `0003-owner-scoped-access.patch`, `0004-vault-atomic-update-user.patch`, `0005-posix-no-symlinks.patch` | **v1.11.0 is the only supported version.** It supersedes `v1.10.0` with 42 further upstream fixes, so the older series — `v1.10.0`, @@ -184,8 +191,9 @@ account's `UserID`. - An ACL holding the `all-users` `READ` grant can be written back unchanged (upstream answers `500`). -It and `0004` are the series' only patches outside `webui/`, and both -have unit tests: after a rebase run `go test ./auth/ ./s3api/...` (on +It, `0004` and `0005` are the series' only patches outside `webui/`, +and all three have unit tests: after a rebase run +`go test ./auth/ ./s3api/... ./backend/...` (on Linux — on Windows upstream's standalone-IAM, posix and CLI tests fail with or without the series) and the leil-rig proof test in @@ -215,6 +223,37 @@ Its unit tests run with the ones above (`go test ./auth/`); its leil-rig proof test is in [docs/vault-atomic-update.md](docs/vault-atomic-update.md#proving-the-patch-is-in-on-leil-rig). +### What the no-symlinks patch does + +`0005-posix-no-symlinks.patch` makes the posix backend resolve every +path below its root and versioning directory from a descriptor of that +directory, opened once at start, with `openat2` and +`RESOLVE_NO_SYMLINKS|RESOLVE_BENEATH` for each directory on the way +(one `O_NOFOLLOW` open per element where `openat2` is missing), and the +last element acted on without following it. Upstream followed a link +anywhere on a key's way, so on a host that mounts more than one +namespace a link planted in a bucket served, overwrote and deleted +another namespace's objects. + +- **A link, FIFO, socket or device is no object.** At the end of a key + it reads as missing (`404 NoSuchKey`) and is never opened; on the way + it answers as a file there does (reads `404`, writes + `409 ObjectParentIsFile`); listings skip it and never enter it. +- **Writes and deletes act on the entry itself.** PUT, a CopyObject + destination and CompleteMultipartUpload replace it; a DELETE of its + key removes it. What a link points to is never touched. +- **Still followed:** the root and versioning directory as named, and + with `--bucketlinks` a link at the bucket level only. +- `backend.MkdirAll`/`MoveFile` gain FS-taking forms + (`MkdirAllFS`/`MoveFileFS`) that the backend calls with its own file + system; the xattr metadata storer is wrapped to resolve the same way. + Sidecar metadata, ScoutFS's own calls and Windows are unchanged. + +Its unit tests are Linux-only (`go test ./backend/posix/ -run +'NoFollow|RootFS'`, on xfs or ext4, also as root); its two-stage +leil-rig proof and what it costs are in +[docs/no-symlinks.md](docs/no-symlinks.md#proving-the-patch-is-in-on-leil-rig). + ## Adding / refreshing a version When upstream cuts a new release you want a build of, you rebase the diff --git a/docs/multi-version-pipeline.md b/docs/multi-version-pipeline.md index 1994693..74f0d5c 100644 --- a/docs/multi-version-pipeline.md +++ b/docs/multi-version-pipeline.md @@ -112,22 +112,39 @@ VGW_REPO_URL="/path/to/local/versitygw" VGW_TAG=vX.Y.Z bash ci/run.sh A clean `git am` plus a populated `src/dist/` means the web UI patches are good. `0003-owner-scoped-access.patch` and -`0004-vault-atomic-update-user.patch` change Go code in `auth/`, so a -clean apply is not enough for them: run their unit tests in the patched -tree, on Linux (on Windows several upstream packages fail regardless), +`0004-vault-atomic-update-user.patch` change Go code in `auth/`, and +`0005-posix-no-symlinks.patch` in `backend/`, so a clean apply is not +enough for them: run their unit tests in the patched tree, on Linux (on +Windows several upstream packages fail regardless; 0005's tests also +need a file system with user xattrs, so not tmpfs), ```bash -go test ./auth/ ./s3api/... +go test ./auth/ ./s3api/... ./backend/... ``` and each one's proof test on leil-rig — see -[owner-scoped-access.md](owner-scoped-access.md#proving-the-patch-is-in-on-leil-rig) +[owner-scoped-access.md](owner-scoped-access.md#proving-the-patch-is-in-on-leil-rig), +[vault-atomic-update.md](vault-atomic-update.md#proving-the-patch-is-in-on-leil-rig) and -[vault-atomic-update.md](vault-atomic-update.md#proving-the-patch-is-in-on-leil-rig). +[no-symlinks.md](no-symlinks.md#proving-the-patch-is-in-on-leil-rig). If upstream has reworked `auth/access-control.go` or `auth/acl.go`, re-read 0003's rules against the new code rather than only resolving the conflict; likewise `auth/iam_vault.go` for 0004 — if upstream's `UpdateUserAccount` already writes with check-and-set, drop 0004. +For 0005, a conflict-free apply is not enough either: any new path call +upstream adds to `backend/posix/` (an `os.Stat`, `os.Open`, `xattr.*`, +`unix.Open`, `os.DirFS`, `backend.MkdirAll`…) follows links until it is +routed through `p.fsys`. After a rebase, this must list only the seven +calls it listed for v1.11.0: the root's own open in `New`, +`validateSubDir`'s check of an operator's path, the three on +`/proc/self/fd` paths (`data_io_linux.go`, `otmpfile_common.go`, +`with_otmpfile.go`), Windows' `dir_windows.go`, and `without_otmpfile.go`'s +`reopenFile`, which nothing calls off Linux: + +```bash +grep -nE '(^|[^.[:alnum:]_])os\.(Stat|Lstat|Open|OpenFile|ReadDir|Remove|RemoveAll|Rename|Mkdir|MkdirAll|Chown|Chtimes|CreateTemp|DirFS)\(|backend\.(MkdirAll|MoveFile)\(' \ + backend/posix/*.go | grep -v -e _test.go -e nofollow_ +``` `src/` may hold someone's local work tree; `ci/clone-source.sh` deletes it. Point `VGW_SRC_DIR` somewhere fresh (any `*-src/` name is diff --git a/docs/no-symlinks.md b/docs/no-symlinks.md new file mode 100644 index 0000000..ae8b15a --- /dev/null +++ b/docs/no-symlinks.md @@ -0,0 +1,186 @@ +# The posix backend never follows a symbolic link (`0005-posix-no-symlinks.patch`) + +`patches/v1.11.0/0005-posix-no-symlinks.patch` applies after `0004`. It changes how VersityGW's posix backend reaches +the files under its root. No path is followed through a symbolic link any more, and a link, FIFO, socket or device is no +object. Requested through Norn (owner, 2026-11-26) after Norn's M5 stage 13 found links planted in a home and a bucket +served across namespaces on leil-rig. The owner settled the design on 2026-11-27. + +| | | +|---|---| +| Touches | `backend/posix/` (new: `nofollow_unix.go`, `nofollow_linux.go`, `nofollow_other.go`, `nofollow_windows.go`, `nofollow_mtim.go`, `nofollow_mtimespec.go`, `nofollow_linux_test.go`), `backend/mkdir.go`, `backend/common.go`, `backend/meta/xattr.go` | +| Base | upstream `v1.11.0` (`e42ae7ab`) + `0001`–`0004` | +| Unit tests | `go test ./backend/posix/ -run 'NoFollow\|RootFS'`, on Linux only, on a file system with user xattrs (xfs, ext4; not tmpfs before Linux 6.6). Run them as root too, for the device case. | +| Proof tests | [`tests/no-symlinks/proof.sh`](../tests/no-symlinks/proof.sh) (throwaway gateways on leil-test-1) and [`tests/no-symlinks/rig-replay.sh`](../tests/no-symlinks/rig-replay.sh) (leil-rig's installed gateways), below | + +## The problem + +Stock 1.11.0 builds every path from the gateway root, its working directory. It hands the path to path-based calls: +`stat`, `open`, `getxattr`, `os.MkdirAll` and so on. So the kernel follows a symbolic link at **any directory on a +key's way**, for every operation. At the **last element** it follows one too, for every call but `lstat`, `unlink`, +`rmdir`, `rename`, `mkdir` and `link`. On a host that mounts more than one namespace, or the whole LeilFS tree (the +rig's gateway hosts, and sto-1's single node), a link in a bucket reaches another namespace: + +| Operation | Link as the last element | Link as a directory on the way | +|---|---|---| +| GET, HEAD, GetObjectAttributes | the target is served | followed | +| CopyObject and UploadPartCopy source | the target is copied | followed | +| PUT, CopyObject destination, CompleteMultipartUpload | the rename replaces the link, but the stat before it follows it (a link to a directory answers 409, and If-Match compares the target's ETag) | **the object is written in the directory the link reaches**; across mounts, through `MoveFile`'s copy fallback | +| DeleteObject, DeleteObjects | the link itself is removed | **the target's file is removed**, and empty directories of the key below the link | +| Tagging, retention, legal hold | the target's attributes are read and written | followed | +| Listings | listed as an object with the link's own size, and the target's ETag and checksums | a full walk does not enter it, but a prefix through it lists the directory it reaches, and those keys are then served | +| Multipart staging, `.sgwtmp` | none | followed: a link at `.sgwtmp` or below moves the staging into the target | +| Bucket-level settings | the bucket is `lstat`ed (a link is refused unless `--bucketlinks`), then read by path: a link swapped in after the `lstat` is followed | none: one element | + +A FIFO GET opens the FIFO and blocks until a writer comes, which can be never. That leaves a goroutine stuck in each +gateway it was sent to until the gateway restarts. A socket GET answers 500. + +## The change + +| | | +|---|---| +| **Resolution** | `rootFS` (`nofollow_unix.go`) takes every path the backend builds under the root or the versioning directory. It resolves the path from a descriptor of that directory, opened once at start. Each directory on the way is opened with `openat2(…, RESOLVE_NO_SYMLINKS \| RESOLVE_BENEATH \| RESOLVE_NO_MAGICLINKS)`. The call on the last element is made relative to its directory, without following it: `O_NOFOLLOW`, `AT_SYMLINK_NOFOLLOW`, the `*at` calls. Extended attributes use the l-calls on `/proc/self/fd//`. So a link swapped in while a request runs is refused too. | +| **Fallback** | Where `openat2` is missing (ENOSYS, Linux before 5.6), refused by seccomp (EPERM), or keeps answering EAGAIN, the directories are opened one element at a time with `O_PATH\|O_DIRECTORY\|O_NOFOLLOW`. The guarantee is the same; it takes one call per element. `RESOLVE_BENEATH` alone would not do: it still follows a link that stays under the root, such as one home's link into another home of the same namespace, or a link from a granted folder to an ungranted one in the same bucket. | +| **Not an object** | A symbolic link, FIFO, socket or device as the last element reads as missing: 404 `NoSuchKey`, `NoSuchVersion` with a version id. It is **never opened**: an existing file is first opened with `O_PATH`, which opens no FIFO or device, then checked, and only then opened through its descriptor. Extended attribute calls on it report it missing too. | +| **On the way** | Such an entry as a directory of the key answers as a file there does: reads 404, writes 409 `ObjectParentIsFile`. Nothing is written or removed through it. | +| **Listings** | The listings' file system holds only regular files and directories. A link is neither listed nor entered, and a prefix through one lists nothing. | +| **Writes and deletes** | PUT, a CopyObject destination and CompleteMultipartUpload replace the entry itself: the rename never follows it. A DELETE of its key with no version id and no preconditions removes the entry itself and answers 204, then goes on as for a missing object. A key with a trailing slash names a directory object, and leaves a link at that name alone. What a link points to is never touched. | +| **What is still followed** | The root and the versioning directory, which are opened as the operator named them. With `--bucketlinks` (off everywhere), a link at the bucket level, as that option promises; nothing below a bucket is followed even then. A bucket that is a link without that option is refused as before, now without the race. | +| **Shared helpers** | `backend.MkdirAll` and `backend.MoveFile` take the file system they work on (`MkdirAllFS`, `MoveFileFS`, the `FS` interface; `backend.OS` is the os package's). The posix backend then makes parent directories and moves temporary files through `rootFS`. The xattr metadata storer passed to `posix.New` is wrapped to resolve through `rootFS`. | + +A link met on the way, or an entry that is no object, is logged at debug level (`--debug`), with its path. + +### What it does not change + +- **The sidecar storer** (`--sidecar`) and **ScoutFS's own calls** are as upstream has them. Neither is deployed. The + sidecar directory is outside every namespace mount, and the posix half of the ScoutFS backend is covered. +- **Windows**: `rootFS` is the os package's there, as upstream has it. +- **darwin and FreeBSD** use the element-by-element walk, since they have no `openat2`. With no `O_PATH` either, an + existing file is opened with `O_NONBLOCK` and then checked, so a FIFO is opened for that moment, though never read and + never waited on. +- **Linux needs `/proc`**: `posix.New` refuses to start without `/proc/self/fd`. Upstream's `O_TMPFILE` path already + needed it. +- A **bucket that holds only a link** answers `BucketNotEmpty` to DeleteBucket while its listing is empty. Remove the + link on the host (Norn's agents already skip links), or DELETE its key by name. + +### What it costs + +Each call on a path opens the directory of its last element and closes it again, a few more system calls than before. +They are mostly lookups the kernel serves from its caches. Measured with +[`tests/no-symlinks/bench.sh`](../tests/no-symlinks/bench.sh) on leil-test-1 (local xfs, one throwaway gateway, +1 KiB objects four directories deep). On LeilFS it was measured through the rig's own instances +(`rig-replay.sh … 300`). Medians, patched vs stock; xfs over three runs each, LeilFS over two patched runs and one stock run: + +| Call | xfs: stock | xfs: patched | LeilFS: stock | LeilFS: patched | +|---|---|---|---|---| +| PUT | 3.0–3.1 ms | 3.0–3.3 ms | 23.2 ms | 22.5–22.8 ms | +| GET | 2.3–2.4 ms | 2.5–2.6 ms | 15.9 ms | 16.3–16.4 ms | +| HEAD | 2.2–2.4 ms | 2.7–2.8 ms | 12.1 ms | 13.1 ms | +| LIST (a 500-key page on xfs, 300 on LeilFS) | 51–52 ms | 103–105 ms | 598 ms | 584–616 ms | +| DELETE | 2.0 ms | 2.2 ms | 6.9 ms | 6.6–7.3 ms | +| system calls in the gateway per GET / HEAD (strace) | 102–104 / 85–88 | 124–126 / 150–153 | | | + +On LeilFS, where the FUSE round trips dominate, the difference is within the noise except HEAD (+8%). On a local disk, +listings take twice as long. They resolve each entry's directory again for its stat and its three attribute reads, so +reading those relative to the listed directory is the place to win it back if it ever matters. HEAD makes 14 +path-based attribute reads. + +## Proving the patch is in (on leil-rig) + +`--version` reads `1.11.0` with or without the patch, so the proof is behaviour. Two stages, both under the lease: + +```bash +RIG_LEASE_WHO=": s3-gateway 0005 proof" ./bin/rig-lease.sh claim --why "s3-gateway 0005 proof" --minutes 120 +VGW_SRC_DIR=build-src VGW_TAG=v1.11.0 bash ci/run.sh +``` + +### Stage 1: throwaway gateways on leil-test-1 + +[`tests/no-symlinks/proof.sh`](../tests/no-symlinks/proof.sh) runs as root. It starts two gateways from the given +binary: A on `127.0.0.1:7393` and B on `:7394`. Each is on posix, rooted at its own namespace directory under +`/var/tmp/s3gw-no-symlinks`, with its own internal IAM, `--chuid --chgid --dir-perms 0700` as the rig's gateways run. +It replays Norn's stage 13 layout with two accounts on the reserved test band: `ns-user` (UID 74990) owns `home` on A +and `data` on B, and `ns-other` (74991) owns `sibling` on A. As root, owned by the UID, it plants in A's +`home/escape/` and B's `data/escape/`: +- links to the other namespace's marker, absolute and relative (`../../../ns-b/…`); +- a link to the other side's directory; +- a FIFO, a socket and a device; +- in A, a link to `sibling`'s object, another home of the same namespace. + +It removes everything at exit; `KEEP=1` keeps it. + +```bash +cd ../leil-rig && source bin/rig-lib.sh +on leil-test-1 'install -d -o leil -g leil /var/tmp/s3gw-0005' +rig_scp ../s3-gateway/build-src/dist/versitygw_linux_amd64_v1/versitygw leil-test-1 /var/tmp/s3gw-0005/versitygw +tar -czf /tmp/no-symlinks.tgz -C ../s3-gateway/tests owner-scope no-symlinks +rig_scp /tmp/no-symlinks.tgz leil-test-1 /var/tmp/s3gw-0005/no-symlinks.tgz +on leil-test-1 'cd /var/tmp/s3gw-0005 && chmod 0755 versitygw && tar -xzf no-symlinks.tgz && bash no-symlinks/proof.sh $PWD/versitygw' +``` + +| Checks | Shows | +|---|---| +| S1–S12 | the accounts, buckets and markers; the entries planted; the links resolve on the host | +| R1–R30 | GET and HEAD of every link, the FIFO, the socket and the device, at the end of the key and through the directory link, on both gateways: 404, each within 20 s | +| R50–R56 | GetObjectTagging, GetObjectAttributes and CopyObject from a link: 404; the bucket's own object still reads | +| L1–L6 | ListObjectsV2, ListObjects and ListObjectVersions, with and without a delimiter: only the marker; a prefix through the link: nothing | +| W1–W17 | PUT, CopyObject and CompleteMultipartUpload replace a link or FIFO with a file of the user's UID; PUT and CopyObject under a link or socket: 409, nothing written on the other side; PutObjectTagging of a link: 404 | +| D1–D9 | DELETE and DeleteObjects remove the link, socket and device themselves, and remove nothing through the directory link | +| X0–X2 | `race.py`: for 3 s a directory of the bucket and a link to the other namespace's directory swap names (`renameat2` `RENAME_EXCHANGE`) as fast as they can, while GET, PUT and DELETE run under it. No GET serves the other side, and its directory holds only what it held. | +| Z1–Z2 | the markers and their attributes are unchanged; no gateway panicked | + +### Stage 2: the rig's installed gateways, on LeilFS + +Pin the build on the rig's four instances through a git-ignored `versitygw.auto.tfvars` with the build's three +`versitygw_*` pins, and run `bin/rig-versitygw.sh --rpm `. Then `bin/rig-gateway-check.sh`, and +[`tests/no-symlinks/rig-replay.sh`](../tests/no-symlinks/rig-replay.sh) as root on leil-mst-1, with `s3req.py` and +`bench.py` beside it. Its arguments are the peer's IP, a UID from the test band and the mount cache time: + +```bash +on leil-mst-1 'bash /var/tmp/s3gw-nf-tools/rig-replay.sh 192.168.100.43 74995 5 300' +``` + +It makes a throwaway account in `0x0` and `0x1`, a home `nf-home-` and a bucket `nf-data-`. Each root +key is read from `/etc/versitygw.d/.conf` only inside the admin calls, and never printed. It plants Norn's links +across the two mounts (`../../../0x1/…` and back), a directory link, a FIFO and a socket, waits out the mount cache, +and drives GET, HEAD, CopyObject, listings, PUT and DELETE at them through all four instances. It then removes +everything through the mounts, with the account. The fourth argument also times that many calls on LeilFS. Then remove +`versitygw.auto.tfvars`, run `bin/rig-versitygw.sh`, `bin/rig-gateway-check.sh` and `bin/rig-status.sh`, and release +the lease. + +### Result on leil-rig, 2026-11-27: **PASSED** + +Run under the lease. leil-test-1 and the gateway hosts run AlmaLinux 9.8 with kernel 5.14.0-687.53.1; the rig has +LeilFS `274875f2`, OpenBao 2.6.2 and Vault IAM: + +| | | +|---|---| +| Build | `VGW_TAG=v1.11.0 bash ci/run.sh` (fresh clone of `v1.11.0`, 0001–0005 by `git am --3way`, GoReleaser, go1.27.3); `--version` 1.11.0, `Build` `a4152e88` | +| `versitygw` (linux amd64) sha256 | `7213faedd150294b2890d986392b20ff5b6e5d24dfa317cc956913451e9ab7a9` | +| `versitygw_1.11.0_linux_amd64.rpm` sha256 | `1148ed7a8f079b2da60530a9b139a7cacd82cffc5349a4c293cf16510d63990a` (built locally; not published, not pinned) | +| Unit tests on leil-test-1 (go1.27.3 linux/amd64) | the new tests: ok, as `leil` and as root, with `openat2` and with the walk, with relative and absolute paths, and with `-race`. The swap test made about 120 000 swaps a run, and every GET that answered served the bucket's own data. Every package but `plugins/`: 35 of 35 ok. | +| `proof.sh` (stage 1) | **87 passed, 0 failed**. Race: 53 344 swaps, 258 rounds; GET 200 ×42 (own data), 404 ×216; PUT 200 ×175, 409 ×82, 500 ×1; the other side untouched. | +| `rig-replay.sh` (stage 2), patched build pinned | **75 passed, 0 failed**, twice: 44 reads through the four instances answered 404, the listings showed the marker alone, and the writes and deletes acted on the entry itself. `rig-gateway-check.sh` passed 0x0 20/20 and 0x1 20/20. | + +**Control: stock 0001–0004.** Same scripts. On leil-test-1 the control was built by `ci/run.sh` from the same +repository state, with `PATCH_DIR` holding 0001–0004 (binary `c522187e…`). On the rig it was the pinned release +`26e5a763…`. +- `proof.sh`: **38 passed, 49 failed**. + - Every link GET and HEAD answered 200 with the other namespace's marker, and so did the other home's. + - The FIFO GET and the copy from it did not answer in 20 s. The socket GET answered 500, and the device GET 200. + - The listings showed every planted entry, and the prefix through the link listed the other side. + - PUT and CopyObject under the link answered 200, written in the other namespace. + - DELETE under it removed the other namespace's marker. + - Tagging went through to the target. + - In the race, 165 GETs served the other side. +- `rig-replay.sh`: **17 passed, 58 failed**, Norn's finding on all four instances and more: + - all 44 reads were served; + - the FIFO GETs did not answer; + - the listings entered the link; + - PUT under the link wrote into the other namespace; + - DELETE under the link removed 0x0's marker. + +The rig was put back after the trial. Every node runs `26e5a763ab3f` again; `rig-gateway-check.sh` passed 20/20 in both +namespaces, and `rig-status.sh` reads as before. Under a swap race as fast as `race.py`'s, a PUT can answer 500 rather +than 409, as one did in one of two runs; nothing is written through the link. + +Run this test again before pinning any build that carries 0005, in leil-rig or leil-cluster. diff --git a/patches/v1.11.0/0005-posix-no-symlinks.patch b/patches/v1.11.0/0005-posix-no-symlinks.patch new file mode 100644 index 0000000..6b7ac7d --- /dev/null +++ b/patches/v1.11.0/0005-posix-no-symlinks.patch @@ -0,0 +1,3962 @@ +From ca2ac51a3ff68b59886911932cf8dafadb536a2f Mon Sep 17 00:00:00 2001 +From: s3-gateway CI +Date: Fri, 27 Nov 2026 00:53:30 -0600 +Subject: [PATCH 5/5] backend/posix: never follow a symbolic link + +The posix backend built every path from the gateway root, its working +directory, and handed it to path-based calls, so the kernel followed a +symbolic link at any directory on a key's way, and at the last element +for every call but lstat, unlink, rename, mkdir and link. On a host +that mounts more than one namespace, or the whole tree, a link planted +in a bucket reached another namespace's data: + +- GET, HEAD, copy sources and UploadPartCopy served the target. +- PUT, CopyObject and CompleteMultipartUpload under a link to a + directory wrote the object there, and DELETE under it removed the + target's file. +- Tagging, retention and legal hold read and wrote the target's + attributes. +- A listing whose prefix ran through a link listed the directory it + reached, and every listing showed a link as an object with its + target's ETag. + +Every path below the root and the versioning directory is now resolved +by rootFS (nofollow_unix.go) from a descriptor of that directory, opened +once at start. The directories on the way are opened with openat2 and +RESOLVE_NO_SYMLINKS|RESOLVE_BENEATH|RESOLVE_NO_MAGICLINKS, or one element +at a time with O_NOFOLLOW where openat2 is missing (ENOSYS), refused by +seccomp (EPERM), or keeps asking for a retry. The call on the last +element is made relative to its directory without following it +(O_NOFOLLOW, AT_SYMLINK_NOFOLLOW, *at calls; extended attributes with +the l-calls on /proc/self/fd//). A link swapped in while a +request runs is refused too. + +A symbolic link, FIFO, socket or device is no object: + +- As the last element it reads as missing: 404 NoSuchKey (NoSuchVersion + with a version id), and it is never opened. An existing file is + opened with O_PATH, checked, and only then opened through its + descriptor. +- As a directory on the way it answers as a file there does: reads 404, + writes 409 ObjectParentIsFile. Nothing is written or removed through + it. +- Listings skip it and never enter it. +- PUT, a CopyObject destination and CompleteMultipartUpload replace the + entry itself (the rename never follows it); a DELETE of its key, with + no version id and no preconditions, removes the entry itself and + answers 204. What a link points to is never touched. + +With --bucketlinks a link at the bucket level is still followed, as the +option promises; nothing below it is. The root and the versioning +directory are opened as the operator named them. + +backend.MkdirAll and backend.MoveFile take the file system they work on +(MkdirAllFS, MoveFileFS, and the FS interface with OS for the os +package's), so the posix backend makes parent directories and moves +temporary files through rootFS too. The xattr metadata storer is +wrapped to resolve its paths through rootFS. The sidecar storer, the +ScoutFS backend's own calls and Windows are unchanged. +--- + backend/common.go | 15 +- + backend/meta/xattr.go | 7 + + backend/mkdir.go | 57 +- + backend/posix/data_io_linux.go | 12 +- + backend/posix/data_io_other.go | 12 +- + backend/posix/dir_unix.go | 16 +- + backend/posix/dir_windows.go | 4 +- + backend/posix/fsync.go | 6 +- + backend/posix/fsync_test.go | 2 +- + backend/posix/keyname.go | 3 +- + backend/posix/nofollow_linux.go | 286 ++++++++ + backend/posix/nofollow_linux_test.go | 898 +++++++++++++++++++++++++ + backend/posix/nofollow_mtim.go | 27 + + backend/posix/nofollow_mtimespec.go | 27 + + backend/posix/nofollow_other.go | 142 ++++ + backend/posix/nofollow_unix.go | 959 +++++++++++++++++++++++++++ + backend/posix/nofollow_windows.go | 70 ++ + backend/posix/objlock.go | 12 +- + backend/posix/otmpfile_common.go | 11 +- + backend/posix/posix.go | 194 +++--- + backend/posix/with_otmpfile.go | 56 +- + backend/posix/without_otmpfile.go | 17 +- + 22 files changed, 2673 insertions(+), 160 deletions(-) + create mode 100644 backend/posix/nofollow_linux.go + create mode 100644 backend/posix/nofollow_linux_test.go + create mode 100644 backend/posix/nofollow_mtim.go + create mode 100644 backend/posix/nofollow_mtimespec.go + create mode 100644 backend/posix/nofollow_other.go + create mode 100644 backend/posix/nofollow_unix.go + create mode 100644 backend/posix/nofollow_windows.go + +diff --git a/backend/common.go b/backend/common.go +index dec5f93..887d3f3 100644 +--- a/backend/common.go ++++ b/backend/common.go +@@ -615,12 +615,17 @@ func (f *FileSectionReadCloser) Close() error { + + // MoveFile moves a file from source to destination. + func MoveFile(source, destination string, perm os.FileMode) error { ++ return MoveFileFS(OS, source, destination, perm) ++} ++ ++// MoveFileFS is MoveFile on the file system fsys. ++func MoveFileFS(fsys FS, source, destination string, perm os.FileMode) error { + // We use Rename as the atomic operation for object puts. The upload is + // written to a temp file to not conflict with any other simultaneous + // uploads. The final operation is to move the temp file into place for + // the object. This ensures the object semantics of last upload completed + // wins and is not some combination of writes from simultaneous uploads. +- err := os.Rename(source, destination) ++ err := fsys.Rename(source, destination) + if err == nil || !errors.Is(err, syscall.EXDEV) { + return err + } +@@ -629,7 +634,7 @@ func MoveFile(source, destination string, perm os.FileMode) error { + // filesystem. The fallback is to copy the file and then remove the source. + // We need to be careful that the desination does not exist before copying + // to prevent any other simultaneous writes to the file. +- sourceFile, err := os.Open(source) ++ sourceFile, err := fsys.Open(source) + if err != nil { + return fmt.Errorf("open source: %w", err) + } +@@ -637,10 +642,10 @@ func MoveFile(source, destination string, perm os.FileMode) error { + + var destFile *os.File + for { +- destFile, err = os.OpenFile(destination, os.O_CREATE|os.O_EXCL|os.O_WRONLY, perm) ++ destFile, err = fsys.OpenFile(destination, os.O_CREATE|os.O_EXCL|os.O_WRONLY, perm) + if err != nil { + if errors.Is(err, fs.ErrExist) { +- if removeErr := os.Remove(destination); removeErr != nil { ++ if removeErr := fsys.Remove(destination); removeErr != nil { + return fmt.Errorf("remove existing destination: %w", removeErr) + } + continue +@@ -656,7 +661,7 @@ func MoveFile(source, destination string, perm os.FileMode) error { + return fmt.Errorf("copy data: %w", err) + } + +- err = os.Remove(source) ++ err = fsys.Remove(source) + if err != nil { + return fmt.Errorf("remove source: %w", err) + } +diff --git a/backend/meta/xattr.go b/backend/meta/xattr.go +index db5fb55..fa7c75c 100644 +--- a/backend/meta/xattr.go ++++ b/backend/meta/xattr.go +@@ -176,6 +176,13 @@ func (x XattrMeta) ListAttributes(bucket, object string) ([]string, error) { + return attributes, nil + } + ++// XattrPrefix is the prefix of the names of the extended attributes that ++// XattrMeta stores attributes in: the name of an attribute is the prefix ++// followed by the attribute. ++func XattrPrefix() string { ++ return xattrPrefix ++} ++ + func isUserAttr(attr string) bool { + return strings.HasPrefix(attr, xattrPrefix) + } +diff --git a/backend/mkdir.go b/backend/mkdir.go +index fe3d952..10e7d36 100644 +--- a/backend/mkdir.go ++++ b/backend/mkdir.go +@@ -46,13 +46,48 @@ const ( + // objects under them, without any coordination with the writers that make + // them. + func MkdirAll(path string, uid, gid int, doChown bool, dirPerm fs.FileMode) error { ++ return MkdirAllFS(OS, path, uid, gid, doChown, dirPerm) ++} ++ ++// MkdirAllFS is MkdirAll on the file system fsys. ++func MkdirAllFS(fsys FS, path string, uid, gid int, doChown bool, dirPerm fs.FileMode) error { + retries := maxMkdirRaceRetries +- return mkdirAll(path, uid, gid, doChown, dirPerm, &retries) ++ return mkdirAll(fsys, path, uid, gid, doChown, dirPerm, &retries) ++} ++ ++// FS is the file system that MkdirAllFS and MoveFileFS work on, by path. OS ++// is the operating system's, whose calls follow symbolic links; a backend ++// can pass its own, such as one that never follows them. ++type FS interface { ++ Stat(name string) (fs.FileInfo, error) ++ Lstat(name string) (fs.FileInfo, error) ++ Open(name string) (*os.File, error) ++ OpenFile(name string, flag int, perm fs.FileMode) (*os.File, error) ++ Mkdir(name string, perm fs.FileMode) error ++ Chown(name string, uid, gid int) error ++ Remove(name string) error ++ Rename(oldpath, newpath string) error ++} ++ ++// OS is the FS of the os package. ++var OS FS = osFS{} ++ ++type osFS struct{} ++ ++func (osFS) Stat(name string) (fs.FileInfo, error) { return os.Stat(name) } ++func (osFS) Lstat(name string) (fs.FileInfo, error) { return os.Lstat(name) } ++func (osFS) Open(name string) (*os.File, error) { return os.Open(name) } ++func (osFS) OpenFile(name string, flag int, perm fs.FileMode) (*os.File, error) { ++ return os.OpenFile(name, flag, perm) + } ++func (osFS) Mkdir(name string, perm fs.FileMode) error { return os.Mkdir(name, perm) } ++func (osFS) Chown(name string, uid, gid int) error { return os.Chown(name, uid, gid) } ++func (osFS) Remove(name string) error { return os.Remove(name) } ++func (osFS) Rename(oldpath, newpath string) error { return os.Rename(oldpath, newpath) } + +-func mkdirAll(path string, uid, gid int, doChown bool, dirPerm fs.FileMode, retries *int) error { ++func mkdirAll(fsys FS, path string, uid, gid int, doChown bool, dirPerm fs.FileMode, retries *int) error { + // Fast path: if we can tell whether path is a directory or file, stop with success or error. +- dir, err := os.Stat(path) ++ dir, err := fsys.Stat(path) + if err == nil { + if dir.IsDir() { + return nil +@@ -74,14 +109,14 @@ func mkdirAll(path string, uid, gid int, doChown bool, dirPerm fs.FileMode, retr + for { + if j > 1 { + // Create parent. +- err = mkdirAll(path[:j-1], uid, gid, doChown, dirPerm, retries) ++ err = mkdirAll(fsys, path[:j-1], uid, gid, doChown, dirPerm, retries) + if err != nil { + return err + } + } + + // Parent now exists; invoke Mkdir and use its result. +- err = os.Mkdir(path, dirPerm) ++ err = fsys.Mkdir(path, dirPerm) + if err == nil { + break + } +@@ -94,12 +129,12 @@ func mkdirAll(path string, uid, gid int, doChown bool, dirPerm fs.FileMode, retr + + // Handle arguments like "foo/." by + // double-checking that directory doesn't exist. +- dir, err1 := os.Lstat(path) ++ dir, err1 := fsys.Lstat(path) + if errors.Is(err, fs.ErrExist) && errors.Is(err1, fs.ErrNotExist) { + // Mkdir saw a directory that Lstat doesn't: it was removed + // right after another writer made it, or this client has a + // stale lookup of it cached. +- dir, err1 = lstatRevalidated(path) ++ dir, err1 = lstatRevalidated(fsys, path) + if errors.Is(err1, fs.ErrNotExist) && *retries > 0 { + takeMkdirRetry(retries) + continue +@@ -117,7 +152,7 @@ func mkdirAll(path string, uid, gid int, doChown bool, dirPerm fs.FileMode, retr + } + + if doChown { +- err = os.Chown(path, uid, gid) ++ err = fsys.Chown(path, uid, gid) + if err != nil { + return err + } +@@ -145,9 +180,9 @@ func takeMkdirRetry(retries *int) { + // have cached as missing. Opening the parent directory makes an NFS client + // revalidate the directory (close-to-open consistency), which drops the + // entries it cached as missing if another client has changed it since. +-func lstatRevalidated(path string) (fs.FileInfo, error) { +- if d, err := os.Open(filepath.Dir(path)); err == nil { ++func lstatRevalidated(fsys FS, path string) (fs.FileInfo, error) { ++ if d, err := fsys.Open(filepath.Dir(path)); err == nil { + d.Close() + } +- return os.Lstat(path) ++ return fsys.Lstat(path) + } +diff --git a/backend/posix/data_io_linux.go b/backend/posix/data_io_linux.go +index 358aefa..5a8d7ce 100644 +--- a/backend/posix/data_io_linux.go ++++ b/backend/posix/data_io_linux.go +@@ -19,6 +19,7 @@ package posix + import ( + "fmt" + "io" ++ "io/fs" + "os" + "path/filepath" + "strconv" +@@ -34,15 +35,20 @@ import ( + // requested. O_DIRECT is best-effort and falls back to buffered I/O when + // unsupported by the filesystem. + func openDataRead(name string, useODirect bool) (*os.File, error) { ++ return openDataReadFS(os.OpenFile, name, useODirect) ++} ++ ++// openDataReadFS is openDataRead with the files opened by openFile. ++func openDataReadFS(openFile func(string, int, fs.FileMode) (*os.File, error), name string, useODirect bool) (*os.File, error) { + if !useODirect { +- return os.Open(name) ++ return openFile(name, os.O_RDONLY, 0) + } + +- f, err := os.OpenFile(name, syscall.O_RDONLY|syscall.O_DIRECT, 0) ++ f, err := openFile(name, syscall.O_RDONLY|syscall.O_DIRECT, 0) + if err != nil { + if isODirectUnsupportedOpenErr(err) { + warnODirectUnsupportedOnce("openDataRead", err) +- return os.Open(name) ++ return openFile(name, os.O_RDONLY, 0) + } + + return nil, err +diff --git a/backend/posix/data_io_other.go b/backend/posix/data_io_other.go +index 790f3da..93aa826 100644 +--- a/backend/posix/data_io_other.go ++++ b/backend/posix/data_io_other.go +@@ -16,11 +16,19 @@ + + package posix + +-import "os" ++import ( ++ "io/fs" ++ "os" ++) + + func openDataRead(name string, useODirect bool) (*os.File, error) { ++ return openDataReadFS(os.OpenFile, name, useODirect) ++} ++ ++// openDataReadFS is openDataRead with the files opened by openFile. ++func openDataReadFS(openFile func(string, int, fs.FileMode) (*os.File, error), name string, useODirect bool) (*os.File, error) { + if useODirect { + warnODirectUnsupportedOnce("openDataRead-nonlinux", os.ErrInvalid) + } +- return os.Open(name) ++ return openFile(name, os.O_RDONLY, 0) + } +diff --git a/backend/posix/dir_unix.go b/backend/posix/dir_unix.go +index 457ba1b..12bbf5c 100644 +--- a/backend/posix/dir_unix.go ++++ b/backend/posix/dir_unix.go +@@ -30,9 +30,10 @@ import ( + // no parent is a file: the parent that was a file has been removed since, or + // a shared filesystem failed the lookup for a directory that another node is + // removing. The caller treats name as missing then. +-func handleParentDirError(name string) error { ++func (p *Posix) handleParentDirError(name string) error { + for dir := filepath.Dir(name); dir != filepath.Dir(dir); dir = filepath.Dir(dir) { +- fi, err := os.Lstat(dir) ++ // a symbolic link is no directory: it is a file in the way ++ fi, err := p.fsys.Lstat(dir) + if err != nil { + continue + } +@@ -44,13 +45,6 @@ func handleParentDirError(name string) error { + return nil + } + +-// removeDir removes the directory name if it is empty. Unlike os.Remove it +-// never removes a file, which a concurrent upload may have put in place of +-// the directory since the caller looked at it. +-func removeDir(name string) error { +- return syscall.Rmdir(name) +-} +- + // isParentDirGone reports whether err from placing an entry in a directory + // means the directory, or one of its parents, is not there: it is missing + // (ENOENT), a stale handle to a directory another client removed (ESTALE), +@@ -94,6 +88,6 @@ func isErrDirNotEmpty(err error) bool { + } + + // openForRead opens an object data file for reading. +-func openForRead(name string, useODirect bool) (*os.File, error) { +- return openDataRead(name, useODirect) ++func (p *Posix) openForRead(name string, useODirect bool) (*os.File, error) { ++ return openDataReadFS(p.fsys.OpenFile, name, useODirect) + } +diff --git a/backend/posix/dir_windows.go b/backend/posix/dir_windows.go +index e1e18b3..a941d49 100644 +--- a/backend/posix/dir_windows.go ++++ b/backend/posix/dir_windows.go +@@ -27,7 +27,7 @@ import ( + "github.com/versity/versitygw/s3err" + ) + +-func handleParentDirError(name string) error { ++func (p *Posix) handleParentDirError(name string) error { + dir := filepath.Dir(name) + + // Walk up the directory hierarchy until Dir returns its argument +@@ -115,7 +115,7 @@ func isErrNotDir(err error) bool { + // is held open for streaming the GET response body. Without this flag, + // Windows returns "The process cannot access the file because it is being + // used by another process" on the Remove call. +-func openForRead(name string, useODirect bool) (*os.File, error) { ++func (p *Posix) openForRead(name string, useODirect bool) (*os.File, error) { + return openDataRead(name, useODirect) + } + +diff --git a/backend/posix/fsync.go b/backend/posix/fsync.go +index a367a74..dc5cd36 100644 +--- a/backend/posix/fsync.go ++++ b/backend/posix/fsync.go +@@ -24,12 +24,12 @@ import ( + // syncFile and syncDir are variables so tests can observe the calls. + var ( + syncFile = func(f *os.File) error { return f.Sync() } +- syncDir = func(dir string) error { ++ syncDir = func(fsys *rootFS, dir string) error { + // Windows cannot fsync a directory handle. + if runtime.GOOS == "windows" { + return nil + } +- d, err := os.Open(dir) ++ d, err := fsys.Open(dir) + if err != nil { + return err + } +@@ -60,7 +60,7 @@ func (tmp *tmpfile) syncNamespace() error { + stop := filepath.Clean(tmp.bucket) + dir := filepath.Dir(filepath.Join(tmp.bucket, tmp.objname)) + for { +- if err := syncDir(dir); err != nil { ++ if err := syncDir(tmp.fsys, dir); err != nil { + return fmt.Errorf("fsync directory %q: %w", dir, err) + } + parent := filepath.Dir(dir) +diff --git a/backend/posix/fsync_test.go b/backend/posix/fsync_test.go +index df425ec..c689981 100644 +--- a/backend/posix/fsync_test.go ++++ b/backend/posix/fsync_test.go +@@ -35,7 +35,7 @@ func recordSyncs(t *testing.T) (files *int, dirs *[]string) { + t.Cleanup(func() { syncFile, syncDir = origFile, origDir }) + files, dirs = new(int), new([]string) + syncFile = func(f *os.File) error { *files++; return origFile(f) } +- syncDir = func(dir string) error { *dirs = append(*dirs, dir); return origDir(dir) } ++ syncDir = func(fsys *rootFS, dir string) error { *dirs = append(*dirs, dir); return origDir(fsys, dir) } + return files, dirs + } + +diff --git a/backend/posix/keyname.go b/backend/posix/keyname.go +index e289cdc..2872614 100644 +--- a/backend/posix/keyname.go ++++ b/backend/posix/keyname.go +@@ -16,7 +16,6 @@ package posix + + import ( + "io/fs" +- "os" + "slices" + "strings" + "unicode/utf8" +@@ -62,7 +61,7 @@ func (p *Posix) decodeKey(name string) string { + // bucketFS returns the file system of the bucket directory with the entries + // named after the keys they store. + func (p *Posix) bucketFS(bucket string) fs.FS { +- fsys := os.DirFS(p.BucketPath(bucket)) ++ fsys := p.fsys.bucketFS(p.BucketPath(bucket)) + if !p.encodeKeys { + return fsys + } +diff --git a/backend/posix/nofollow_linux.go b/backend/posix/nofollow_linux.go +new file mode 100644 +index 0000000..e5a4614 +--- /dev/null ++++ b/backend/posix/nofollow_linux.go +@@ -0,0 +1,286 @@ ++// Copyright 2026 s3-gateway contributors ++// This file is licensed under the Apache License, Version 2.0 ++// (the "License"); you may not use this file except in compliance ++// with the License. You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, ++// software distributed under the License is distributed on an ++// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++// KIND, either express or implied. See the License for the ++// specific language governing permissions and limitations ++// under the License. ++ ++//go:build linux ++ ++package posix ++ ++import ( ++ "errors" ++ "fmt" ++ "io/fs" ++ "os" ++ "slices" ++ "strconv" ++ "strings" ++ "sync/atomic" ++ "time" ++ ++ "github.com/pkg/xattr" ++ "github.com/versity/versitygw/debuglogger" ++ "golang.org/x/sys/unix" ++) ++ ++// dirPathFlags open a directory on the way: O_PATH, so it needs no read ++// permission and is only a place to resolve the next element from. ++const dirPathFlags = unix.O_PATH | unix.O_DIRECTORY | unix.O_CLOEXEC ++ ++// noOpenat2 is set once openat2 is found missing (ENOSYS, before Linux ++// 5.6), after which directories are opened one element at a time. Tests set ++// it to run the fallback. ++var noOpenat2 atomic.Bool ++ ++// checkNoFollowSupport checks for /proc/self/fd, through which the backend ++// reopens the files it resolved and reaches their extended attributes. ++func checkNoFollowSupport() error { ++ if _, err := os.Stat(procSelfFD); err != nil { ++ return fmt.Errorf("the posix backend needs %v (is /proc mounted?): %w", procSelfFD, err) ++ } ++ return nil ++} ++ ++const procSelfFD = "/proc/self/fd" ++ ++func procPath(fd int) string { ++ return procSelfFD + "/" + strconv.Itoa(fd) ++} ++ ++// beneath opens the directory rel below dirfd, following no symbolic link. ++func beneath(dirfd int, rel string) (int, error) { ++ if !noOpenat2.Load() { ++ fd, err, fallback := openat2Beneath(dirfd, rel) ++ if !fallback { ++ return fd, err ++ } ++ } ++ return walkBeneath(dirfd, rel, dirPathFlags|unix.O_NOFOLLOW) ++} ++ ++// openat2Beneath opens rel below dirfd with openat2. fallback is set when ++// the element-by-element walk has to do it instead: openat2 is missing, a ++// seccomp filter refuses it (EPERM), or it keeps asking for a retry. ++func openat2Beneath(dirfd int, rel string) (fd int, err error, fallback bool) { ++ how := unix.OpenHow{ ++ Flags: dirPathFlags, ++ Resolve: unix.RESOLVE_NO_SYMLINKS | unix.RESOLVE_BENEATH | unix.RESOLVE_NO_MAGICLINKS, ++ } ++ for try := 0; ; try++ { ++ fd, err := unix.Openat2(dirfd, rel, &how) ++ switch { ++ case err == unix.EINTR: ++ continue ++ case err == unix.EAGAIN && try < 64: ++ // RESOLVE_BENEATH saw a concurrent rename or mount ++ continue ++ case err == unix.ENOSYS: ++ if !noOpenat2.Swap(true) { ++ debuglogger.Logf("posix: openat2 is not available, resolving paths one element at a time") ++ } ++ return -1, err, true ++ case err == unix.EPERM || err == unix.EAGAIN: ++ return -1, err, true ++ } ++ return fd, err, false ++ } ++} ++ ++// dirFileName is the name of the directory file of fd: the descriptor's ++// /proc path, so that the lstat that os.File.ReadDir makes of an entry whose ++// type the directory did not report resolves through the descriptor too. ++func dirFileName(fd int, _ string) string { ++ return procPath(fd) ++} ++ ++// openExisting opens the existing element a with flag, if it is a regular ++// file or a directory. It is first opened with O_PATH, which never opens a ++// FIFO or a device, and checked; only then is that very file opened with ++// flag, through its descriptor. ++func openExisting(a at, name string, flag int) (int, error) { ++ pflags := unix.O_PATH | unix.O_CLOEXEC ++ if !a.follow { ++ pflags |= unix.O_NOFOLLOW ++ } ++ pfd, err := openat(a.dir.fd, a.name, pflags, 0) ++ if err != nil { ++ return -1, &fs.PathError{Op: "open", Path: name, Err: err} ++ } ++ defer unix.Close(pfd) ++ var st unix.Stat_t ++ if err := ignoringEINTR(func() error { return unix.Fstat(pfd, &st) }); err != nil { ++ return -1, &fs.PathError{Op: "open", Path: name, Err: err} ++ } ++ mode := fileModeOf(st.Mode) ++ if !isObjectMode(mode) { ++ return -1, hidden("open", name, mode) ++ } ++ if flag&unix.O_DIRECTORY != 0 && !mode.IsDir() { ++ return -1, &fs.PathError{Op: "open", Path: name, Err: unix.ENOTDIR} ++ } ++ flag &^= unix.O_NOFOLLOW | unix.O_CREAT | unix.O_EXCL ++ for { ++ fd, err := unix.Open(procPath(pfd), flag|unix.O_CLOEXEC, 0) ++ if err == unix.EINTR { ++ continue ++ } ++ if err != nil { ++ return -1, &fs.PathError{Op: "open", Path: name, Err: err} ++ } ++ return fd, nil ++ } ++} ++ ++// openTmpfile opens an unnamed temporary file (O_TMPFILE, which flags hold) ++// in the directory dir. ++func (r *rootFS) openTmpfile(dir string, flags int, perm uint32) (int, error) { ++ d, err := r.dirAt("open", dir) ++ if err != nil { ++ return -1, err ++ } ++ defer d.close() ++ fd, err := openat(d.fd, ".", flags, perm) ++ if err != nil { ++ return -1, &fs.PathError{Op: "open", Path: dir, Err: err} ++ } ++ return fd, nil ++} ++ ++// xattrPath is the path the extended attribute calls take for the element ++// a: its name in its directory's descriptor, so that the l-calls follow ++// nothing but that descriptor. ++func xattrPath(a at) string { ++ return procPath(a.dir.fd) + "/" + a.name ++} ++ ++// noObjectAt returns the error that reports the element a missing if it is ++// no regular file or directory, nil if it is one. The extended attribute ++// calls ask it when the kernel's answer may mean that a is of another kind, ++// which can hold no user attributes. ++func noObjectAt(a at, name string) error { ++ fi, err := lstatAt(a, name) ++ if err != nil { ++ return &fs.PathError{Op: "lstat", Path: name, Err: err} ++ } ++ if !isObjectMode(fi.Mode()) { ++ return hidden("xattr", name, fi.Mode()) ++ } ++ return nil ++} ++ ++func (r *rootFS) getXattr(name, attr string) ([]byte, error) { ++ a, err := r.resolve("xattr.get", name) ++ if err != nil { ++ return nil, err ++ } ++ defer a.close() ++ var b []byte ++ if a.follow { ++ b, err = xattr.Get(xattrPath(a), attr) ++ } else { ++ b, err = xattr.LGet(xattrPath(a), attr) ++ } ++ if err == nil { ++ return b, nil ++ } ++ // The kernel refuses user attributes on anything but regular files and ++ // directories (ENODATA to read, EPERM to write). ++ if xattrErrIs(err, xattr.ENOATTR, unix.EPERM) { ++ if herr := noObjectAt(a, name); herr != nil { ++ return nil, herr ++ } ++ } ++ return nil, xattrErr("xattr.get", name, attr, err) ++} ++ ++func (r *rootFS) setXattr(name, attr string, value []byte) error { ++ a, err := r.resolve("xattr.set", name) ++ if err != nil { ++ return err ++ } ++ defer a.close() ++ if a.follow { ++ err = xattr.Set(xattrPath(a), attr, value) ++ } else { ++ err = xattr.LSet(xattrPath(a), attr, value) ++ } ++ if err == nil { ++ return nil ++ } ++ if xattrErrIs(err, unix.EPERM) { ++ if herr := noObjectAt(a, name); herr != nil { ++ return herr ++ } ++ } ++ return xattrErr("xattr.set", name, attr, err) ++} ++ ++func (r *rootFS) removeXattr(name, attr string) error { ++ a, err := r.resolve("xattr.remove", name) ++ if err != nil { ++ return err ++ } ++ defer a.close() ++ if a.follow { ++ err = xattr.Remove(xattrPath(a), attr) ++ } else { ++ err = xattr.LRemove(xattrPath(a), attr) ++ } ++ if err == nil { ++ return nil ++ } ++ if xattrErrIs(err, xattr.ENOATTR, unix.EPERM) { ++ if herr := noObjectAt(a, name); herr != nil { ++ return herr ++ } ++ } ++ return xattrErr("xattr.remove", name, attr, err) ++} ++ ++func (r *rootFS) listXattr(name string) ([]string, error) { ++ a, err := r.resolve("xattr.list", name) ++ if err != nil { ++ return nil, err ++ } ++ defer a.close() ++ var attrs []string ++ if a.follow { ++ attrs, err = xattr.List(xattrPath(a)) ++ } else { ++ attrs, err = xattr.LList(xattrPath(a)) ++ } ++ if err != nil { ++ return nil, xattrErr("xattr.list", name, "", err) ++ } ++ // Only regular files and directories hold user attributes: an entry ++ // without any may be another kind, which is reported missing. ++ if !hasUserXattr(attrs) { ++ if herr := noObjectAt(a, name); herr != nil { ++ return nil, herr ++ } ++ } ++ return attrs, nil ++} ++ ++// hasUserXattr reports whether attrs holds an attribute of the user ++// namespace. ++func hasUserXattr(attrs []string) bool { ++ return slices.ContainsFunc(attrs, func(attr string) bool { return strings.HasPrefix(attr, "user.") }) ++} ++ ++func xattrErrIs(err error, errnos ...unix.Errno) bool { ++ return slices.ContainsFunc(errnos, func(errno unix.Errno) bool { return errors.Is(err, errno) }) ++} ++ ++func statMtime(st *unix.Stat_t) time.Time { ++ return time.Unix(st.Mtim.Unix()) ++} +diff --git a/backend/posix/nofollow_linux_test.go b/backend/posix/nofollow_linux_test.go +new file mode 100644 +index 0000000..58770f3 +--- /dev/null ++++ b/backend/posix/nofollow_linux_test.go +@@ -0,0 +1,898 @@ ++// Copyright 2026 s3-gateway contributors ++// This file is licensed under the Apache License, Version 2.0 ++// (the "License"); you may not use this file except in compliance ++// with the License. You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, ++// software distributed under the License is distributed on an ++// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++// KIND, either express or implied. See the License for the ++// specific language governing permissions and limitations ++// under the License. ++ ++//go:build linux ++ ++package posix ++ ++import ( ++ "bytes" ++ "context" ++ "errors" ++ "fmt" ++ "io" ++ "io/fs" ++ "os" ++ "path/filepath" ++ "regexp" ++ "slices" ++ "strings" ++ "sync" ++ "sync/atomic" ++ "testing" ++ "time" ++ ++ "github.com/aws/aws-sdk-go-v2/aws" ++ "github.com/aws/aws-sdk-go-v2/service/s3" ++ "github.com/aws/aws-sdk-go-v2/service/s3/types" ++ "github.com/pkg/xattr" ++ "github.com/versity/versitygw/backend/meta" ++ "github.com/versity/versitygw/s3err" ++ "github.com/versity/versitygw/s3response" ++ "golang.org/x/sys/unix" ++) ++ ++const ( ++ insideData = "this bucket's own data" ++ outsideData = "the other namespace's marker" ++) ++ ++// noFollowFixture is a gateway root with the bucket home, which holds two ++// objects (real.txt, dir/x.txt) and, planted beside them as a host user ++// could plant them: ++// ++// link-abs -> /secret.txt (absolute) ++// link-rel -> ../other/secret.txt (relative, to another bucket) ++// link-dir -> /dir (a directory) ++// sub/link-dir-rel -> ../../other (a directory, relative) ++// fifo, sock a FIFO and a socket ++// dev /dev/null's device (as root only) ++// ++// is another namespace's directory outside the root. Its files ++// carry an ETag attribute, so a listing that read through a link would show ++// it. ++type noFollowFixture struct { ++ p *Posix ++ root string ++ outside string ++ bucket string ++ nonObj []string // the keys of the planted entries that are no objects ++} ++ ++func newNoFollowFixture(t *testing.T, opts PosixOpts) *noFollowFixture { ++ t.Helper() ++ root, outside := t.TempDir(), t.TempDir() ++ mustWrite(t, filepath.Join(outside, "secret.txt"), outsideData) ++ mustMkdir(t, filepath.Join(outside, "dir")) ++ mustWrite(t, filepath.Join(outside, "dir", "inner.txt"), outsideData) ++ mustMkdir(t, filepath.Join(outside, "stage")) ++ for _, name := range []string{"secret.txt", "dir", "dir/inner.txt"} { ++ if err := xattr.Set(filepath.Join(outside, name), "user.etag", []byte(`"outside"`)); err != nil { ++ t.Skipf("the test directory takes no user extended attributes (set TMPDIR to xfs or ext4): %v", err) ++ } ++ } ++ ++ opts.NewDirPerm = 0755 ++ opts.CopyObjectThreshold = 5 << 30 ++ p, err := New(root, meta.XattrMeta{}, opts) ++ if err != nil { ++ t.Fatalf("new posix: %v", err) ++ } ++ t.Cleanup(p.Shutdown) ++ f := &noFollowFixture{p: p, root: root, outside: outside, bucket: "home"} ++ createTestBucket(t, p, "home") ++ createTestBucket(t, p, "other") ++ f.put(t, "other", "secret.txt", outsideData) ++ f.put(t, "home", "real.txt", insideData) ++ f.put(t, "home", "dir/x.txt", insideData) ++ ++ b := filepath.Join(root, "home") ++ mustMkdir(t, filepath.Join(b, "sub")) ++ mustSymlink(t, filepath.Join(outside, "secret.txt"), filepath.Join(b, "link-abs")) ++ mustSymlink(t, "../other/secret.txt", filepath.Join(b, "link-rel")) ++ mustSymlink(t, filepath.Join(outside, "dir"), filepath.Join(b, "link-dir")) ++ mustSymlink(t, "../../other", filepath.Join(b, "sub", "link-dir-rel")) ++ if err := unix.Mkfifo(filepath.Join(b, "fifo"), 0644); err != nil { ++ t.Fatalf("mkfifo: %v", err) ++ } ++ if err := unix.Mknod(filepath.Join(b, "sock"), unix.S_IFSOCK|0644, 0); err != nil { ++ t.Fatalf("mknod socket: %v", err) ++ } ++ f.nonObj = []string{"link-abs", "link-rel", "link-dir", "fifo", "sock"} ++ if os.Geteuid() == 0 { ++ if err := unix.Mknod(filepath.Join(b, "dev"), unix.S_IFCHR|0644, int(unix.Mkdev(1, 3))); err != nil { ++ t.Fatalf("mknod device: %v", err) ++ } ++ f.nonObj = append(f.nonObj, "dev") ++ } ++ return f ++} ++ ++// throughLinks are keys whose path runs through a link to a directory. ++var throughLinks = []string{"link-dir/inner.txt", "sub/link-dir-rel/secret.txt", "link-dir/"} ++ ++func (f *noFollowFixture) put(t *testing.T, bucket, key, data string) { ++ t.Helper() ++ if _, err := testPut(f.p, bucket, key, []byte(data), nil, nil); err != nil { ++ t.Fatalf("put %v/%v: %v", bucket, key, err) ++ } ++} ++ ++func (f *noFollowFixture) path(name string) string { ++ return filepath.Join(f.root, f.bucket, name) ++} ++ ++// unchanged checks that the other namespace and the other bucket are as the ++// fixture made them. ++func (f *noFollowFixture) unchanged(t *testing.T) { ++ t.Helper() ++ for _, name := range []string{"secret.txt", "dir/inner.txt"} { ++ if got := mustRead(t, filepath.Join(f.outside, name)); got != outsideData { ++ t.Errorf("%v outside the root now holds %q", name, got) ++ } ++ if got, err := userXattrs(filepath.Join(f.outside, name)); err != nil || !slices.Equal(got, []string{"user.etag"}) { ++ t.Errorf("%v outside the root now has attributes %v (%v)", name, got, err) ++ } ++ } ++ for _, dir := range []string{"dir", "stage"} { ++ ents, _ := os.ReadDir(filepath.Join(f.outside, dir)) ++ var names []string ++ for _, e := range ents { ++ names = append(names, e.Name()) ++ } ++ want := map[string][]string{"dir": {"inner.txt"}, "stage": nil}[dir] ++ if !slices.Equal(names, want) { ++ t.Errorf("%v outside the root now holds %v, want %v", dir, names, want) ++ } ++ } ++ if got := mustRead(t, filepath.Join(f.root, "other", "secret.txt")); got != outsideData { ++ t.Errorf("other/secret.txt now holds %q", got) ++ } ++ if ents, _ := os.ReadDir(filepath.Join(f.root, "other")); len(ents) != 1 && !(len(ents) == 2 && ents[0].Name() == MetaTmpDir) { ++ t.Errorf("bucket other now holds %v", ents) ++ } ++} ++ ++// forEachResolver runs fn with openat2 and with the element-by-element walk ++// that stands in for it, and with relative and with absolute paths. ++func forEachResolver(t *testing.T, fn func(t *testing.T, opts PosixOpts)) { ++ for _, walk := range []bool{false, true} { ++ for _, abs := range []bool{false, true} { ++ name := fmt.Sprintf("openat2/abs=%v", abs) ++ if walk { ++ name = fmt.Sprintf("walk/abs=%v", abs) ++ } ++ t.Run(name, func(t *testing.T) { ++ old := noOpenat2.Load() ++ noOpenat2.Store(walk) ++ t.Cleanup(func() { noOpenat2.Store(old) }) ++ fn(t, PosixOpts{AbsolutePaths: abs}) ++ }) ++ } ++ } ++} ++ ++func apiCode(err error) string { ++ var nv s3err.NoSuchVersionError ++ if errors.As(err, &nv) { ++ return nv.Code ++ } ++ var ae s3err.APIError ++ if errors.As(err, &ae) { ++ return ae.Code ++ } ++ if err == nil { ++ return "no error" ++ } ++ // the bucket errors and others render the API error's XML ++ if m := regexp.MustCompile(`([^<]*)`).FindStringSubmatch(err.Error()); m != nil { ++ return m[1] ++ } ++ return err.Error() ++} ++ ++// within runs fn and fails the test if it does not return in 10 s: a FIFO ++// that the backend opened for reading would block it. ++func within(t *testing.T, what string, fn func()) { ++ t.Helper() ++ done := make(chan struct{}) ++ go func() { defer close(done); fn() }() ++ select { ++ case <-done: ++ case <-time.After(10 * time.Second): ++ t.Fatalf("%v did not return: something was opened that blocks", what) ++ } ++} ++ ++func TestNoFollowReads(t *testing.T) { ++ forEachResolver(t, func(t *testing.T, opts PosixOpts) { ++ f := newNoFollowFixture(t, opts) ++ ctx := context.Background() ++ b := f.bucket ++ for _, key := range append(slices.Clone(f.nonObj), throughLinks...) { ++ t.Run(key, func(t *testing.T) { ++ within(t, "GetObject "+key, func() { ++ out, err := f.p.GetObject(ctx, &s3.GetObjectInput{Bucket: &b, Key: aws.String(key)}) ++ if err == nil { ++ data, _ := io.ReadAll(out.Body) ++ out.Body.Close() ++ t.Errorf("GetObject %v: served %q", key, data) ++ } else if apiCode(err) != "NoSuchKey" { ++ t.Errorf("GetObject %v: got %v, want NoSuchKey", key, err) ++ } ++ }) ++ within(t, "HeadObject "+key, func() { ++ _, err := f.p.HeadObject(ctx, &s3.HeadObjectInput{Bucket: &b, Key: aws.String(key)}) ++ if apiCode(err) != "NoSuchKey" { ++ t.Errorf("HeadObject %v: got %v, want NoSuchKey", key, err) ++ } ++ }) ++ within(t, "GetObjectAttributes "+key, func() { ++ _, err := f.p.GetObjectAttributes(ctx, &s3.GetObjectAttributesInput{ ++ Bucket: &b, Key: aws.String(key), ++ ObjectAttributes: []types.ObjectAttributes{types.ObjectAttributesEtag, types.ObjectAttributesObjectSize}, ++ }) ++ if apiCode(err) != "NoSuchKey" { ++ t.Errorf("GetObjectAttributes %v: got %v, want NoSuchKey", key, err) ++ } ++ }) ++ within(t, "GetObjectTagging "+key, func() { ++ _, err := f.p.GetObjectTagging(ctx, b, key, "") ++ if apiCode(err) != "NoSuchKey" { ++ t.Errorf("GetObjectTagging %v: got %v, want NoSuchKey", key, err) ++ } ++ }) ++ within(t, "CopyObject from "+key, func() { ++ _, err := f.p.CopyObject(ctx, s3response.CopyObjectInput{ ++ Bucket: &b, Key: aws.String("copied.txt"), CopySource: aws.String(b + "/" + key), ++ ExpectedBucketOwner: aws.String(""), MetadataDirective: types.MetadataDirectiveCopy, ++ }) ++ if apiCode(err) != "NoSuchKey" { ++ t.Errorf("CopyObject from %v: got %v, want NoSuchKey", key, err) ++ } ++ }) ++ within(t, "UploadPartCopy from "+key, func() { ++ mp, err := f.p.CreateMultipartUpload(ctx, s3response.CreateMultipartUploadInput{Bucket: &b, Key: aws.String("mp.txt")}) ++ if err != nil { ++ t.Fatalf("create multipart upload: %v", err) ++ } ++ _, err = f.p.UploadPartCopy(ctx, &s3.UploadPartCopyInput{ ++ Bucket: &b, Key: aws.String("mp.txt"), UploadId: &mp.UploadId, PartNumber: aws.Int32(1), ++ CopySource: aws.String(b + "/" + key), CopySourceRange: aws.String(""), ++ }) ++ if apiCode(err) != "NoSuchKey" { ++ t.Errorf("UploadPartCopy from %v: got %v, want NoSuchKey", key, err) ++ } ++ f.p.AbortMultipartUpload(ctx, &s3.AbortMultipartUploadInput{Bucket: &b, Key: aws.String("mp.txt"), UploadId: &mp.UploadId}) ++ }) ++ }) ++ } ++ // the real objects still read ++ if data, _ := getTestObject(t, f.p, b, "real.txt"); string(data) != insideData { ++ t.Errorf("real.txt: got %q", data) ++ } ++ f.unchanged(t) ++ }) ++} ++ ++func TestNoFollowListings(t *testing.T) { ++ forEachResolver(t, func(t *testing.T, opts PosixOpts) { ++ f := newNoFollowFixture(t, opts) ++ ctx := context.Background() ++ b := f.bucket ++ keys := func(objs []s3response.Object) []string { ++ var out []string ++ for _, o := range objs { ++ out = append(out, *o.Key) ++ } ++ return out ++ } ++ prefixes := func(cps []types.CommonPrefix) []string { ++ var out []string ++ for _, cp := range cps { ++ out = append(out, *cp.Prefix) ++ } ++ return out ++ } ++ ++ within(t, "ListObjectsV2", func() { ++ out, err := f.p.ListObjectsV2(ctx, &s3.ListObjectsV2Input{Bucket: &b, MaxKeys: aws.Int32(1000), StartAfter: aws.String("")}) ++ if err != nil { ++ t.Fatalf("ListObjectsV2: %v", err) ++ } ++ if got := keys(out.Contents); !slices.Equal(got, []string{"dir/x.txt", "real.txt"}) { ++ t.Errorf("ListObjectsV2: got %v", got) ++ } ++ for _, o := range out.Contents { ++ if strings.Contains(*o.ETag, "outside") { ++ t.Errorf("ListObjectsV2: %v has the other namespace's ETag", *o.Key) ++ } ++ } ++ }) ++ within(t, "ListObjectsV2 with a delimiter", func() { ++ out, err := f.p.ListObjectsV2(ctx, &s3.ListObjectsV2Input{Bucket: &b, Delimiter: aws.String("/"), MaxKeys: aws.Int32(1000), StartAfter: aws.String("")}) ++ if err != nil { ++ t.Fatalf("ListObjectsV2: %v", err) ++ } ++ if got := keys(out.Contents); !slices.Equal(got, []string{"real.txt"}) { ++ t.Errorf("ListObjectsV2 /: got %v", got) ++ } ++ if got := prefixes(out.CommonPrefixes); slices.Contains(got, "link-dir/") { ++ t.Errorf("ListObjectsV2 /: common prefixes %v hold the link", got) ++ } ++ }) ++ for _, prefix := range []string{"link-dir/", "link-dir/inner", "sub/link-dir-rel/", "sub/"} { ++ within(t, "ListObjectsV2 "+prefix, func() { ++ out, err := f.p.ListObjectsV2(ctx, &s3.ListObjectsV2Input{Bucket: &b, Prefix: aws.String(prefix), MaxKeys: aws.Int32(1000), StartAfter: aws.String("")}) ++ if err != nil { ++ t.Fatalf("ListObjectsV2 %v: %v", prefix, err) ++ } ++ if got := keys(out.Contents); len(got) != 0 { ++ t.Errorf("ListObjectsV2 %v: got %v", prefix, got) ++ } ++ }) ++ within(t, "ListObjects "+prefix, func() { ++ out, err := f.p.ListObjects(ctx, &s3.ListObjectsInput{Bucket: &b, Prefix: aws.String(prefix), MaxKeys: aws.Int32(1000)}) ++ if err != nil { ++ t.Fatalf("ListObjects %v: %v", prefix, err) ++ } ++ if got := keys(out.Contents); len(got) != 0 { ++ t.Errorf("ListObjects %v: got %v", prefix, got) ++ } ++ }) ++ } ++ within(t, "ListObjects", func() { ++ out, err := f.p.ListObjects(ctx, &s3.ListObjectsInput{Bucket: &b, MaxKeys: aws.Int32(1000)}) ++ if err != nil { ++ t.Fatalf("ListObjects: %v", err) ++ } ++ if got := keys(out.Contents); !slices.Equal(got, []string{"dir/x.txt", "real.txt"}) { ++ t.Errorf("ListObjects: got %v", got) ++ } ++ }) ++ within(t, "ListBuckets", func() { ++ out, err := f.p.ListBuckets(ctx, s3response.ListBucketsInput{IsAdmin: true, MaxBuckets: 1000}) ++ if err != nil { ++ t.Fatalf("ListBuckets: %v", err) ++ } ++ var names []string ++ for _, bk := range out.Buckets.Bucket { ++ names = append(names, bk.Name) ++ } ++ if !slices.Equal(names, []string{"home", "other"}) { ++ t.Errorf("ListBuckets: got %v", names) ++ } ++ }) ++ f.unchanged(t) ++ }) ++} ++ ++func TestNoFollowWrites(t *testing.T) { ++ forEachResolver(t, func(t *testing.T, opts PosixOpts) { ++ ctx := context.Background() ++ ++ t.Run("put replaces the entry", func(t *testing.T) { ++ f := newNoFollowFixture(t, opts) ++ for _, key := range f.nonObj { ++ within(t, "PutObject "+key, func() { ++ if _, err := testPut(f.p, f.bucket, key, []byte("new "+key), nil, nil); err != nil { ++ t.Fatalf("PutObject %v: %v", key, err) ++ } ++ }) ++ fi, err := os.Lstat(f.path(key)) ++ if err != nil || !fi.Mode().IsRegular() { ++ t.Fatalf("%v after the put: %v, %v", key, fi, err) ++ } ++ if data, _ := getTestObject(t, f.p, f.bucket, key); string(data) != "new "+key { ++ t.Errorf("GetObject %v: got %q", key, data) ++ } ++ } ++ f.unchanged(t) ++ }) ++ ++ t.Run("copy and complete replace the link", func(t *testing.T) { ++ f := newNoFollowFixture(t, opts) ++ b := f.bucket ++ _, err := f.p.CopyObject(ctx, s3response.CopyObjectInput{ ++ Bucket: &b, Key: aws.String("link-rel"), CopySource: aws.String(b + "/real.txt"), ++ ExpectedBucketOwner: aws.String(""), MetadataDirective: types.MetadataDirectiveCopy, ++ }) ++ if err != nil { ++ t.Fatalf("CopyObject to link-rel: %v", err) ++ } ++ if data, _ := getTestObject(t, f.p, b, "link-rel"); string(data) != insideData { ++ t.Errorf("link-rel after the copy: %q", data) ++ } ++ mp, err := f.p.CreateMultipartUpload(ctx, s3response.CreateMultipartUploadInput{Bucket: &b, Key: aws.String("link-abs")}) ++ if err != nil { ++ t.Fatalf("create multipart upload: %v", err) ++ } ++ part, err := f.p.UploadPart(ctx, &s3.UploadPartInput{ ++ Bucket: &b, Key: aws.String("link-abs"), UploadId: &mp.UploadId, PartNumber: aws.Int32(1), ++ Body: strings.NewReader("multipart"), ContentLength: aws.Int64(9), ++ }) ++ if err != nil { ++ t.Fatalf("upload part: %v", err) ++ } ++ _, _, err = f.p.CompleteMultipartUpload(ctx, &s3.CompleteMultipartUploadInput{ ++ Bucket: &b, Key: aws.String("link-abs"), UploadId: &mp.UploadId, ++ MultipartUpload: &types.CompletedMultipartUpload{Parts: []types.CompletedPart{{PartNumber: aws.Int32(1), ETag: part.ETag}}}, ++ }) ++ if err != nil { ++ t.Fatalf("complete multipart upload: %v", err) ++ } ++ if data, _ := getTestObject(t, f.p, b, "link-abs"); string(data) != "multipart" { ++ t.Errorf("link-abs after the upload: %q", data) ++ } ++ for _, key := range []string{"link-rel", "link-abs"} { ++ if fi, err := os.Lstat(f.path(key)); err != nil || !fi.Mode().IsRegular() { ++ t.Errorf("%v: %v, %v", key, fi, err) ++ } ++ } ++ f.unchanged(t) ++ }) ++ ++ t.Run("no write under a link", func(t *testing.T) { ++ f := newNoFollowFixture(t, opts) ++ b := f.bucket ++ for _, key := range []string{"link-dir/new.txt", "sub/link-dir-rel/new.txt", "link-dir/", "link-abs/x", "fifo/x"} { ++ within(t, "PutObject "+key, func() { ++ _, err := testPut(f.p, b, key, []byte{}, nil, nil) ++ if apiCode(err) != "ObjectParentIsFile" { ++ t.Errorf("PutObject %v: got %v, want ObjectParentIsFile", key, err) ++ } ++ }) ++ within(t, "CopyObject to "+key, func() { ++ _, err := f.p.CopyObject(ctx, s3response.CopyObjectInput{ ++ Bucket: &b, Key: aws.String(strings.TrimSuffix(key, "/") + "-copy"), CopySource: aws.String(b + "/real.txt"), ++ ExpectedBucketOwner: aws.String(""), MetadataDirective: types.MetadataDirectiveCopy, ++ }) ++ if strings.HasSuffix(key, "/") { ++ // the copy went to link-dir-copy, beside the link ++ return ++ } ++ if apiCode(err) != "ObjectParentIsFile" { ++ t.Errorf("CopyObject to %v: got %v, want ObjectParentIsFile", key, err) ++ } ++ }) ++ } ++ for _, key := range []string{"link-dir/mp.txt", "sub/link-dir-rel/mp.txt"} { ++ mp, err := f.p.CreateMultipartUpload(ctx, s3response.CreateMultipartUploadInput{Bucket: &b, Key: aws.String(key)}) ++ if err != nil { ++ t.Fatalf("create multipart upload %v: %v", key, err) ++ } ++ part, err := f.p.UploadPart(ctx, &s3.UploadPartInput{ ++ Bucket: &b, Key: aws.String(key), UploadId: &mp.UploadId, PartNumber: aws.Int32(1), ++ Body: strings.NewReader("multipart"), ContentLength: aws.Int64(9), ++ }) ++ if err != nil { ++ t.Fatalf("upload part %v: %v", key, err) ++ } ++ _, _, err = f.p.CompleteMultipartUpload(ctx, &s3.CompleteMultipartUploadInput{ ++ Bucket: &b, Key: aws.String(key), UploadId: &mp.UploadId, ++ MultipartUpload: &types.CompletedMultipartUpload{Parts: []types.CompletedPart{{PartNumber: aws.Int32(1), ETag: part.ETag}}}, ++ }) ++ if apiCode(err) != "ObjectParentIsFile" { ++ t.Errorf("CompleteMultipartUpload %v: got %v, want ObjectParentIsFile", key, err) ++ } ++ } ++ for _, key := range append(slices.Clone(f.nonObj), throughLinks...) { ++ err := f.p.PutObjectTagging(ctx, b, key, "", map[string]string{"k": "v"}) ++ if apiCode(err) != "NoSuchKey" { ++ t.Errorf("PutObjectTagging %v: got %v, want NoSuchKey", key, err) ++ } ++ } ++ // the links are still there ++ for _, key := range []string{"link-dir", "sub/link-dir-rel"} { ++ if fi, err := os.Lstat(f.path(key)); err != nil || fi.Mode()&fs.ModeSymlink == 0 { ++ t.Errorf("%v: %v, %v", key, fi, err) ++ } ++ } ++ f.unchanged(t) ++ }) ++ ++ t.Run("a link as the staging directory", func(t *testing.T) { ++ f := newNoFollowFixture(t, opts) ++ b := f.bucket ++ if err := os.RemoveAll(f.path(MetaTmpDir)); err != nil { ++ t.Fatal(err) ++ } ++ mustSymlink(t, filepath.Join(f.outside, "stage"), f.path(MetaTmpDir)) ++ if _, err := testPut(f.p, b, "staged.txt", []byte(insideData), nil, nil); err == nil { ++ t.Errorf("PutObject staged through %v: no error", MetaTmpDir) ++ } ++ if _, err := f.p.CreateMultipartUpload(ctx, s3response.CreateMultipartUploadInput{Bucket: &b, Key: aws.String("staged-mp")}); err == nil { ++ t.Errorf("CreateMultipartUpload staged through %v: no error", MetaTmpDir) ++ } ++ f.unchanged(t) ++ }) ++ }) ++} ++ ++func TestNoFollowDeletes(t *testing.T) { ++ forEachResolver(t, func(t *testing.T, opts PosixOpts) { ++ ctx := context.Background() ++ f := newNoFollowFixture(t, opts) ++ b := f.bucket ++ for _, key := range throughLinks { ++ within(t, "DeleteObject "+key, func() { ++ if _, err := f.p.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: &b, Key: aws.String(key)}); err != nil { ++ t.Errorf("DeleteObject %v: %v", key, err) ++ } ++ }) ++ } ++ // a trailing slash names a directory object, which a link is not ++ if _, err := f.p.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: &b, Key: aws.String("link-dir/")}); err != nil { ++ t.Errorf("DeleteObject link-dir/: %v", err) ++ } ++ if _, err := os.Lstat(f.path("link-dir")); err != nil { ++ t.Errorf("DeleteObject link-dir/ removed the link: %v", err) ++ } ++ f.unchanged(t) ++ ++ for _, key := range f.nonObj[:len(f.nonObj)-1] { ++ within(t, "DeleteObject "+key, func() { ++ if _, err := f.p.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: &b, Key: aws.String(key)}); err != nil { ++ t.Errorf("DeleteObject %v: %v", key, err) ++ } ++ }) ++ if _, err := os.Lstat(f.path(key)); !errors.Is(err, fs.ErrNotExist) { ++ t.Errorf("%v after its delete: %v", key, err) ++ } ++ } ++ last := f.nonObj[len(f.nonObj)-1] ++ res, err := f.p.DeleteObjects(ctx, &s3.DeleteObjectsInput{Bucket: &b, Delete: &types.Delete{ ++ Objects: []types.ObjectIdentifier{{Key: aws.String(last)}}, ++ }}) ++ if err != nil || len(res.Error) != 0 { ++ t.Errorf("DeleteObjects %v: %v, %+v", last, err, res.Error) ++ } ++ if _, err := os.Lstat(f.path(last)); !errors.Is(err, fs.ErrNotExist) { ++ t.Errorf("%v after its delete: %v", last, err) ++ } ++ f.unchanged(t) ++ }) ++} ++ ++func TestNoFollowBucketLinks(t *testing.T) { ++ forEachResolver(t, func(t *testing.T, opts PosixOpts) { ++ ctx := context.Background() ++ for _, bucketlinks := range []bool{false, true} { ++ t.Run(fmt.Sprintf("bucketlinks=%v", bucketlinks), func(t *testing.T) { ++ opts := opts ++ opts.BucketLinks = bucketlinks ++ f := newNoFollowFixture(t, opts) ++ linked := filepath.Join(f.outside, "linked") ++ mustMkdir(t, linked) ++ mustWrite(t, filepath.Join(linked, "file.txt"), "in the linked bucket") ++ mustSymlink(t, filepath.Join(f.outside, "secret.txt"), filepath.Join(linked, "inner-link")) ++ mustSymlink(t, linked, filepath.Join(f.root, "linked")) ++ bucket := "linked" ++ ++ _, err := f.p.HeadBucket(ctx, &s3.HeadBucketInput{Bucket: &bucket}) ++ if !bucketlinks { ++ if apiCode(err) != "NoSuchBucket" { ++ t.Errorf("HeadBucket linked: got %v, want NoSuchBucket", err) ++ } ++ _, err := f.p.GetObject(ctx, &s3.GetObjectInput{Bucket: &bucket, Key: aws.String("file.txt")}) ++ if apiCode(err) != "NoSuchBucket" { ++ t.Errorf("GetObject linked/file.txt: got %v, want NoSuchBucket", err) ++ } ++ return ++ } ++ if err != nil { ++ t.Fatalf("HeadBucket linked: %v", err) ++ } ++ if data, _ := getTestObject(t, f.p, bucket, "file.txt"); string(data) != "in the linked bucket" { ++ t.Errorf("GetObject linked/file.txt: %q", data) ++ } ++ _, err = f.p.GetObject(ctx, &s3.GetObjectInput{Bucket: &bucket, Key: aws.String("inner-link")}) ++ if apiCode(err) != "NoSuchKey" { ++ t.Errorf("GetObject linked/inner-link: got %v, want NoSuchKey", err) ++ } ++ out, err := f.p.ListObjectsV2(ctx, &s3.ListObjectsV2Input{Bucket: &bucket, MaxKeys: aws.Int32(1000), StartAfter: aws.String("")}) ++ if err != nil || len(out.Contents) != 1 || *out.Contents[0].Key != "file.txt" { ++ t.Errorf("ListObjectsV2 linked: %+v, %v", out.Contents, err) ++ } ++ if err := f.p.PutBucketTagging(ctx, bucket, map[string]string{"k": "v"}); err != nil { ++ t.Fatalf("PutBucketTagging linked: %v", err) ++ } ++ if tags, err := f.p.GetBucketTagging(ctx, bucket); err != nil || tags["k"] != "v" { ++ t.Errorf("GetBucketTagging linked: %v, %v", tags, err) ++ } ++ f.put(t, bucket, "new.txt", "new") ++ if got := mustRead(t, filepath.Join(linked, "new.txt")); got != "new" { ++ t.Errorf("linked/new.txt: %q", got) ++ } ++ }) ++ } ++ }) ++} ++ ++func TestNoFollowVersions(t *testing.T) { ++ forEachResolver(t, func(t *testing.T, opts PosixOpts) { ++ ctx := context.Background() ++ opts.VersioningDir = t.TempDir() ++ f := newNoFollowFixture(t, opts) ++ b := f.bucket ++ if err := f.p.PutBucketVersioning(ctx, b, types.BucketVersioningStatusEnabled); err != nil { ++ t.Fatalf("put bucket versioning: %v", err) ++ } ++ first, err := testPut(f.p, b, "v.txt", []byte("first"), nil, nil) ++ if err != nil { ++ t.Fatal(err) ++ } ++ if _, err := testPut(f.p, b, "v.txt", []byte("second"), nil, nil); err != nil { ++ t.Fatal(err) ++ } ++ // the first version, in the versioning directory, made a link ++ vpath := filepath.Join(opts.VersioningDir, b, genObjVersionKey("v.txt"), first.VersionID) ++ if err := os.Remove(vpath); err != nil { ++ t.Fatalf("remove the first version: %v", err) ++ } ++ mustSymlink(t, filepath.Join(f.outside, "secret.txt"), vpath) ++ _, err = f.p.GetObject(ctx, &s3.GetObjectInput{Bucket: &b, Key: aws.String("v.txt"), VersionId: aws.String(first.VersionID)}) ++ if apiCode(err) != "NoSuchVersion" { ++ t.Errorf("GetObject of the linked version: got %v, want NoSuchVersion", err) ++ } ++ // a link at the key: a put snapshots no version of it ++ mustSymlink(t, filepath.Join(f.outside, "secret.txt"), f.path("snap.txt")) ++ if _, err := testPut(f.p, b, "snap.txt", []byte("snap"), nil, nil); err != nil { ++ t.Fatal(err) ++ } ++ vers, err := f.p.ListObjectVersions(ctx, &s3.ListObjectVersionsInput{Bucket: &b, Prefix: aws.String("snap.txt"), MaxKeys: aws.Int32(1000)}) ++ if err != nil || len(vers.Versions) != 1 { ++ t.Errorf("ListObjectVersions snap.txt: %+v, %v", vers.Versions, err) ++ } ++ f.unchanged(t) ++ }) ++} ++ ++// TestNoFollowSwapRace swaps a directory of the bucket with a link to a ++// directory outside the root as fast as it can while it reads, writes and ++// deletes under it: no call may reach the other side. ++func TestNoFollowSwapRace(t *testing.T) { ++ forEachResolver(t, func(t *testing.T, opts PosixOpts) { ++ ctx := context.Background() ++ f := newNoFollowFixture(t, opts) ++ b := f.bucket ++ f.put(t, b, "race/obj.txt", insideData) ++ outdir := filepath.Join(f.outside, "racedir") ++ mustMkdir(t, outdir) ++ mustWrite(t, filepath.Join(outdir, "obj.txt"), outsideData) ++ mustWrite(t, filepath.Join(outdir, "victim.txt"), outsideData) ++ mustSymlink(t, outdir, f.path("race-alt")) ++ ++ var stop atomic.Bool ++ var swaps atomic.Int64 ++ var wg sync.WaitGroup ++ wg.Add(1) ++ go func() { ++ defer wg.Done() ++ for !stop.Load() { ++ if err := unix.Renameat2(unix.AT_FDCWD, f.path("race"), unix.AT_FDCWD, f.path("race-alt"), unix.RENAME_EXCHANGE); err != nil { ++ t.Errorf("swap: %v", err) ++ return ++ } ++ swaps.Add(1) ++ } ++ }() ++ ++ deadline := time.Now().Add(3 * time.Second) ++ var reads, served int ++ for i := 0; time.Now().Before(deadline); i++ { ++ out, err := f.p.GetObject(ctx, &s3.GetObjectInput{Bucket: &b, Key: aws.String("race/obj.txt")}) ++ reads++ ++ if err == nil { ++ data, _ := io.ReadAll(out.Body) ++ out.Body.Close() ++ served++ ++ if string(data) != insideData { ++ t.Fatalf("GetObject race/obj.txt served %q", data) ++ } ++ } ++ testPut(f.p, b, fmt.Sprintf("race/new-%d.txt", i%50), []byte(insideData), nil, nil) ++ f.p.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: &b, Key: aws.String("race/victim.txt")}) ++ f.p.PutObjectTagging(ctx, b, "race/obj.txt", "", map[string]string{"k": "v"}) ++ } ++ stop.Store(true) ++ wg.Wait() ++ t.Logf("%d swaps, %d reads, %d served", swaps.Load(), reads, served) ++ ++ ents, _ := os.ReadDir(outdir) ++ var names []string ++ for _, e := range ents { ++ names = append(names, e.Name()) ++ } ++ if !slices.Equal(names, []string{"obj.txt", "victim.txt"}) { ++ t.Errorf("the directory outside the root now holds %v", names) ++ } ++ for _, name := range names { ++ if got := mustRead(t, filepath.Join(outdir, name)); got != outsideData { ++ t.Errorf("%v outside the root now holds %q", name, got) ++ } ++ if attrs, _ := userXattrs(filepath.Join(outdir, name)); len(attrs) != 0 { ++ t.Errorf("%v outside the root now has attributes %v", name, attrs) ++ } ++ } ++ f.unchanged(t) ++ }) ++} ++ ++// TestRootFS checks the file system calls directly. ++func TestRootFS(t *testing.T) { ++ forEachResolver(t, func(t *testing.T, opts PosixOpts) { ++ f := newNoFollowFixture(t, opts) ++ r := f.p.fsys ++ path := func(name string) string { ++ return f.p.ObjectPath(f.bucket, name) ++ } ++ errno := func(err error) error { ++ var perr *fs.PathError ++ if errors.As(err, &perr) { ++ return perr.Err ++ } ++ var lerr *os.LinkError ++ if errors.As(err, &lerr) { ++ return lerr.Err ++ } ++ return err ++ } ++ ++ for _, name := range f.nonObj { ++ if _, err := r.Stat(path(name)); errno(err) != unix.ENOENT { ++ t.Errorf("Stat %v: got %v, want ENOENT", name, err) ++ } ++ if fi, err := r.Lstat(path(name)); err != nil || isObjectMode(fi.Mode()) { ++ t.Errorf("Lstat %v: %v, %v", name, fi, err) ++ } ++ within(t, "Open "+name, func() { ++ if _, err := r.Open(path(name)); errno(err) != unix.ENOENT { ++ t.Errorf("Open %v: got %v, want ENOENT", name, err) ++ } ++ }) ++ within(t, "OpenFile O_CREATE "+name, func() { ++ if _, err := r.OpenFile(path(name), os.O_RDWR|os.O_CREATE, 0644); errno(err) != unix.ENOENT { ++ t.Errorf("OpenFile O_CREATE %v: got %v, want ENOENT", name, err) ++ } ++ }) ++ if _, err := r.getXattr(path(name), "user.etag"); errno(err) != unix.ENOENT { ++ t.Errorf("getXattr %v: got %v, want ENOENT", name, err) ++ } ++ if err := r.setXattr(path(name), "user.etag", []byte("x")); errno(err) != unix.ENOENT { ++ t.Errorf("setXattr %v: got %v, want ENOENT", name, err) ++ } ++ if _, err := r.listXattr(path(name)); errno(err) != unix.ENOENT { ++ t.Errorf("listXattr %v: got %v, want ENOENT", name, err) ++ } ++ } ++ for _, name := range []string{"link-dir/inner.txt", "sub/link-dir-rel/secret.txt", "link-abs/x"} { ++ if _, err := r.Stat(path(name)); errno(err) != unix.ENOTDIR { ++ t.Errorf("Stat %v: got %v, want ENOTDIR", name, err) ++ } ++ if _, err := r.OpenFile(path(name), os.O_RDWR|os.O_CREATE|os.O_EXCL, 0644); errno(err) != unix.ENOTDIR { ++ t.Errorf("OpenFile O_CREATE %v: got %v, want ENOTDIR", name, err) ++ } ++ if err := r.Mkdir(path(name+".d"), 0755); errno(err) != unix.ENOTDIR { ++ t.Errorf("Mkdir under %v: got %v, want ENOTDIR", name, err) ++ } ++ if _, err := r.getXattr(path(name), "user.etag"); errno(err) != unix.ENOTDIR { ++ t.Errorf("getXattr %v: got %v, want ENOTDIR", name, err) ++ } ++ if err := r.Remove(path(name)); errno(err) != unix.ENOTDIR { ++ t.Errorf("Remove %v: got %v, want ENOTDIR", name, err) ++ } ++ } ++ for _, dir := range []string{"link-dir", "sub/link-dir-rel"} { ++ if _, err := r.ReadDir(path(dir)); errno(err) != unix.ENOENT { ++ t.Errorf("ReadDir %v: got %v, want ENOENT", dir, err) ++ } ++ if _, err := r.CreateTemp(path(dir), "t."); errno(err) != unix.ENOTDIR { ++ t.Errorf("CreateTemp in %v: got %v, want ENOTDIR", dir, err) ++ } ++ } ++ // a rename onto a link replaces the link ++ tmp, err := r.CreateTemp(path("dir"), "t.") ++ if err != nil { ++ t.Fatal(err) ++ } ++ tmp.WriteString("renamed") ++ tmp.Close() ++ if err := r.Rename(tmp.Name(), path("link-abs")); err != nil { ++ t.Fatalf("Rename onto link-abs: %v", err) ++ } ++ if got := mustRead(t, f.path("link-abs")); got != "renamed" { ++ t.Errorf("link-abs: %q", got) ++ } ++ // RemoveAll of a directory holding links removes the links only ++ mustMkdir(t, f.path("tree")) ++ mustSymlink(t, filepath.Join(f.outside, "dir"), f.path("tree/to-dir")) ++ mustSymlink(t, filepath.Join(f.outside, "secret.txt"), f.path("tree/to-file")) ++ mustWrite(t, f.path("tree/own.txt"), insideData) ++ if err := r.RemoveAll(path("tree")); err != nil { ++ t.Fatalf("RemoveAll tree: %v", err) ++ } ++ if _, err := os.Lstat(f.path("tree")); !errors.Is(err, fs.ErrNotExist) { ++ t.Errorf("tree after RemoveAll: %v", err) ++ } ++ if err := r.RemoveAll(path("link-dir")); err != nil { ++ t.Fatalf("RemoveAll link-dir: %v", err) ++ } ++ if _, err := os.Lstat(f.path("link-dir")); !errors.Is(err, fs.ErrNotExist) { ++ t.Errorf("link-dir after RemoveAll: %v", err) ++ } ++ // listings' file system ++ ents, err := fs.ReadDir(r.bucketFS(f.p.BucketPath(f.bucket)), ".") ++ if err != nil { ++ t.Fatal(err) ++ } ++ var names []string ++ for _, e := range ents { ++ names = append(names, e.Name()) ++ } ++ // link-abs is a file by now, link-dir is gone ++ for _, name := range names { ++ if slices.Contains(f.nonObj, name) && name != "link-abs" { ++ t.Errorf("bucketFS.ReadDir lists %v: %v", name, names) ++ } ++ } ++ if !slices.Contains(names, "link-abs") || !slices.Contains(names, "real.txt") { ++ t.Errorf("bucketFS.ReadDir: %v", names) ++ } ++ f.unchanged(t) ++ }) ++} ++ ++// userXattrs lists the user attributes of name, leaving out those of other ++// namespaces, such as SELinux's label. ++func userXattrs(name string) ([]string, error) { ++ attrs, err := xattr.List(name) ++ var user []string ++ for _, a := range attrs { ++ if strings.HasPrefix(a, "user.") { ++ user = append(user, a) ++ } ++ } ++ return user, err ++} ++ ++func mustWrite(t *testing.T, name, data string) { ++ t.Helper() ++ if err := os.WriteFile(name, []byte(data), 0644); err != nil { ++ t.Fatal(err) ++ } ++} ++ ++func mustRead(t *testing.T, name string) string { ++ t.Helper() ++ b, err := os.ReadFile(name) ++ if err != nil { ++ t.Fatalf("read %v: %v", name, err) ++ } ++ return string(bytes.TrimSpace(b)) ++} ++ ++func mustMkdir(t *testing.T, name string) { ++ t.Helper() ++ if err := os.MkdirAll(name, 0755); err != nil { ++ t.Fatal(err) ++ } ++} ++ ++func mustSymlink(t *testing.T, target, name string) { ++ t.Helper() ++ if err := os.Symlink(target, name); err != nil { ++ t.Fatal(err) ++ } ++} +diff --git a/backend/posix/nofollow_mtim.go b/backend/posix/nofollow_mtim.go +new file mode 100644 +index 0000000..0ef2a29 +--- /dev/null ++++ b/backend/posix/nofollow_mtim.go +@@ -0,0 +1,27 @@ ++// Copyright 2026 s3-gateway contributors ++// This file is licensed under the Apache License, Version 2.0 ++// (the "License"); you may not use this file except in compliance ++// with the License. You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, ++// software distributed under the License is distributed on an ++// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++// KIND, either express or implied. See the License for the ++// specific language governing permissions and limitations ++// under the License. ++ ++//go:build !linux && !windows && !netbsd ++ ++package posix ++ ++import ( ++ "time" ++ ++ "golang.org/x/sys/unix" ++) ++ ++func statMtime(st *unix.Stat_t) time.Time { ++ return time.Unix(int64(st.Mtim.Sec), int64(st.Mtim.Nsec)) ++} +diff --git a/backend/posix/nofollow_mtimespec.go b/backend/posix/nofollow_mtimespec.go +new file mode 100644 +index 0000000..dea209a +--- /dev/null ++++ b/backend/posix/nofollow_mtimespec.go +@@ -0,0 +1,27 @@ ++// Copyright 2026 s3-gateway contributors ++// This file is licensed under the Apache License, Version 2.0 ++// (the "License"); you may not use this file except in compliance ++// with the License. You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, ++// software distributed under the License is distributed on an ++// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++// KIND, either express or implied. See the License for the ++// specific language governing permissions and limitations ++// under the License. ++ ++//go:build netbsd ++ ++package posix ++ ++import ( ++ "time" ++ ++ "golang.org/x/sys/unix" ++) ++ ++func statMtime(st *unix.Stat_t) time.Time { ++ return time.Unix(int64(st.Mtimespec.Sec), int64(st.Mtimespec.Nsec)) ++} +diff --git a/backend/posix/nofollow_other.go b/backend/posix/nofollow_other.go +new file mode 100644 +index 0000000..990df18 +--- /dev/null ++++ b/backend/posix/nofollow_other.go +@@ -0,0 +1,142 @@ ++// Copyright 2026 s3-gateway contributors ++// This file is licensed under the Apache License, Version 2.0 ++// (the "License"); you may not use this file except in compliance ++// with the License. You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, ++// software distributed under the License is distributed on an ++// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++// KIND, either express or implied. See the License for the ++// specific language governing permissions and limitations ++// under the License. ++ ++//go:build !linux && !windows ++ ++package posix ++ ++import ( ++ "io/fs" ++ "os" ++ ++ "github.com/pkg/xattr" ++ "golang.org/x/sys/unix" ++) ++ ++// Without openat2 and O_PATH the directories on the way are opened for ++// reading, one element at a time with O_NOFOLLOW, and an existing file is ++// opened with O_NONBLOCK before it is checked: a FIFO that the check then ++// refuses is opened, though never read and never waited on. ++ ++const dirPathFlags = os.O_RDONLY | unix.O_DIRECTORY | unix.O_CLOEXEC ++ ++func checkNoFollowSupport() error { ++ return nil ++} ++ ++func beneath(dirfd int, rel string) (int, error) { ++ return walkBeneath(dirfd, rel, dirPathFlags|unix.O_NOFOLLOW) ++} ++ ++func dirFileName(_ int, name string) string { ++ return name ++} ++ ++// openExisting opens the existing element a with flag, if it is a regular ++// file or a directory. ++func openExisting(a at, name string, flag int) (int, error) { ++ oflags := flag | unix.O_NONBLOCK ++ if !a.follow { ++ oflags |= unix.O_NOFOLLOW ++ } ++ fd, err := openat(a.dir.fd, a.name, oflags, 0) ++ if err == unix.ELOOP || err == unix.EMLINK { ++ return -1, hidden("open", name, fs.ModeSymlink) ++ } ++ if err != nil { ++ return -1, &fs.PathError{Op: "open", Path: name, Err: err} ++ } ++ var st unix.Stat_t ++ if err := ignoringEINTR(func() error { return unix.Fstat(fd, &st) }); err != nil { ++ unix.Close(fd) ++ return -1, &fs.PathError{Op: "open", Path: name, Err: err} ++ } ++ mode := fileModeOf(uint32(st.Mode)) ++ if !isObjectMode(mode) { ++ unix.Close(fd) ++ return -1, hidden("open", name, mode) ++ } ++ if flag&unix.O_NONBLOCK == 0 { ++ if err := unix.SetNonblock(fd, false); err != nil { ++ unix.Close(fd) ++ return -1, &fs.PathError{Op: "open", Path: name, Err: err} ++ } ++ } ++ return fd, nil ++} ++ ++// openForXattr opens the regular file or directory at name for its ++// extended attributes, which are then reached through the descriptor. ++func (r *rootFS) openForXattr(op, name string) (*os.File, error) { ++ a, err := r.resolve(op, name) ++ if err != nil { ++ return nil, err ++ } ++ defer a.close() ++ fd, err := openExisting(a, name, os.O_RDONLY) ++ if err != nil { ++ return nil, err ++ } ++ return os.NewFile(uintptr(fd), name), nil ++} ++ ++func (r *rootFS) getXattr(name, attr string) ([]byte, error) { ++ f, err := r.openForXattr("xattr.get", name) ++ if err != nil { ++ return nil, err ++ } ++ defer f.Close() ++ b, err := xattr.FGet(f, attr) ++ if err != nil { ++ return nil, xattrErr("xattr.get", name, attr, err) ++ } ++ return b, nil ++} ++ ++func (r *rootFS) setXattr(name, attr string, value []byte) error { ++ f, err := r.openForXattr("xattr.set", name) ++ if err != nil { ++ return err ++ } ++ defer f.Close() ++ if err := xattr.FSet(f, attr, value); err != nil { ++ return xattrErr("xattr.set", name, attr, err) ++ } ++ return nil ++} ++ ++func (r *rootFS) removeXattr(name, attr string) error { ++ f, err := r.openForXattr("xattr.remove", name) ++ if err != nil { ++ return err ++ } ++ defer f.Close() ++ if err := xattr.FRemove(f, attr); err != nil { ++ return xattrErr("xattr.remove", name, attr, err) ++ } ++ return nil ++} ++ ++func (r *rootFS) listXattr(name string) ([]string, error) { ++ f, err := r.openForXattr("xattr.list", name) ++ if err != nil { ++ return nil, err ++ } ++ defer f.Close() ++ attrs, err := xattr.FList(f) ++ if err != nil { ++ return nil, xattrErr("xattr.list", name, "", err) ++ } ++ return attrs, nil ++} +diff --git a/backend/posix/nofollow_unix.go b/backend/posix/nofollow_unix.go +new file mode 100644 +index 0000000..4ae04c2 +--- /dev/null ++++ b/backend/posix/nofollow_unix.go +@@ -0,0 +1,959 @@ ++// Copyright 2026 s3-gateway contributors ++// This file is licensed under the Apache License, Version 2.0 ++// (the "License"); you may not use this file except in compliance ++// with the License. You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, ++// software distributed under the License is distributed on an ++// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++// KIND, either express or implied. See the License for the ++// specific language governing permissions and limitations ++// under the License. ++ ++//go:build !windows ++ ++package posix ++ ++import ( ++ "errors" ++ "fmt" ++ "io" ++ "io/fs" ++ "math/rand/v2" ++ "os" ++ "path" ++ "path/filepath" ++ "slices" ++ "strconv" ++ "strings" ++ "syscall" ++ "time" ++ ++ "github.com/pkg/xattr" ++ "github.com/versity/versitygw/backend/meta" ++ "github.com/versity/versitygw/debuglogger" ++ "github.com/versity/versitygw/s3err" ++ "golang.org/x/sys/unix" ++) ++ ++// rootFS is the file system the posix backend reads and writes objects on. ++// It takes the paths the backend builds, relative to the gateway root (the ++// working directory) or absolute under the root or the versioning directory, ++// and resolves them from a descriptor of that directory, opened once at ++// start, without following a symbolic link anywhere below it: ++// ++// - A directory on the way that is a symbolic link fails the call as a file ++// there does (ENOTDIR): reads find nothing, writes answer that the ++// object's parent is a file. ++// - A last element that is a symbolic link, FIFO, socket or device is no ++// object: Stat, Open, ReadDir and the extended attribute calls report it ++// missing (ENOENT), and it is never opened. Lstat, Remove, Rename and ++// the publish of a new object act on the entry itself. ++// ++// With BucketLinks a symbolic link at the bucket level is followed, as the ++// option promises; nothing below it is. The root and the versioning ++// directory are opened as the operator named them. ++// ++// The directories on the way are opened with openat2 and ++// RESOLVE_NO_SYMLINKS|RESOLVE_BENEATH on Linux, or one element at a time ++// with O_NOFOLLOW where openat2 is missing, so a link swapped in while a ++// request runs is refused too. ++type rootFS struct { ++ root string // absolute path of the gateway root ++ rootfd int ++ relative bool // relative paths are relative to the root ++ vdir string // absolute path of the versioning directory, or "" ++ vdirFile *os.File ++ vdirfd int ++ bucketlinks bool ++} ++ ++// newRootFS returns the rootFS of the gateway root open as rootFile, at the ++// absolute path root. Relative paths are resolved against the root when ++// relative is set. vdir is the absolute path of the versioning directory, or ++// "" without versioning. ++func newRootFS(rootFile *os.File, root string, relative bool, vdir string, bucketlinks bool) (*rootFS, error) { ++ if err := checkNoFollowSupport(); err != nil { ++ return nil, err ++ } ++ r := &rootFS{ ++ root: root, ++ rootfd: int(rootFile.Fd()), ++ relative: relative, ++ vdirfd: -1, ++ bucketlinks: bucketlinks, ++ } ++ if vdir != "" { ++ f, err := os.Open(vdir) ++ if err != nil { ++ return nil, fmt.Errorf("open versioning directory %v: %w", vdir, err) ++ } ++ r.vdir, r.vdirFile, r.vdirfd = vdir, f, int(f.Fd()) ++ } ++ return r, nil ++} ++ ++func (r *rootFS) close() { ++ if r.vdirFile != nil { ++ r.vdirFile.Close() ++ } ++} ++ ++// errOutsideRoot is the error for a path that is neither under the gateway ++// root nor under the versioning directory. ++var errOutsideRoot = errors.New("not under the gateway root or the versioning directory") ++ ++// locate returns the descriptor of the directory name is resolved from, name ++// relative to it, and whether that directory is the gateway root. ++func (r *rootFS) locate(name string) (int, string, bool, error) { ++ if filepath.IsAbs(name) { ++ if rel, ok := relativeTo(r.root, name); ok { ++ return r.rootfd, rel, true, nil ++ } ++ if r.vdir != "" { ++ if rel, ok := relativeTo(r.vdir, name); ok { ++ return r.vdirfd, rel, false, nil ++ } ++ } ++ return -1, "", false, errOutsideRoot ++ } ++ if !r.relative { ++ return -1, "", false, errOutsideRoot ++ } ++ rel := filepath.Clean(name) ++ if rel != "." && !filepath.IsLocal(rel) { ++ return -1, "", false, errOutsideRoot ++ } ++ return r.rootfd, rel, true, nil ++} ++ ++func relativeTo(dir, name string) (string, bool) { ++ rel, err := filepath.Rel(dir, name) ++ if err != nil || (rel != "." && !filepath.IsLocal(rel)) { ++ return "", false ++ } ++ return rel, true ++} ++ ++// bucketLevel reports whether rel, relative to the root when inRoot is set, ++// names a bucket that BucketLinks lets be a symbolic link to a directory. ++func (r *rootFS) bucketLevel(inRoot bool, rel string) bool { ++ return r.bucketlinks && inRoot && rel != "." && rel != objLockDir && ++ !strings.ContainsRune(rel, filepath.Separator) ++} ++ ++// dirFD is a directory descriptor, closed by close unless it is the root's ++// or the versioning directory's. ++type dirFD struct { ++ fd int ++ owned bool ++} ++ ++func (d dirFD) close() { ++ if d.owned { ++ unix.Close(d.fd) ++ } ++} ++ ++// openDir opens the directory rel below the directory base, inRoot telling ++// whether base is the gateway root, following no symbolic link on the way ++// but a bucket's with BucketLinks. ++func (r *rootFS) openDir(base int, rel string, inRoot bool) (dirFD, error) { ++ if rel == "." { ++ return dirFD{fd: base}, nil ++ } ++ if r.bucketlinks && inRoot { ++ bucket, rest, _ := strings.Cut(rel, string(filepath.Separator)) ++ if bucket != objLockDir { ++ // the bucket, following a link: BucketLinks makes it one ++ fd, err := openat(base, bucket, dirPathFlags, 0) ++ if err != nil { ++ return dirFD{}, err ++ } ++ if rest == "" { ++ return dirFD{fd: fd, owned: true}, nil ++ } ++ below, err := beneath(fd, rest) ++ unix.Close(fd) ++ if err != nil { ++ return dirFD{}, err ++ } ++ return dirFD{fd: below, owned: true}, nil ++ } ++ } ++ fd, err := beneath(base, rel) ++ if err != nil { ++ return dirFD{}, err ++ } ++ return dirFD{fd: fd, owned: true}, nil ++} ++ ++// walkBeneath opens the directory rel below dirfd one element at a time with ++// flags, which hold O_NOFOLLOW, so that no element is a symbolic link. ++func walkBeneath(dirfd int, rel string, flags int) (int, error) { ++ fd, owned := dirfd, false ++ for _, elem := range strings.Split(rel, string(filepath.Separator)) { ++ if elem == "" || elem == "." { ++ continue ++ } ++ if elem == ".." { ++ if owned { ++ unix.Close(fd) ++ } ++ return -1, unix.EXDEV ++ } ++ next, err := openat(fd, elem, flags, 0) ++ if owned { ++ unix.Close(fd) ++ } ++ if err != nil { ++ if err == unix.EMLINK { ++ // FreeBSD's answer to O_NOFOLLOW on a link ++ err = unix.ELOOP ++ } ++ return -1, err ++ } ++ fd, owned = next, true ++ } ++ if !owned { ++ return unix.Dup(dirfd) ++ } ++ return fd, nil ++} ++ ++// at is the last element of a path: the directory that holds it and its ++// name there, "." for the root or the versioning directory itself. ++type at struct { ++ dir dirFD ++ name string ++ // follow is set when the element is a bucket that BucketLinks lets be ++ // a symbolic link, which the calls that read it then follow. ++ follow bool ++} ++ ++func (a at) close() { ++ a.dir.close() ++} ++ ++// resolve opens the directory that holds the last element of name. Its ++// errors are those of op on name. ++func (r *rootFS) resolve(op, name string) (at, error) { ++ base, rel, inRoot, err := r.locate(name) ++ if err != nil { ++ return at{}, &fs.PathError{Op: op, Path: name, Err: err} ++ } ++ if rel == "." { ++ return at{dir: dirFD{fd: base}, name: "."}, nil ++ } ++ d, err := r.openDir(base, filepath.Dir(rel), inRoot) ++ if err != nil { ++ return at{}, resolveErr(op, name, err) ++ } ++ return at{dir: d, name: filepath.Base(rel), follow: r.bucketLevel(inRoot, rel)}, nil ++} ++ ++// dirAt opens the directory name itself. ++func (r *rootFS) dirAt(op, name string) (dirFD, error) { ++ base, rel, inRoot, err := r.locate(name) ++ if err != nil { ++ return dirFD{}, &fs.PathError{Op: op, Path: name, Err: err} ++ } ++ d, err := r.openDir(base, rel, inRoot) ++ if err != nil { ++ return dirFD{}, resolveErr(op, name, err) ++ } ++ return d, nil ++} ++ ++// resolveErr is the error of op on name when opening a directory on its way ++// failed with err: a symbolic link there (ELOOP) is reported as a file there ++// (ENOTDIR), and an escape from the root (EXDEV from RESOLVE_BENEATH, which ++// the backend's cleaned paths never make) as a permission error. ++func resolveErr(op, name string, err error) error { ++ switch err { ++ case unix.ELOOP: ++ debuglogger.Logf("posix: a directory on the way to %q is a symbolic link: not followed", name) ++ err = syscall.ENOTDIR ++ case unix.EXDEV: ++ err = syscall.EACCES ++ } ++ return &fs.PathError{Op: op, Path: name, Err: err} ++} ++ ++// isObjectMode reports whether an entry of mode m can be an object: a ++// regular file or a directory. ++func isObjectMode(m fs.FileMode) bool { ++ return m.IsRegular() || m.IsDir() ++} ++ ++// hidden logs that the entry at name, of mode m, is no object, and returns ++// the error that reports it missing to op. ++func hidden(op, name string, m fs.FileMode) error { ++ var kind string ++ switch { ++ case m&fs.ModeSymlink != 0: ++ kind = "a symbolic link" ++ case m&fs.ModeNamedPipe != 0: ++ kind = "a FIFO" ++ case m&fs.ModeSocket != 0: ++ kind = "a socket" ++ case m&fs.ModeDevice != 0: ++ kind = "a device" ++ default: ++ kind = "not a file or directory" ++ } ++ debuglogger.Logf("posix: %q is %v: not followed or opened", name, kind) ++ return &fs.PathError{Op: op, Path: name, Err: syscall.ENOENT} ++} ++ ++func ignoringEINTR(fn func() error) error { ++ for { ++ err := fn() ++ if err != unix.EINTR { ++ return err ++ } ++ } ++} ++ ++func openat(dirfd int, name string, flags int, perm uint32) (int, error) { ++ for { ++ fd, err := unix.Openat(dirfd, name, flags|unix.O_CLOEXEC, perm) ++ if err != unix.EINTR { ++ return fd, err ++ } ++ } ++} ++ ++func fstatat(dirfd int, name string, st *unix.Stat_t, flags int) error { ++ return ignoringEINTR(func() error { return unix.Fstatat(dirfd, name, st, flags) }) ++} ++ ++func unlinkat(dirfd int, name string, flags int) error { ++ return ignoringEINTR(func() error { return unix.Unlinkat(dirfd, name, flags) }) ++} ++ ++// lstatAt returns the file info of the element a, following it only if ++// a.follow is set. ++func lstatAt(a at, name string) (fs.FileInfo, error) { ++ flags := unix.AT_SYMLINK_NOFOLLOW ++ if a.follow { ++ flags = 0 ++ } ++ var st unix.Stat_t ++ if err := fstatat(a.dir.fd, a.name, &st, flags); err != nil { ++ return nil, err ++ } ++ return newFileInfo(filepath.Base(name), &st), nil ++} ++ ++// Lstat returns the file info of the entry at name, never following it. ++func (r *rootFS) Lstat(name string) (fs.FileInfo, error) { ++ a, err := r.resolve("lstat", name) ++ if err != nil { ++ return nil, err ++ } ++ defer a.close() ++ var st unix.Stat_t ++ if err := fstatat(a.dir.fd, a.name, &st, unix.AT_SYMLINK_NOFOLLOW); err != nil { ++ return nil, &fs.PathError{Op: "lstat", Path: name, Err: err} ++ } ++ return newFileInfo(filepath.Base(name), &st), nil ++} ++ ++// Stat returns the file info of the regular file or directory at name. Any ++// other entry is reported missing. ++func (r *rootFS) Stat(name string) (fs.FileInfo, error) { ++ a, err := r.resolve("stat", name) ++ if err != nil { ++ return nil, err ++ } ++ defer a.close() ++ fi, err := lstatAt(a, name) ++ if err != nil { ++ return nil, &fs.PathError{Op: "stat", Path: name, Err: err} ++ } ++ if !isObjectMode(fi.Mode()) { ++ return nil, hidden("stat", name, fi.Mode()) ++ } ++ return fi, nil ++} ++ ++// Open opens the regular file or directory at name for reading. ++func (r *rootFS) Open(name string) (*os.File, error) { ++ return r.OpenFile(name, os.O_RDONLY, 0) ++} ++ ++// OpenFile opens the regular file or directory at name, or creates a ++// regular file there with O_CREATE. An existing entry of any other kind is ++// reported missing and never opened, and none is created through a link. ++func (r *rootFS) OpenFile(name string, flag int, perm fs.FileMode) (*os.File, error) { ++ a, err := r.resolve("open", name) ++ if err != nil { ++ return nil, err ++ } ++ defer a.close() ++ fd, err := r.openAt(a, name, flag, perm) ++ if err != nil { ++ return nil, err ++ } ++ return os.NewFile(uintptr(fd), name), nil ++} ++ ++func (r *rootFS) openAt(a at, name string, flag int, perm fs.FileMode) (int, error) { ++ if flag&os.O_CREATE != 0 { ++ // O_CREATE|O_EXCL never follows the last element ++ fd, err := openat(a.dir.fd, a.name, flag|os.O_EXCL|unix.O_NOFOLLOW, uint32(perm.Perm())) ++ if err == nil { ++ return fd, nil ++ } ++ if flag&os.O_EXCL != 0 || err != unix.EEXIST { ++ return -1, &fs.PathError{Op: "open", Path: name, Err: err} ++ } ++ // it exists: open it as it is, if it is a file or a directory ++ flag &^= os.O_CREATE ++ } ++ return openExisting(a, name, flag) ++} ++ ++// ReadDir returns the entries of the directory at name, sorted by name, of ++// every kind. The entries' Info is the Lstat of the entry. ++func (r *rootFS) ReadDir(name string) ([]fs.DirEntry, error) { ++ a, err := r.resolve("open", name) ++ if err != nil { ++ return nil, err ++ } ++ defer a.close() ++ fd, err := openDirRead(a, name) ++ if err != nil { ++ return nil, err ++ } ++ f := os.NewFile(uintptr(fd), dirFileName(fd, name)) ++ ents, err := f.ReadDir(-1) ++ f.Close() ++ var perr *fs.PathError ++ if errors.As(err, &perr) { ++ err = &fs.PathError{Op: perr.Op, Path: name, Err: perr.Err} ++ } ++ out := make([]fs.DirEntry, 0, len(ents)) ++ for _, e := range ents { ++ out = append(out, dirEntry{r: r, path: filepath.Join(name, e.Name()), name: e.Name(), typ: e.Type()}) ++ } ++ slices.SortFunc(out, func(a, b fs.DirEntry) int { return strings.Compare(a.Name(), b.Name()) }) ++ return out, err ++} ++ ++// openDirRead opens the directory element a for reading. O_DIRECTORY fails ++// on any other kind of entry before it is opened. ++func openDirRead(a at, name string) (int, error) { ++ flags := os.O_RDONLY | unix.O_DIRECTORY ++ if !a.follow { ++ flags |= unix.O_NOFOLLOW ++ } ++ fd, err := openat(a.dir.fd, a.name, flags, 0) ++ if err == unix.ELOOP || err == unix.EMLINK || err == unix.ENOTDIR { ++ // Linux answers ENOTDIR for a link with O_DIRECTORY: a link, FIFO, ++ // socket or device is no directory but no file either ++ if fi, lerr := lstatAt(a, name); lerr == nil && !isObjectMode(fi.Mode()) { ++ return -1, hidden("open", name, fi.Mode()) ++ } ++ } ++ if err != nil { ++ return -1, &fs.PathError{Op: "open", Path: name, Err: err} ++ } ++ return fd, nil ++} ++ ++// dirEntry is an entry of rootFS.ReadDir. ++type dirEntry struct { ++ r *rootFS ++ path string ++ name string ++ typ fs.FileMode ++} ++ ++func (e dirEntry) Name() string { return e.name } ++func (e dirEntry) IsDir() bool { return e.typ.IsDir() } ++func (e dirEntry) Type() fs.FileMode { return e.typ } ++func (e dirEntry) Info() (fs.FileInfo, error) { return e.r.Lstat(e.path) } ++func (e dirEntry) String() string { return fs.FormatDirEntry(e) } ++ ++// Mkdir makes the directory name. ++func (r *rootFS) Mkdir(name string, perm fs.FileMode) error { ++ a, err := r.resolve("mkdir", name) ++ if err != nil { ++ return err ++ } ++ defer a.close() ++ err = ignoringEINTR(func() error { return unix.Mkdirat(a.dir.fd, a.name, uint32(perm.Perm())) }) ++ if err != nil { ++ return &fs.PathError{Op: "mkdir", Path: name, Err: err} ++ } ++ return nil ++} ++ ++// Chown changes the owner of the entry at name, never following it. ++func (r *rootFS) Chown(name string, uid, gid int) error { ++ a, err := r.resolve("chown", name) ++ if err != nil { ++ return err ++ } ++ defer a.close() ++ err = ignoringEINTR(func() error { ++ return unix.Fchownat(a.dir.fd, a.name, uid, gid, unix.AT_SYMLINK_NOFOLLOW) ++ }) ++ if err != nil { ++ return &fs.PathError{Op: "chown", Path: name, Err: err} ++ } ++ return nil ++} ++ ++// Chtimes changes the access and modification times of the entry at name, ++// never following it. ++func (r *rootFS) Chtimes(name string, atime, mtime time.Time) error { ++ a, err := r.resolve("chtimes", name) ++ if err != nil { ++ return err ++ } ++ defer a.close() ++ ts := []unix.Timespec{unix.NsecToTimespec(atime.UnixNano()), unix.NsecToTimespec(mtime.UnixNano())} ++ err = ignoringEINTR(func() error { ++ return unix.UtimesNanoAt(a.dir.fd, a.name, ts, unix.AT_SYMLINK_NOFOLLOW) ++ }) ++ if err != nil { ++ return &fs.PathError{Op: "chtimes", Path: name, Err: err} ++ } ++ return nil ++} ++ ++// Remove removes the entry at name, a file of any kind or an empty ++// directory, as os.Remove does. A symbolic link is removed itself. ++func (r *rootFS) Remove(name string) error { ++ a, err := r.resolve("remove", name) ++ if err != nil { ++ return err ++ } ++ defer a.close() ++ err = unlinkat(a.dir.fd, a.name, 0) ++ if err == nil { ++ return nil ++ } ++ err1 := unlinkat(a.dir.fd, a.name, unix.AT_REMOVEDIR) ++ if err1 == nil { ++ return nil ++ } ++ // os.Remove: both failed, report the error that makes more sense ++ if err1 != unix.ENOTDIR { ++ err = err1 ++ } ++ return &fs.PathError{Op: "remove", Path: name, Err: err} ++} ++ ++// Rmdir removes the directory at name if it is empty. Unlike Remove it never ++// removes a file. ++func (r *rootFS) Rmdir(name string) error { ++ a, err := r.resolve("rmdir", name) ++ if err != nil { ++ return err ++ } ++ defer a.close() ++ if err := unlinkat(a.dir.fd, a.name, unix.AT_REMOVEDIR); err != nil { ++ return &fs.PathError{Op: "rmdir", Path: name, Err: err} ++ } ++ return nil ++} ++ ++// Rename renames the entry at oldpath to newpath, replacing what newpath ++// names as rename(2) does. Neither last element is followed. ++func (r *rootFS) Rename(oldpath, newpath string) error { ++ linkErr := func(err error) error { ++ var perr *fs.PathError ++ if errors.As(err, &perr) { ++ err = perr.Err ++ } ++ return &os.LinkError{Op: "rename", Old: oldpath, New: newpath, Err: err} ++ } ++ oa, err := r.resolve("rename", oldpath) ++ if err != nil { ++ return linkErr(err) ++ } ++ defer oa.close() ++ na, err := r.resolve("rename", newpath) ++ if err != nil { ++ return linkErr(err) ++ } ++ defer na.close() ++ err = ignoringEINTR(func() error { return unix.Renameat(oa.dir.fd, oa.name, na.dir.fd, na.name) }) ++ if err != nil { ++ return linkErr(err) ++ } ++ return nil ++} ++ ++// RemoveAll removes name and everything below it, as os.RemoveAll does. It ++// enters no symbolic link: a link is removed itself. ++func (r *rootFS) RemoveAll(name string) error { ++ a, err := r.resolve("removeall", name) ++ if errors.Is(err, fs.ErrNotExist) { ++ return nil ++ } ++ if err != nil { ++ return err ++ } ++ defer a.close() ++ if a.name == "." { ++ return &fs.PathError{Op: "removeall", Path: name, Err: syscall.EINVAL} ++ } ++ if err := removeAllAt(a.dir.fd, a.name); err != nil { ++ return &fs.PathError{Op: "removeall", Path: name, Err: err} ++ } ++ return nil ++} ++ ++const removeAllBatch = 1024 ++ ++// removeAllAt removes the entry name in the directory dirfd and, if it is a ++// directory, everything below it. ++func removeAllAt(dirfd int, name string) error { ++ err := unlinkat(dirfd, name, 0) ++ if err == nil || err == unix.ENOENT { ++ return nil ++ } ++ // Linux answers EISDIR for a directory, the BSDs EPERM ++ if err != unix.EISDIR && err != unix.EPERM && err != unix.EACCES { ++ return err ++ } ++ unlinkErr := err ++ var firstErr error ++ for first := true; ; first = false { ++ fd, err := openat(dirfd, name, os.O_RDONLY|unix.O_DIRECTORY|unix.O_NOFOLLOW, 0) ++ if err == unix.ENOENT { ++ return nil ++ } ++ if err != nil { ++ if first && (err == unix.ENOTDIR || err == unix.ELOOP || err == unix.EMLINK) { ++ // not a directory: the unlink's error stands ++ return unlinkErr ++ } ++ return err ++ } ++ d := os.NewFile(uintptr(fd), name) ++ // Removing entries may reorder the directory, so each batch is ++ // read from a fresh open, as os.RemoveAll does. ++ names, rerr := d.Readdirnames(removeAllBatch) ++ numErr := 0 ++ for _, n := range names { ++ if err := removeAllAt(fd, n); err != nil { ++ numErr++ ++ if firstErr == nil { ++ firstErr = err ++ } ++ } ++ } ++ d.Close() ++ if rerr != nil && rerr != io.EOF { ++ if firstErr == nil { ++ firstErr = rerr ++ } ++ break ++ } ++ if len(names) < removeAllBatch || numErr == len(names) { ++ break ++ } ++ } ++ err = unlinkat(dirfd, name, unix.AT_REMOVEDIR) ++ if err == nil || err == unix.ENOENT { ++ return nil ++ } ++ if firstErr != nil { ++ return firstErr ++ } ++ return err ++} ++ ++// CreateTemp creates a new regular file in the directory dir, named after ++// pattern as os.CreateTemp names it, and opens it for reading and writing. ++func (r *rootFS) CreateTemp(dir, pattern string) (*os.File, error) { ++ d, err := r.dirAt("createtemp", dir) ++ if err != nil { ++ return nil, err ++ } ++ defer d.close() ++ prefix, suffix := pattern, "" ++ if i := strings.LastIndexByte(pattern, '*'); i >= 0 { ++ prefix, suffix = pattern[:i], pattern[i+1:] ++ } ++ for try := 0; ; try++ { ++ name := prefix + strconv.FormatUint(uint64(rand.Uint32()), 10) + suffix ++ fd, err := openat(d.fd, name, os.O_RDWR|os.O_CREATE|os.O_EXCL|unix.O_NOFOLLOW, 0600) ++ if err == nil { ++ return os.NewFile(uintptr(fd), filepath.Join(dir, name)), nil ++ } ++ if err == unix.EEXIST && try < 10000 { ++ continue ++ } ++ return nil, &fs.PathError{Op: "createtemp", Path: filepath.Join(dir, pattern), Err: err} ++ } ++} ++ ++// removeNonObject removes the entry at name if it is a symbolic link, FIFO, ++// socket or device: the entry itself, never what a link points to. Any ++// other entry, and none, is left as it is. ++func (p *Posix) removeNonObject(name string) error { ++ fi, err := p.fsys.Lstat(name) ++ if err != nil || isObjectMode(fi.Mode()) { ++ return nil ++ } ++ hidden("remove", name, fi.Mode()) ++ err = p.fsys.Remove(name) ++ if err != nil && !errors.Is(err, fs.ErrNotExist) { ++ return fmt.Errorf("remove %v: %w", name, err) ++ } ++ return nil ++} ++ ++// bucketFS returns the file system of the bucket directory dir for the ++// listings: it holds only the regular files and directories under dir, so a ++// listing neither shows nor enters any other entry. ++func (r *rootFS) bucketFS(dir string) fs.FS { ++ return bucketFS{r: r, dir: dir} ++} ++ ++type bucketFS struct { ++ r *rootFS ++ dir string ++} ++ ++func (b bucketFS) path(op, name string) (string, error) { ++ if !fs.ValidPath(name) { ++ return "", &fs.PathError{Op: op, Path: name, Err: fs.ErrInvalid} ++ } ++ return filepath.Join(b.dir, filepath.FromSlash(name)), nil ++} ++ ++func (b bucketFS) Open(name string) (fs.File, error) { ++ p, err := b.path("open", name) ++ if err != nil { ++ return nil, err ++ } ++ f, err := b.r.Open(p) ++ if err != nil { ++ return nil, err ++ } ++ return f, nil ++} ++ ++func (b bucketFS) Stat(name string) (fs.FileInfo, error) { ++ p, err := b.path("stat", name) ++ if err != nil { ++ return nil, err ++ } ++ fi, err := b.r.Stat(p) ++ if err != nil { ++ return nil, err ++ } ++ return renamedInfo{FileInfo: fi, name: path.Base(name)}, nil ++} ++ ++func (b bucketFS) ReadDir(name string) ([]fs.DirEntry, error) { ++ p, err := b.path("readdir", name) ++ if err != nil { ++ return nil, err ++ } ++ ents, err := b.r.ReadDir(p) ++ out := ents[:0] ++ for _, e := range ents { ++ if e.IsDir() || e.Type().IsRegular() { ++ out = append(out, objectEntry{e.(dirEntry)}) ++ continue ++ } ++ hidden("readdir", filepath.Join(p, e.Name()), e.Type()) ++ } ++ return out, err ++} ++ ++// objectEntry is an entry of bucketFS.ReadDir, whose Info is that of the ++// regular file or directory it is. ++type objectEntry struct { ++ dirEntry ++} ++ ++func (e objectEntry) Info() (fs.FileInfo, error) { return e.r.Stat(e.path) } ++func (e objectEntry) String() string { return fs.FormatDirEntry(e) } ++ ++// renamedInfo is a FileInfo under another name. ++type renamedInfo struct { ++ fs.FileInfo ++ name string ++} ++ ++func (fi renamedInfo) Name() string { return fi.name } ++ ++// fileInfo is the FileInfo of a unix.Stat_t. ++type fileInfo struct { ++ name string ++ size int64 ++ mode fs.FileMode ++ mtime time.Time ++ sys unix.Stat_t ++} ++ ++func newFileInfo(name string, st *unix.Stat_t) *fileInfo { ++ return &fileInfo{ ++ name: name, ++ size: int64(st.Size), ++ mode: fileModeOf(uint32(st.Mode)), ++ mtime: statMtime(st), ++ sys: *st, ++ } ++} ++ ++func (fi *fileInfo) Name() string { return fi.name } ++func (fi *fileInfo) Size() int64 { return fi.size } ++func (fi *fileInfo) Mode() fs.FileMode { return fi.mode } ++func (fi *fileInfo) ModTime() time.Time { return fi.mtime } ++func (fi *fileInfo) IsDir() bool { return fi.mode.IsDir() } ++func (fi *fileInfo) Sys() any { return &fi.sys } ++ ++// fileModeOf is the FileMode of a stat mode, as the os package makes it. ++func fileModeOf(m uint32) fs.FileMode { ++ mode := fs.FileMode(m & 0777) ++ switch m & unix.S_IFMT { ++ case unix.S_IFBLK: ++ mode |= fs.ModeDevice ++ case unix.S_IFCHR: ++ mode |= fs.ModeDevice | fs.ModeCharDevice ++ case unix.S_IFDIR: ++ mode |= fs.ModeDir ++ case unix.S_IFIFO: ++ mode |= fs.ModeNamedPipe ++ case unix.S_IFLNK: ++ mode |= fs.ModeSymlink ++ case unix.S_IFSOCK: ++ mode |= fs.ModeSocket ++ } ++ if m&unix.S_ISGID != 0 { ++ mode |= fs.ModeSetgid ++ } ++ if m&unix.S_ISUID != 0 { ++ mode |= fs.ModeSetuid ++ } ++ if m&unix.S_ISVTX != 0 { ++ mode |= fs.ModeSticky ++ } ++ return mode ++} ++ ++// wrapMeta returns the metadata storer the backend uses for ms: the ++// extended attribute storer resolves its paths with r. Other storers keep ++// their metadata outside the gateway root and are used as they are. ++func (r *rootFS) wrapMeta(ms meta.MetadataStorer, pathRoot string) meta.MetadataStorer { ++ if xm, ok := ms.(meta.XattrMeta); ok { ++ return noFollowXattr{XattrMeta: xm, r: r, pathRoot: pathRoot} ++ } ++ return ms ++} ++ ++// noFollowXattr is meta.XattrMeta with the attributes of a bucket or object ++// read and written through rootFS: never through a symbolic link, and those ++// of an entry that is no regular file or directory never at all. ++type noFollowXattr struct { ++ meta.XattrMeta ++ r *rootFS ++ pathRoot string ++} ++ ++var _ meta.MetadataStorer = noFollowXattr{} ++ ++// path is the path of bucket's object, as meta.XattrMeta builds it. ++func (x noFollowXattr) path(bucket, object string) (string, error) { ++ if filepath.IsAbs(bucket) { ++ return filepath.Join(bucket, object), nil ++ } ++ if bucket == "" || bucket == "." || bucket == ".." { ++ return "", fmt.Errorf("xattr metadata: invalid bucket name %q", bucket) ++ } ++ return filepath.Join(x.pathRoot, bucket, object), nil ++} ++ ++func (x noFollowXattr) RetrieveAttribute(f *os.File, bucket, object, attribute string) ([]byte, error) { ++ if f != nil { ++ return x.XattrMeta.RetrieveAttribute(f, bucket, object, attribute) ++ } ++ name, err := x.path(bucket, object) ++ if err != nil { ++ return nil, err ++ } ++ b, err := x.r.getXattr(name, meta.XattrPrefix()+attribute) ++ if errors.Is(err, xattr.ENOATTR) { ++ return nil, meta.ErrNoSuchKey ++ } ++ return b, err ++} ++ ++func (x noFollowXattr) StoreAttribute(f *os.File, bucket, object, attribute string, value []byte) error { ++ if f != nil { ++ return x.XattrMeta.StoreAttribute(f, bucket, object, attribute, value) ++ } ++ name, err := x.path(bucket, object) ++ if err != nil { ++ return err ++ } ++ return storeAttributeErr(x.r.setXattr(name, meta.XattrPrefix()+attribute, value)) ++} ++ ++// storeAttributeErr maps err as meta.XattrMeta.StoreAttribute does. ++func storeAttributeErr(err error) error { ++ if errors.Is(err, syscall.EROFS) { ++ return s3err.GetAPIError(s3err.ErrMethodNotAllowed) ++ } ++ if errors.Is(err, syscall.ENOSPC) { ++ return s3err.GetAPIError(s3err.ErrNoSpaceLeftOnDevice) ++ } ++ return err ++} ++ ++func (x noFollowXattr) DeleteAttribute(bucket, object, attribute string) error { ++ name, err := x.path(bucket, object) ++ if err != nil { ++ return err ++ } ++ err = x.r.removeXattr(name, meta.XattrPrefix()+attribute) ++ if errors.Is(err, xattr.ENOATTR) { ++ return meta.ErrNoSuchKey ++ } ++ if errors.Is(err, syscall.EROFS) { ++ return s3err.GetAPIError(s3err.ErrMethodNotAllowed) ++ } ++ return err ++} ++ ++func (x noFollowXattr) ListAttributes(bucket, object string) ([]string, error) { ++ name, err := x.path(bucket, object) ++ if err != nil { ++ return nil, err ++ } ++ attrs, err := x.r.listXattr(name) ++ if err != nil { ++ return nil, err ++ } ++ prefix := meta.XattrPrefix() ++ attributes := make([]string, 0, len(attrs)) ++ for _, attr := range attrs { ++ if strings.HasPrefix(attr, prefix) { ++ attributes = append(attributes, strings.TrimPrefix(attr, prefix)) ++ } ++ } ++ return attributes, nil ++} ++ ++// xattrErr is the error of the extended attribute call op on the attribute ++// attr of name, with err the errno of the call. ++func xattrErr(op, name, attr string, err error) error { ++ var xerr *xattr.Error ++ if errors.As(err, &xerr) { ++ err = xerr.Err ++ } ++ return &xattr.Error{Op: op, Path: name, Name: attr, Err: err} ++} +diff --git a/backend/posix/nofollow_windows.go b/backend/posix/nofollow_windows.go +new file mode 100644 +index 0000000..0de600b +--- /dev/null ++++ b/backend/posix/nofollow_windows.go +@@ -0,0 +1,70 @@ ++// Copyright 2026 s3-gateway contributors ++// This file is licensed under the Apache License, Version 2.0 ++// (the "License"); you may not use this file except in compliance ++// with the License. You may obtain a copy of the License at ++// ++// http://www.apache.org/licenses/LICENSE-2.0 ++// ++// Unless required by applicable law or agreed to in writing, ++// software distributed under the License is distributed on an ++// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY ++// KIND, either express or implied. See the License for the ++// specific language governing permissions and limitations ++// under the License. ++ ++//go:build windows ++ ++package posix ++ ++import ( ++ "io/fs" ++ "os" ++ "time" ++ ++ "github.com/versity/versitygw/backend/meta" ++) ++ ++// rootFS is the file system the posix backend reads and writes objects on. ++// On Windows it is the os package's, as upstream has it: the backend's ++// refusal of symbolic links is built for the unix systems only. ++type rootFS struct{} ++ ++func newRootFS(_ *os.File, _ string, _ bool, _ string, _ bool) (*rootFS, error) { ++ return &rootFS{}, nil ++} ++ ++func (r *rootFS) close() {} ++ ++func (r *rootFS) Stat(name string) (fs.FileInfo, error) { return os.Stat(name) } ++func (r *rootFS) Lstat(name string) (fs.FileInfo, error) { return os.Lstat(name) } ++func (r *rootFS) Open(name string) (*os.File, error) { return os.Open(name) } ++func (r *rootFS) OpenFile(name string, flag int, perm fs.FileMode) (*os.File, error) { ++ return os.OpenFile(name, flag, perm) ++} ++func (r *rootFS) ReadDir(name string) ([]fs.DirEntry, error) { return os.ReadDir(name) } ++func (r *rootFS) Mkdir(name string, perm fs.FileMode) error { return os.Mkdir(name, perm) } ++func (r *rootFS) Chown(name string, uid, gid int) error { return os.Chown(name, uid, gid) } ++func (r *rootFS) Remove(name string) error { return os.Remove(name) } ++func (r *rootFS) Rmdir(name string) error { return removeDir(name) } ++func (r *rootFS) Rename(oldpath, newpath string) error { return os.Rename(oldpath, newpath) } ++func (r *rootFS) RemoveAll(name string) error { return os.RemoveAll(name) } ++func (r *rootFS) CreateTemp(dir, pattern string) (*os.File, error) { ++ return os.CreateTemp(dir, pattern) ++} ++func (r *rootFS) Chtimes(name string, atime, mtime time.Time) error { ++ return os.Chtimes(name, atime, mtime) ++} ++ ++func (r *rootFS) bucketFS(dir string) fs.FS { ++ return os.DirFS(dir) ++} ++ ++// removeNonObject leaves the entry at name: on Windows the backend treats ++// every entry as upstream does. ++func (p *Posix) removeNonObject(string) error { ++ return nil ++} ++ ++func (r *rootFS) wrapMeta(ms meta.MetadataStorer, _ string) meta.MetadataStorer { ++ return ms ++} +diff --git a/backend/posix/objlock.go b/backend/posix/objlock.go +index 8d507d1..2c41534 100644 +--- a/backend/posix/objlock.go ++++ b/backend/posix/objlock.go +@@ -114,14 +114,14 @@ func (p *Posix) verifyObjectLockMode() error { + } + + lockDir := filepath.Join(p.rootdir, objLockDir) +- if err := backend.MkdirAll(lockDir, 0, 0, false, p.newDirPerm); err != nil { ++ if err := backend.MkdirAllFS(p.fsys, lockDir, 0, 0, false, p.newDirPerm); err != nil { + return fmt.Errorf("make object lock directory: %w", err) + } +- f, err := os.CreateTemp(lockDir, ".startup-lock-*") ++ f, err := p.fsys.CreateTemp(lockDir, ".startup-lock-*") + if err != nil { + return fmt.Errorf("create object lock probe: %w", err) + } +- defer os.Remove(f.Name()) ++ defer p.fsys.Remove(f.Name()) + defer f.Close() + + if err := lockFileExclusive(context.Background(), f, p.objectLockMode); err != nil { +@@ -205,7 +205,7 @@ func (p *Posix) openObjLockFile(bucketHash [sha256.Size]byte, shard uint8) (*os. + lockDir := filepath.Join(p.rootdir, objLockDir, fmt.Sprintf("%x", bucketHash)) + name := filepath.Join(lockDir, fmt.Sprintf("%02x", shard)) + +- f, err := os.OpenFile(name, os.O_RDWR|os.O_CREATE, defaultNewFilePerm) ++ f, err := p.fsys.OpenFile(name, os.O_RDWR|os.O_CREATE, defaultNewFilePerm) + if err == nil { + return f, nil + } +@@ -214,11 +214,11 @@ func (p *Posix) openObjLockFile(bucketHash [sha256.Size]byte, shard uint8) (*os. + } + + // lock dir not created yet +- err = backend.MkdirAll(lockDir, 0, 0, false, p.newDirPerm) ++ err = backend.MkdirAllFS(p.fsys, lockDir, 0, 0, false, p.newDirPerm) + if err != nil { + return nil, fmt.Errorf("make object lock dir: %w", err) + } +- f, err = os.OpenFile(name, os.O_RDWR|os.O_CREATE, defaultNewFilePerm) ++ f, err = p.fsys.OpenFile(name, os.O_RDWR|os.O_CREATE, defaultNewFilePerm) + if err != nil { + return nil, fmt.Errorf("open object lock file: %w", err) + } +diff --git a/backend/posix/otmpfile_common.go b/backend/posix/otmpfile_common.go +index ac156fe..d63ac3d 100644 +--- a/backend/posix/otmpfile_common.go ++++ b/backend/posix/otmpfile_common.go +@@ -150,8 +150,7 @@ func (tmp *tmpfile) switchToBufferedAtCurrentOffset(reason string) error { + return fmt.Errorf("capture write offset before fallback reopen: %w", seekErr) + } + +- name := tmp.f.Name() +- f, openErr := os.OpenFile(name, os.O_RDWR, 0) ++ f, openErr := reopenFile(tmp.f, os.O_RDWR) + if openErr != nil { + return fmt.Errorf("reopen temp file in buffered mode after O_DIRECT fallback (%s): %w", reason, openErr) + } +@@ -203,7 +202,11 @@ func (tmp *tmpfile) applyModTime(path string) error { + if tmp.modTime.IsZero() { + return nil + } +- return os.Chtimes(path, time.Now(), tmp.modTime) ++ if tmp.isOTmp { ++ // the descriptor's /proc path: the file has no name yet ++ return os.Chtimes(path, time.Now(), tmp.modTime) ++ } ++ return tmp.fsys.Chtimes(path, time.Now(), tmp.modTime) + } + + func sleepWithJitter(backoffMs int) { +@@ -238,7 +241,7 @@ func (tmp *tmpfile) publishInDir(dir string, publish func() error) error { + } + // MkdirAll gives up when the directories keep disappearing; the + // next attempt makes them again after a longer wait. +- err = backend.MkdirAll(dir, tmp.uid, tmp.gid, tmp.doChown, tmp.newDirPerm) ++ err = backend.MkdirAllFS(tmp.fsys, dir, tmp.uid, tmp.gid, tmp.doChown, tmp.newDirPerm) + if err != nil && !isParentDirGone(err) && !isDirDeletePending(err) { + return fmt.Errorf("make parent dir: %w", err) + } +diff --git a/backend/posix/posix.go b/backend/posix/posix.go +index 0b18adc..4a9b040 100644 +--- a/backend/posix/posix.go ++++ b/backend/posix/posix.go +@@ -58,6 +58,10 @@ type Posix struct { + + rootfd *os.File + rootdir string ++ // fsys resolves every path below the root and the versioning directory ++ // without following a symbolic link, and treats any entry that is no ++ // regular file or directory as no object (see rootFS). ++ fsys *rootFS + // pathRoot is the directory bucket paths are built from: rootdir when + // PosixOpts.AbsolutePaths is set, otherwise "" because the process + // working directory is the root directory. See BucketPath. +@@ -435,6 +439,12 @@ func New(rootdir string, ms meta.MetadataStorer, opts PosixOpts) (*Posix, error) + } + } + ++ fsys, err := newRootFS(f, rootdirAbs, !opts.AbsolutePaths, versioningdirAbs, opts.BucketLinks) ++ if err != nil { ++ f.Close() ++ return nil, err ++ } ++ + if versioningdirAbs != "" { + fmt.Println("Bucket versioning enabled with directory:", versioningdirAbs) + } +@@ -467,8 +477,9 @@ func New(rootdir string, ms meta.MetadataStorer, opts PosixOpts) (*Posix, error) + } + + p := &Posix{ +- meta: ms, ++ meta: fsys.wrapMeta(ms, pathRoot), + rootfd: f, ++ fsys: fsys, + rootdir: rootdirAbs, + pathRoot: pathRoot, + euid: euid, +@@ -613,6 +624,9 @@ func isDirBelowRoot(root, dir string) bool { + } + + func (p *Posix) Shutdown() { ++ if p.fsys != nil { ++ p.fsys.close() ++ } + p.rootfd.Close() + } + +@@ -745,9 +759,9 @@ func (p *Posix) DoesBucketExist(bucket string) error { + // storing bucket metadata on it or building object paths through it. + func (p *Posix) doesBucketExist(bucket string) error { + path := p.BucketPath(bucket) +- fi, err := os.Lstat(path) ++ fi, err := p.fsys.Lstat(path) + if err == nil && p.bucketlinks && fi.Mode()&fs.ModeSymlink != 0 { +- fi, err = os.Stat(path) ++ fi, err = p.fsys.Stat(path) + } + // a symlink loop never resolves to a directory + if errors.Is(err, fs.ErrNotExist) || errors.Is(err, syscall.ELOOP) { +@@ -790,7 +804,7 @@ func (p *Posix) ListBuckets(ctx context.Context, input s3response.ListBucketsInp + } + defer release() + +- fis, err := listBucketFileInfos(p.rootPath(), p.bucketlinks) ++ fis, err := p.listBucketFileInfos(p.rootPath(), p.bucketlinks) + if err != nil { + return s3response.ListAllMyBucketsResult{}, fmt.Errorf("listBucketFileInfos : %w", err) + } +@@ -958,7 +972,7 @@ func (p *Posix) CreateBucket(ctx context.Context, input *s3.CreateBucketInput, a + return err + } + +- err = os.Mkdir(p.BucketPath(bucket), p.newDirPerm) ++ err = p.fsys.Mkdir(p.BucketPath(bucket), p.newDirPerm) + if err != nil && os.IsExist(err) { + // An existing entry that is not a bucket, such as a regular file at + // the root of a preexisting dataset, still takes the name but has +@@ -1013,7 +1027,7 @@ func (p *Posix) CreateBucket(ctx context.Context, input *s3.CreateBucketInput, a + }() + + if doChown { +- err = os.Chown(p.BucketPath(bucket), uid, gid) ++ err = p.fsys.Chown(p.BucketPath(bucket), uid, gid) + if err != nil { + return p.chownErr(bucket, uid, gid, err) + } +@@ -1072,14 +1086,14 @@ func (p *Posix) CreateBucket(ctx context.Context, input *s3.CreateBucketInput, a + // are logged rather than returned — the caller is already failing with the + // error that matters, and reporting a cleanup failure instead would hide it. + func (p *Posix) removePartialBucket(bucket string) { +- if err := os.RemoveAll(p.BucketPath(bucket)); err != nil { ++ if err := p.fsys.RemoveAll(p.BucketPath(bucket)); err != nil { + debuglogger.Logf("failed to remove partially created bucket (%q): %v", bucket, err) + } + if err := p.meta.DeleteAttributes(bucket, ""); err != nil { + debuglogger.Logf("failed to delete partially created bucket sidecar attributes (%q): %v", bucket, err) + } + if p.versioningEnabled() { +- err := os.RemoveAll(filepath.Join(p.versioningDir, bucket)) ++ err := p.fsys.RemoveAll(filepath.Join(p.versioningDir, bucket)) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + debuglogger.Logf("failed to remove partially created bucket version directory (%q): %v", bucket, err) + } +@@ -1092,7 +1106,7 @@ func (p *Posix) removePartialBucket(bucket string) { + // rewritten, so callers matching on EROFS or ErrObjectParentIsFile are + // unaffected. + func (p *Posix) mkdirAll(path string, uid, gid int, doChown bool) error { +- err := backend.MkdirAll(path, uid, gid, doChown, p.newDirPerm) ++ err := backend.MkdirAllFS(p.fsys, path, uid, gid, doChown, p.newDirPerm) + if doChown && errors.Is(err, syscall.EPERM) { + return p.chownErr(path, uid, gid, err) + } +@@ -1119,7 +1133,7 @@ func (p *Posix) chownErr(name string, uid, gid int, err error) error { + + func (p *Posix) isBucketEmpty(bucket string) error { + if p.versioningEnabled() { +- ents, err := os.ReadDir(filepath.Join(p.versioningDir, bucket)) ++ ents, err := p.fsys.ReadDir(filepath.Join(p.versioningDir, bucket)) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return fmt.Errorf("readdir bucket: %w", err) + } +@@ -1132,7 +1146,7 @@ func (p *Posix) isBucketEmpty(bucket string) error { + } + } + +- ents, err := os.ReadDir(p.BucketPath(bucket)) ++ ents, err := p.fsys.ReadDir(p.BucketPath(bucket)) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return fmt.Errorf("readdir bucket: %w", err) + } +@@ -1171,7 +1185,7 @@ func (p *Posix) DeleteBucket(ctx context.Context, bucket string) (err error) { + } + + // Remove the bucket +- err = os.RemoveAll(p.BucketPath(bucket)) ++ err = p.fsys.RemoveAll(p.BucketPath(bucket)) + if err != nil { + return fmt.Errorf("remove bucket: %w", err) + } +@@ -1184,7 +1198,7 @@ func (p *Posix) DeleteBucket(ctx context.Context, bucket string) (err error) { + } + // Remove the bucket from versioning directory + if p.versioningEnabled() { +- err = os.RemoveAll(filepath.Join(p.versioningDir, bucket)) ++ err = p.fsys.RemoveAll(filepath.Join(p.versioningDir, bucket)) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return fmt.Errorf("remove bucket version: %w", err) + } +@@ -1443,7 +1457,7 @@ func genObjVersionKey(key string) string { + func (p *Posix) deleteNullVersionIdObject(bucket, key string) error { + versionPath := filepath.Join(p.genObjVersionPath(bucket, key), nullVersionId) + +- err := os.Remove(versionPath) ++ err := p.fsys.Remove(versionPath) + if errors.Is(err, fs.ErrNotExist) { + return nil + } +@@ -1519,7 +1533,7 @@ func (p *Posix) isLiveObject(fi os.FileInfo, bucket, key string) (bool, error) { + // error matching fs.ErrNotExist is returned when key has no current + // version, including when the entry at its path is another key's object. + func (p *Posix) statLiveObject(bucket, key string) (os.FileInfo, error) { +- fi, err := os.Stat(p.ObjectPath(bucket, key)) ++ fi, err := p.fsys.Stat(p.ObjectPath(bucket, key)) + if isErrNotDir(err) { + return nil, fs.ErrNotExist + } +@@ -1605,7 +1619,7 @@ func (p *Posix) clearDirObjectAttrs(bucket, key string) error { + + // Creates a new copy(version) of an object in the versioning directory + func (p *Posix) createObjVersion(bucket, key string, size int64, acc auth.Account, removeAttributes bool) (versionPath string, err error) { +- sf, err := os.Open(p.ObjectPath(bucket, key)) ++ sf, err := p.fsys.Open(p.ObjectPath(bucket, key)) + if err != nil { + return "", err + } +@@ -1665,7 +1679,7 @@ func (p *Posix) createObjVersion(bucket, key string, size int64, acc auth.Accoun + + versionPath = filepath.Join(versionBucketPath, versioningKey) + +- err = backend.MkdirAll(filepath.Join(versionBucketPath, genObjVersionKey(key)), 0, 0, false, p.newDirPerm) ++ err = backend.MkdirAllFS(p.fsys, filepath.Join(versionBucketPath, genObjVersionKey(key)), 0, 0, false, p.newDirPerm) + if err != nil { + return versionPath, err + } +@@ -1699,7 +1713,7 @@ func (p *Posix) createObjVersion(bucket, key string, size int64, acc auth.Accoun + // record its place in the version history: it's the current + // version, which makes it newer than the versions already in the + // versioning directory and older than any version created later +- prev, err := newestObjVersionId(filepath.Join(versionBucketPath, genObjVersionKey(key))) ++ prev, err := p.newestObjVersionId(filepath.Join(versionBucketPath, genObjVersionKey(key))) + if err != nil { + return versionPath, fmt.Errorf("get newest object version: %w", err) + } +@@ -1790,7 +1804,7 @@ func (p *Posix) ensureNotDeleteMarker(bucket, object, versionId string) error { + // data file simply doesn't exist — the two cases are indistinguishable + // from metadata alone. Verify the data file directly so callers + // receive the correct NoSuchVersion / NoSuchKey error. +- if _, statErr := os.Stat(p.ObjectPath(bucket, object)); errors.Is(statErr, fs.ErrNotExist) || isErrNotDir(statErr) { ++ if _, statErr := p.fsys.Stat(p.ObjectPath(bucket, object)); errors.Is(statErr, fs.ErrNotExist) || isErrNotDir(statErr) { + if versionId != "" { + return s3err.GetAPIError(s3err.ErrNoSuchVersion) + } +@@ -1961,7 +1975,7 @@ func (p *Posix) fileToObjVersions(bucket string) backend.GetVersionsFunc { + + // List all the versions of the object in the versioning directory + versionPath := p.genObjVersionPath(bucket, p.encodeKey(key)) +- dirEnts, err := os.ReadDir(versionPath) ++ dirEnts, err := p.fsys.ReadDir(versionPath) + if errors.Is(err, fs.ErrNotExist) { + return result(false), nil + } +@@ -1978,7 +1992,7 @@ func (p *Posix) fileToObjVersions(bucket string) backend.GetVersionsFunc { + var nullVersionIdObj *s3response.ObjectVersion + var nullObjDelMarker *s3response.DeleteMarkerEntry + var nullPos nullVersionPos +- nf, err := os.Stat(filepath.Join(versionPath, nullVersionId)) ++ nf, err := p.fsys.Stat(filepath.Join(versionPath, nullVersionId)) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return nil, err + } +@@ -2213,7 +2227,7 @@ func (p *Posix) CreateMultipartUpload(ctx context.Context, mpu s3response.Create + tmppath := p.ObjectPath(bucket, objdir) + // the unique upload id is a directory for all of the parts + // associated with this specific multipart upload +- err = backend.MkdirAll(filepath.Join(tmppath, uploadID), 0, 0, false, p.newDirPerm) ++ err = backend.MkdirAllFS(p.fsys, filepath.Join(tmppath, uploadID), 0, 0, false, p.newDirPerm) + if err != nil { + if errors.Is(err, syscall.EDQUOT) { + return s3response.InitiateMultipartUploadResult{}, s3err.GetAPIError(s3err.ErrQuotaExceeded) +@@ -2562,7 +2576,7 @@ func (p *Posix) CompleteMultipartUploadWithCopy(ctx context.Context, input *s3.C + } + + partObjPath := filepath.Join(objdir, uploadName, fmt.Sprintf("%v", *part.PartNumber)) +- fi, err := os.Lstat(p.ObjectPath(bucket, partObjPath)) ++ fi, err := p.fsys.Stat(p.ObjectPath(bucket, partObjPath)) + if err != nil { + return "", s3err.GetInvalidPartErr(uploadID, *part.PartNumber, backend.GetStringFromPtr(part.ETag)) + } +@@ -2618,11 +2632,11 @@ func (p *Posix) CompleteMultipartUploadWithCopy(ctx context.Context, input *s3.C + if err != nil { + return res, "", err + } +- err = os.Rename(uploadIDDir, uploadIDInProgress) ++ err = p.fsys.Rename(uploadIDDir, uploadIDInProgress) + unlockClaim() + if errors.Is(err, fs.ErrNotExist) { + // Another call already claimed this slot and is still assembling the object. +- if _, statErr := os.Stat(uploadIDInProgress); statErr == nil { ++ if _, statErr := p.fsys.Stat(uploadIDInProgress); statErr == nil { + etag := multipartClaimToken + if p.dataIntegrityEtag { + etag, err = predictDataIntegrityFinalETag(activeUploadName) +@@ -2646,7 +2660,7 @@ func (p *Posix) CompleteMultipartUploadWithCopy(ctx context.Context, input *s3.C + if strings.HasSuffix(object, "/") { + return res, "", s3err.GetAPIError(s3err.ErrNoSuchUpload) + } +- fi, err := os.Stat(p.ObjectPath(bucket, object)) ++ fi, err := p.fsys.Stat(p.ObjectPath(bucket, object)) + if errors.Is(err, fs.ErrNotExist) || isErrNotDir(err) { + return res, "", s3err.GetAPIError(s3err.ErrNoSuchUpload) + } +@@ -2708,7 +2722,7 @@ func (p *Posix) CompleteMultipartUploadWithCopy(ctx context.Context, input *s3.C + newMetaObj := filepath.Join(metaObjDir, activeUploadName) + if err := p.meta.RenameObject(bucket, oldMetaObj, newMetaObj); err != nil { + // Roll back the data directory rename so a future retry can succeed. +- os.Rename(uploadIDInProgress, uploadIDDir) ++ p.fsys.Rename(uploadIDInProgress, uploadIDDir) + return res, "", fmt.Errorf("rename metadata for in-progress: %w", err) + } + +@@ -2726,7 +2740,7 @@ func (p *Posix) CompleteMultipartUploadWithCopy(ctx context.Context, input *s3.C + return + } + p.meta.RenameObject(bucket, newMetaObj, oldMetaObj) +- os.Rename(uploadIDInProgress, uploadIDDir) ++ p.fsys.Rename(uploadIDInProgress, uploadIDDir) + }() + + // Fast-fail precondition and directory checks before the parts are +@@ -2737,7 +2751,7 @@ func (p *Posix) CompleteMultipartUploadWithCopy(ctx context.Context, input *s3.C + if err != nil { + return res, "", err + } +- if d, err := os.Stat(p.ObjectPath(bucket, object)); err == nil && d.IsDir() { ++ if d, err := p.fsys.Stat(p.ObjectPath(bucket, object)); err == nil && d.IsDir() { + return res, "", s3err.GetAPIError(s3err.ErrExistingObjectIsDirectory) + } + +@@ -2798,7 +2812,7 @@ func (p *Posix) CompleteMultipartUploadWithCopy(ctx context.Context, input *s3.C + + partObjPath := filepath.Join(objdir, activeUploadName, fmt.Sprintf("%v", *part.PartNumber)) + fullPartPath := p.ObjectPath(bucket, partObjPath) +- fi, err := os.Lstat(fullPartPath) ++ fi, err := p.fsys.Stat(fullPartPath) + if err != nil { + return res, "", s3err.GetInvalidPartErr(uploadID, *part.PartNumber, backend.GetStringFromPtr(part.ETag)) + } +@@ -2969,7 +2983,7 @@ func (p *Posix) CompleteMultipartUploadWithCopy(ctx context.Context, input *s3.C + for _, part := range parts { + partObjPath := filepath.Join(objdir, activeUploadName, fmt.Sprintf("%v", *part.PartNumber)) + fullPartPath := p.ObjectPath(bucket, partObjPath) +- pf, err := os.Open(fullPartPath) ++ pf, err := p.fsys.Open(fullPartPath) + if err != nil { + return res, "", fmt.Errorf("open part %v: %v", *part.PartNumber, err) + } +@@ -3049,7 +3063,7 @@ func (p *Posix) CompleteMultipartUploadWithCopy(ctx context.Context, input *s3.C + } + vEnabled := p.isBucketVersioningEnabled(vStatus) + +- d, err := os.Stat(objname) ++ d, err := p.fsys.Stat(objname) + if err == nil && d.IsDir() { + // the directory is the object of the key with a trailing slash, or + // the parent of other objects: its attributes are not this object's +@@ -3164,7 +3178,7 @@ func (p *Posix) CompleteMultipartUploadWithCopy(ctx context.Context, input *s3.C + + err = f.link() + if err != nil { +- return res, "", publishErr(objname, err) ++ return res, "", p.publishErr(objname, err) + } + + // cleanup tmp dirs +@@ -3304,7 +3318,7 @@ func (p *Posix) checkUploadIDExists(bucket, object, uploadID string) ([32]byte, + sum := sha256.Sum256([]byte(object)) + objdir := filepath.Join(p.BucketPath(bucket), MetaTmpMultipartDir, fmt.Sprintf("%x", sum)) + +- _, err := os.Stat(filepath.Join(objdir, uploadID)) ++ _, err := p.fsys.Stat(filepath.Join(objdir, uploadID)) + if errors.Is(err, fs.ErrNotExist) { + return [32]byte{}, s3err.GetNoSuchUploadErr(uploadID) + } +@@ -3561,7 +3575,7 @@ func (p *Posix) AbortMultipartUpload(ctx context.Context, mpu *s3.AbortMultipart + sum := sha256.Sum256([]byte(object)) + objdir := filepath.Join(p.BucketPath(bucket), MetaTmpMultipartDir, fmt.Sprintf("%x", sum)) + +- f, err := os.Stat(filepath.Join(objdir, uploadID)) ++ f, err := p.fsys.Stat(filepath.Join(objdir, uploadID)) + if err != nil { + return s3err.GetNoSuchUploadErr(uploadID) + } +@@ -3583,7 +3597,7 @@ func (p *Posix) removeUpload(bucket, key, uploadName string) error { + objdir := filepath.Join(MetaTmpMultipartDir, fmt.Sprintf("%x", sha256.Sum256([]byte(key)))) + upiddir := filepath.Join(objdir, uploadName) + +- err := os.RemoveAll(p.ObjectPath(bucket, upiddir)) ++ err := p.fsys.RemoveAll(p.ObjectPath(bucket, upiddir)) + if err != nil { + return fmt.Errorf("remove multipart upload container: %w", err) + } +@@ -3593,7 +3607,7 @@ func (p *Posix) removeUpload(bucket, key, uploadName string) error { + } + + // Remove fails while other uploads of key remain +- if os.Remove(p.ObjectPath(bucket, objdir)) != nil { ++ if p.fsys.Remove(p.ObjectPath(bucket, objdir)) != nil { + return nil + } + err = p.meta.DeleteAttributes(bucket, objdir) +@@ -3602,7 +3616,7 @@ func (p *Posix) removeUpload(bucket, key, uploadName string) error { + } + // A new upload of key can make the directory again and store the name + // of key before the metadata of the removed directory is removed +- if _, err := os.Stat(p.ObjectPath(bucket, objdir)); err == nil { ++ if _, err := p.fsys.Stat(p.ObjectPath(bucket, objdir)); err == nil { + _ = p.meta.StoreAttribute(nil, bucket, objdir, onameAttr, []byte(key)) + } + return nil +@@ -3647,7 +3661,7 @@ func (p *Posix) ListMultipartUploads(ctx context.Context, mpu *s3.ListMultipartU + } + + // ignore readdir error and use the empty list returned +- objs, _ := os.ReadDir(p.ObjectPath(bucket, MetaTmpMultipartDir)) ++ objs, _ := p.fsys.ReadDir(p.ObjectPath(bucket, MetaTmpMultipartDir)) + + var uploads []s3response.Upload + +@@ -3671,7 +3685,7 @@ func (p *Posix) ListMultipartUploads(ctx context.Context, mpu *s3.ListMultipartU + continue + } + +- upids, err := os.ReadDir(filepath.Join(p.BucketPath(bucket), MetaTmpMultipartDir, obj.Name())) ++ upids, err := p.fsys.ReadDir(filepath.Join(p.BucketPath(bucket), MetaTmpMultipartDir, obj.Name())) + if err != nil { + continue + } +@@ -3794,7 +3808,7 @@ func (p *Posix) ListParts(ctx context.Context, input *s3.ListPartsInput) (s3resp + objdir := filepath.Join(MetaTmpMultipartDir, fmt.Sprintf("%x", sum)) + tmpdir := p.ObjectPath(bucket, objdir) + +- ents, err := os.ReadDir(filepath.Join(tmpdir, uploadID)) ++ ents, err := p.fsys.ReadDir(filepath.Join(tmpdir, uploadID)) + if errors.Is(err, fs.ErrNotExist) { + return lpr, s3err.GetNoSuchUploadErr(uploadID) + } +@@ -3843,7 +3857,7 @@ func (p *Posix) ListParts(ctx context.Context, input *s3.ListPartsInput) (s3resp + continue + } + +- fi, err := os.Lstat(p.ObjectPath(bucket, partPath)) ++ fi, err := p.fsys.Stat(p.ObjectPath(bucket, partPath)) + if err != nil { + continue + } +@@ -3953,7 +3967,7 @@ func (p *Posix) UploadPartWithPostFunc(ctx context.Context, input *s3.UploadPart + objdir := filepath.Join(MetaTmpMultipartDir, fmt.Sprintf("%x", sum)) + mpPath := filepath.Join(objdir, uploadID) + +- _, err = os.Stat(p.ObjectPath(bucket, mpPath)) ++ _, err = p.fsys.Stat(p.ObjectPath(bucket, mpPath)) + if errors.Is(err, fs.ErrNotExist) { + return nil, s3err.GetNoSuchUploadErr(uploadID) + } +@@ -4296,7 +4310,7 @@ func (p *Posix) UploadPartCopy(ctx context.Context, upi *s3.UploadPartCopyInput) + sum := sha256.Sum256([]byte(*upi.Key)) + objdir := filepath.Join(MetaTmpMultipartDir, fmt.Sprintf("%x", sum)) + +- _, err = os.Stat(filepath.Join(p.BucketPath(*upi.Bucket), objdir, *upi.UploadId)) ++ _, err = p.fsys.Stat(filepath.Join(p.BucketPath(*upi.Bucket), objdir, *upi.UploadId)) + if errors.Is(err, fs.ErrNotExist) { + return s3response.CopyPartResult{}, s3err.GetNoSuchUploadErr(*upi.UploadId) + } +@@ -4370,8 +4384,9 @@ func (p *Posix) UploadPartCopy(ctx context.Context, upi *s3.UploadPartCopyInput) + } + + objPath := p.ObjectPath(srcBucket, srcObject) +- fi, err := os.Stat(objPath) +- if errors.Is(err, fs.ErrNotExist) { ++ fi, err := p.fsys.Stat(objPath) ++ // a file, or a link, as a directory on the way: no such object either ++ if errors.Is(err, fs.ErrNotExist) || isErrNotDir(err) { + if p.versioningEnabled() && vEnabled { + return s3response.CopyPartResult{}, s3err.GetNoSuchVersionErr(srcKey, srcVersionId) + } +@@ -4410,7 +4425,7 @@ func (p *Posix) UploadPartCopy(ctx context.Context, upi *s3.UploadPartCopyInput) + return s3response.CopyPartResult{}, s3err.GetCopySourceObjectTooLargeErr(p.copyObjectThreshold) + } + +- srcf, err := os.Open(objPath) ++ srcf, err := p.fsys.Open(objPath) + if errors.Is(err, fs.ErrNotExist) { + return s3response.CopyPartResult{}, s3err.GetAPIError(s3err.ErrNoSuchKey) + } +@@ -4562,7 +4577,7 @@ func (p *Posix) UploadPartCopy(ctx context.Context, upi *s3.UploadPartCopyInput) + return s3response.CopyPartResult{}, fmt.Errorf("link object in namespace: %w", err) + } + +- fi, err = os.Stat(p.ObjectPath(*upi.Bucket, partPath)) ++ fi, err = p.fsys.Stat(p.ObjectPath(*upi.Bucket, partPath)) + if err != nil { + return s3response.CopyPartResult{}, fmt.Errorf("stat part path: %w", err) + } +@@ -4696,7 +4711,7 @@ func (p *Posix) snapshotObjVersion(bucket, key string, vStatus types.BucketVersi + } + + isDir := strings.HasSuffix(key, "/") +- d, err := os.Stat(p.ObjectPath(bucket, key)) ++ d, err := p.fsys.Stat(p.ObjectPath(bucket, key)) + if err != nil || d.IsDir() != isDir { + // nothing to snapshot + return nil +@@ -4969,7 +4984,7 @@ func (p *Posix) PutObjectWithPostFunc(ctx context.Context, po s3response.PutObje + // Setting it needs the directory to be owned by the gateway, + // otherwise it's left as is. + now := time.Now() +- _ = os.Chtimes(name, now, now) ++ _ = p.fsys.Chtimes(name, now, now) + } + + // Set object tagging once the etag makes the directory an object +@@ -5010,7 +5025,7 @@ func (p *Posix) PutObjectWithPostFunc(ctx context.Context, po s3response.PutObje + vEnabled := p.isBucketVersioningEnabled(vStatus) + + // object is file +- d, err := os.Stat(name) ++ d, err := p.fsys.Stat(name) + if err == nil && d.IsDir() { + return s3response.PutObjectOutput{}, s3err.GetAPIError(s3err.ErrExistingObjectIsDirectory) + } +@@ -5022,7 +5037,7 @@ func (p *Posix) PutObjectWithPostFunc(ctx context.Context, po s3response.PutObje + return s3response.PutObjectOutput{}, s3err.GetKeyTooLongErr(int64(len(*po.Key)), 1024) + } + if isErrNotDir(err) { +- parentErr := handleParentDirError(name) ++ parentErr := p.handleParentDirError(name) + if parentErr != nil { + return s3response.PutObjectOutput{}, parentErr + } +@@ -5141,7 +5156,7 @@ func (p *Posix) PutObjectWithPostFunc(ctx context.Context, po s3response.PutObje + + // The path may have become a directory while the body was staged: the + // attributes there belong to the directory, not to this object. +- d, err = os.Stat(name) ++ d, err = p.fsys.Stat(name) + if err == nil && d.IsDir() { + return s3response.PutObjectOutput{}, s3err.GetAPIError(s3err.ErrExistingObjectIsDirectory) + } +@@ -5242,7 +5257,7 @@ func (p *Posix) PutObjectWithPostFunc(ctx context.Context, po s3response.PutObje + + err = f.link() + if err != nil { +- return s3response.PutObjectOutput{}, publishErr(name, err) ++ return s3response.PutObjectOutput{}, p.publishErr(name, err) + } + + // Set object tagging +@@ -5284,7 +5299,7 @@ func (p *Posix) PutObjectWithPostFunc(ctx context.Context, po s3response.PutObje + + // publishErr returns the error for a request that failed to publish the + // object at path name in the namespace +-func publishErr(name string, err error) error { ++func (p *Posix) publishErr(name string, err error) error { + switch { + case errors.Is(err, syscall.EDQUOT): + return s3err.GetAPIError(s3err.ErrQuotaExceeded) +@@ -5301,7 +5316,7 @@ func publishErr(name string, err error) error { + return s3err.GetAPIError(s3err.ErrExistingObjectIsDirectory) + } + if !backend.IsPermissionErr(err) { +- if fi, serr := os.Stat(name); serr == nil && fi.IsDir() { ++ if fi, serr := p.fsys.Stat(name); serr == nil && fi.IsDir() { + return s3err.GetAPIError(s3err.ErrExistingObjectIsDirectory) + } + } +@@ -5400,10 +5415,23 @@ func (p *Posix) DeleteObject(ctx context.Context, input *s3.DeleteObjectInput) ( + IfMatchSize: input.IfMatchSize, + } + ++ // A symbolic link, FIFO, socket or device at the key is no object, but ++ // a delete of the key removes it: the entry itself, never what a link ++ // points to. The delete then goes on as for a missing object. A delete ++ // of a version, or one with preconditions, names an object and leaves ++ // such an entry alone. ++ if !isDir && getString(input.VersionId) == "" && ++ conds.IfMatch == nil && conds.IfMatchLastModTime == nil && conds.IfMatchSize == nil { ++ err = p.removeNonObject(objpath) ++ if err != nil { ++ return nil, err ++ } ++ } ++ + // evalVersionPreconditions evaluates the conditions against the + // version at bucket/object + evalVersionPreconditions := func(bucket, object string) error { +- f, err := os.Stat(p.ObjectPath(bucket, object)) ++ f, err := p.fsys.Stat(p.ObjectPath(bucket, object)) + if err != nil { + return nil + } +@@ -5425,7 +5453,7 @@ func (p *Posix) DeleteObject(ctx context.Context, input *s3.DeleteObjectInput) ( + } + + // if the versionId is not specified, make the current version a delete marker +- fi, err := os.Stat(objpath) ++ fi, err := p.fsys.Stat(objpath) + if errors.Is(err, fs.ErrNotExist) || isErrNotDir(err) { + // AWS returns success if the object does not exist + return &s3.DeleteObjectOutput{}, nil +@@ -5494,7 +5522,7 @@ func (p *Posix) DeleteObject(ctx context.Context, input *s3.DeleteObjectInput) ( + // when the version it hides was. Setting the time needs the + // entry to be owned by the gateway, otherwise it's left as is. + now := time.Now() +- _ = os.Chtimes(objpath, now, now) ++ _ = p.fsys.Chtimes(objpath, now, now) + + return &s3.DeleteObjectOutput{ + DeleteMarker: getBoolPtr(true), +@@ -5555,12 +5583,12 @@ func (p *Posix) DeleteObject(ctx context.Context, input *s3.DeleteObjectInput) ( + VersionId: input.VersionId, + }, nil + } +- err = os.Remove(objpath) ++ err = p.fsys.Remove(objpath) + if err != nil && !errors.Is(err, fs.ErrNotExist) && !isErrNotDir(err) { + return nil, fmt.Errorf("remove obj version: %w", err) + } + +- ents, err := os.ReadDir(versionPath) ++ ents, err := p.fsys.ReadDir(versionPath) + if errors.Is(err, fs.ErrNotExist) { + if err := p.meta.DeleteAttributes(bucket, object); err != nil && + !errors.Is(err, meta.ErrNoSuchKey) && !errors.Is(err, fs.ErrNotExist) { +@@ -5593,7 +5621,7 @@ func (p *Posix) DeleteObject(ctx context.Context, input *s3.DeleteObjectInput) ( + return nil, fmt.Errorf("get latest obj version: %w", err) + } + srcVersionId := srcObjVersion.Name() +- sf, err := os.Open(filepath.Join(versionPath, srcVersionId)) ++ sf, err := p.fsys.Open(filepath.Join(versionPath, srcVersionId)) + if err != nil { + return nil, fmt.Errorf("open obj version: %w", err) + } +@@ -5657,7 +5685,7 @@ func (p *Posix) DeleteObject(ctx context.Context, input *s3.DeleteObjectInput) ( + } + } + +- err = os.Remove(filepath.Join(versionPath, srcVersionId)) ++ err = p.fsys.Remove(filepath.Join(versionPath, srcVersionId)) + if err != nil { + return nil, fmt.Errorf("remove obj version %w", err) + } +@@ -5678,7 +5706,7 @@ func (p *Posix) DeleteObject(ctx context.Context, input *s3.DeleteObjectInput) ( + + isDelMarker, _ := p.isObjDeleteMarker(versionPath, *input.VersionId) + +- err = os.Remove(filepath.Join(versionPath, *input.VersionId)) ++ err = p.fsys.Remove(filepath.Join(versionPath, *input.VersionId)) + if isErrNameTooLong(err) { + return nil, s3err.GetKeyTooLongErr(int64(len(*input.Key)), 1024) + } +@@ -5711,7 +5739,7 @@ func (p *Posix) DeleteObject(ctx context.Context, input *s3.DeleteObjectInput) ( + return nil, err + } + +- fi, err := os.Stat(objpath) ++ fi, err := p.fsys.Stat(objpath) + if isErrNameTooLong(err) { + return nil, s3err.GetKeyTooLongErr(int64(len(*input.Key)), 1024) + } +@@ -5736,7 +5764,7 @@ func (p *Posix) DeleteObject(ctx context.Context, input *s3.DeleteObjectInput) ( + return &s3.DeleteObjectOutput{}, nil + } + +- err = os.Remove(objpath) ++ err = p.fsys.Remove(objpath) + if errors.Is(err, fs.ErrNotExist) || isErrNotDir(err) { + // another delete removed the object after the stat. + // AWS returns success if the object does not exist +@@ -5779,8 +5807,8 @@ func (p *Posix) DeleteObject(ctx context.Context, input *s3.DeleteObjectInput) ( + // empty string if it has none. The entries are named after the version id + // and os.ReadDir sorts them by name, which puts the ulid version ids in + // creation order. +-func newestObjVersionId(versionPath string) (string, error) { +- ents, err := os.ReadDir(versionPath) ++func (p *Posix) newestObjVersionId(versionPath string) (string, error) { ++ ents, err := p.fsys.ReadDir(versionPath) + if errors.Is(err, fs.ErrNotExist) { + return "", nil + } +@@ -5879,13 +5907,13 @@ func (p *Posix) deleteDirObjectLatestVersion(bucket, key string) error { + objpath := p.ObjectPath(bucket, key) + versionPath := p.genObjVersionPath(bucket, key) + +- ents, err := os.ReadDir(versionPath) ++ ents, err := p.fsys.ReadDir(versionPath) + if err != nil && !errors.Is(err, fs.ErrNotExist) { + return fmt.Errorf("read version dir: %w", err) + } + + if len(ents) == 0 { +- err := os.Remove(objpath) ++ err := p.fsys.Remove(objpath) + if isErrDirNotEmpty(err) { + // the directory stays as the parent of the objects under it + err = p.clearDirObjectAttrs(bucket, key) +@@ -5935,7 +5963,7 @@ func (p *Posix) deleteDirObjectLatestVersion(bucket, key string) error { + } + } + +- err = os.Remove(filepath.Join(versionPath, srcVersionId)) ++ err = p.fsys.Remove(filepath.Join(versionPath, srcVersionId)) + if err != nil { + return fmt.Errorf("remove obj version: %w", err) + } +@@ -5945,7 +5973,7 @@ func (p *Posix) deleteDirObjectLatestVersion(bucket, key string) error { + + // The restored version keeps its last modified time. Setting it needs + // the directory to be owned by the gateway, otherwise it's left as is. +- _ = os.Chtimes(objpath, time.Now(), srcInfo.ModTime()) ++ _ = p.fsys.Chtimes(objpath, time.Now(), srcInfo.ModTime()) + + return nil + } +@@ -5977,7 +6005,7 @@ func (p *Posix) removeParents(bucket, object string) { + + // The parent may have been replaced by an object since its + // attribute was checked: remove it only if it is a directory. +- err = removeDir(p.ObjectPath(bucket, parent)) ++ err = p.fsys.Rmdir(p.ObjectPath(bucket, parent)) + if err != nil { + break + } +@@ -6140,7 +6168,7 @@ func (p *Posix) GetObjectWithPreReadFunc(ctx context.Context, input *s3.GetObjec + + objPath := p.ObjectPath(bucket, object) + +- fid, err := os.Stat(objPath) ++ fid, err := p.fsys.Stat(objPath) + if errors.Is(err, fs.ErrNotExist) || isErrNotDir(err) { + if versionId != "" { + return nil, s3err.GetNoSuchVersionErr(*input.Key, versionId) +@@ -6315,7 +6343,7 @@ func (p *Posix) GetObjectWithPreReadFunc(ctx context.Context, input *s3.GetObjec + // openForRead opens with FILE_SHARE_DELETE on Windows so that a concurrent + // DeleteObject can call os.Remove on this file while the GET response body + // is still being streamed. On POSIX, os.Open is sufficient. +- f, err := openForRead(objPath, p.enableODirect) ++ f, err := p.openForRead(objPath, p.enableODirect) + if IsEntryGone(err) { + // the object was removed after the stat above, or its directory + // was, which a shared filesystem can report as ENOTDIR or ESTALE. +@@ -6540,7 +6568,7 @@ func (p *Posix) HeadObject(ctx context.Context, input *s3.HeadObjectInput) (*s3. + + objPath := p.ObjectPath(bucket, object) + +- fi, err := os.Stat(objPath) ++ fi, err := p.fsys.Stat(objPath) + if errors.Is(err, fs.ErrNotExist) || isErrNotDir(err) { + if versionId != "" { + return nil, s3err.GetNoSuchVersionErr(*input.Key, versionId) +@@ -6947,7 +6975,7 @@ func (p *Posix) CopyObject(ctx context.Context, input s3response.CopyObjectInput + } + + objPath := joinPathWithTrailer(p.BucketPath(srcBucket), srcObject) +- f, err := os.Open(objPath) ++ f, err := p.fsys.Open(objPath) + if errors.Is(err, fs.ErrNotExist) || isErrNotDir(err) { + if p.versioningEnabled() && vEnabled { + return s3response.CopyObjectOutput{}, s3err.GetNoSuchVersionErr(origSrcObject, srcVersionId) +@@ -7067,7 +7095,7 @@ func (p *Posix) CopyObject(ctx context.Context, input s3response.CopyObjectInput + // If a different checksum algorith is specified + // first caclculate and store the checksum + if checksums.Algorithm != input.ChecksumAlgorithm { +- f, err := os.Open(dstObjdPath) ++ f, err := p.fsys.Open(dstObjdPath) + if err != nil { + return s3response.CopyObjectOutput{}, fmt.Errorf("open obj file: %w", err) + } +@@ -7287,7 +7315,7 @@ func (p *Posix) CopyObject(ctx context.Context, input s3response.CopyObjectInput + chType = res.ChecksumType + } + +- fi, err = os.Stat(dstObjdPath) ++ fi, err = p.fsys.Stat(dstObjdPath) + if err != nil { + return s3response.CopyObjectOutput{}, fmt.Errorf("stat dst object: %w", err) + } +@@ -8455,8 +8483,8 @@ func (p *Posix) ChangeBucketOwner(ctx context.Context, bucket, owner string) (er + + // listBucketFileInfos returns the file info of every bucket directory under + // rootdir. With bucketlinks, a symlink to a directory counts as a bucket too. +-func listBucketFileInfos(rootdir string, bucketlinks bool) ([]fs.FileInfo, error) { +- entries, err := os.ReadDir(rootdir) ++func (p *Posix) listBucketFileInfos(rootdir string, bucketlinks bool) ([]fs.FileInfo, error) { ++ entries, err := p.fsys.ReadDir(rootdir) + if err != nil { + return nil, fmt.Errorf("readdir buckets: %w", err) + } +@@ -8473,7 +8501,7 @@ func listBucketFileInfos(rootdir string, bucketlinks bool) ([]fs.FileInfo, error + } + + if bucketlinks && entry.Type() == fs.ModeSymlink { +- fi, err = os.Stat(filepath.Join(rootdir, entry.Name())) ++ fi, err = p.fsys.Stat(filepath.Join(rootdir, entry.Name())) + if err != nil { + // skip entries returning errors + continue +@@ -8498,7 +8526,7 @@ func (p *Posix) ListBucketsAndOwners(ctx context.Context) (buckets []s3response. + } + defer release() + +- fis, err := listBucketFileInfos(p.rootPath(), p.bucketlinks) ++ fis, err := p.listBucketFileInfos(p.rootPath(), p.bucketlinks) + if err != nil { + return buckets, fmt.Errorf("listBucketFileInfos: %w", err) + } +diff --git a/backend/posix/with_otmpfile.go b/backend/posix/with_otmpfile.go +index e6c0e69..6879d07 100644 +--- a/backend/posix/with_otmpfile.go ++++ b/backend/posix/with_otmpfile.go +@@ -38,6 +38,8 @@ import ( + const procfddir = "/proc/self/fd" + + type tmpfile struct { ++ // fsys is the backend's file system, which the file is published on ++ fsys *rootFS + f *os.File + bucket string + objname string +@@ -85,7 +87,7 @@ func (p *Posix) openTmpFile(dir, bucket, obj string, size int64, acct auth.Accou + + filePerm := uint32(p.newFilePerm.Perm()) + +- fd, err := unix.Open(dir, openFlags, filePerm) ++ fd, err := p.fsys.openTmpfile(dir, openFlags, filePerm) + if err != nil { + if errors.Is(err, syscall.EROFS) { + return nil, s3err.GetAPIError(s3err.ErrMethodNotAllowed) +@@ -94,7 +96,7 @@ func (p *Posix) openTmpFile(dir, bucket, obj string, size int64, acct auth.Accou + if p.enableODirect && bool(allowODirect) && isODirectUnsupportedOpenErr(err) { + warnODirectUnsupportedOnce("openTmpFile", err) + +- fd, err = unix.Open(dir, unix.O_RDWR|unix.O_TMPFILE|unix.O_CLOEXEC, filePerm) ++ fd, err = p.fsys.openTmpfile(dir, unix.O_RDWR|unix.O_TMPFILE|unix.O_CLOEXEC, filePerm) + if err == nil { + useODirect = false + } else if errors.Is(err, syscall.EROFS) { +@@ -123,6 +125,7 @@ func (p *Posix) openTmpFile(dir, bucket, obj string, size int64, acct auth.Accou + } + + tmp := &tmpfile{ ++ fsys: p.fsys, + f: f, + bucket: bucket, + objname: obj, +@@ -162,7 +165,7 @@ func (p *Posix) openMkTemp(dir, bucket, obj string, size int64, dofalloc bool, u + } + return nil, fmt.Errorf("make temp dir: %w", err) + } +- f, err := os.CreateTemp(dir, ++ f, err := p.fsys.CreateTemp(dir, + fmt.Sprintf("%x.", sha256.Sum256([]byte(obj)))) + if err != nil { + if errors.Is(err, syscall.EROFS) { +@@ -173,30 +176,23 @@ func (p *Posix) openMkTemp(dir, bucket, obj string, size int64, dofalloc bool, u + + useODirect := false + if p.enableODirect && bool(allowODirect) { +- name := f.Name() +- if err := f.Close(); err != nil { +- os.Remove(name) +- return nil, fmt.Errorf("close temp file before O_DIRECT reopen: %w", err) +- } +- +- fd, err := unix.Open(name, unix.O_RDWR|unix.O_CLOEXEC|unix.O_DIRECT, uint32(p.newFilePerm.Perm())) ++ // the file is opened again through its descriptor, not its name ++ df, err := reopenFile(f, unix.O_RDWR|unix.O_DIRECT) + if err == nil { +- f = os.NewFile(uintptr(fd), name) ++ f.Close() ++ f = df + useODirect = true + } else if isODirectUnsupportedOpenErr(err) { + warnODirectUnsupportedOnce("openMkTemp", err) +- f, err = os.OpenFile(name, os.O_RDWR, 0) +- if err != nil { +- os.Remove(name) +- return nil, fmt.Errorf("reopen temp file after O_DIRECT fallback: %w", err) +- } + } else { +- os.Remove(name) ++ f.Close() ++ p.fsys.Remove(f.Name()) + return nil, fmt.Errorf("open temp file with O_DIRECT: %w", err) + } + } + + tmp := &tmpfile{ ++ fsys: p.fsys, + f: f, + bucket: bucket, + objname: obj, +@@ -218,7 +214,7 @@ func (p *Posix) openMkTemp(dir, bucket, obj string, size int64, dofalloc bool, u + err := f.Chown(uid, gid) + if err != nil { + f.Close() +- os.Remove(f.Name()) ++ p.fsys.Remove(f.Name()) + return nil, fmt.Errorf("set temp file ownership: %w", p.chownErr(filepath.Join(bucket, obj), uid, gid, err)) + } + } +@@ -315,13 +311,13 @@ func (tmp *tmpfile) link() error { + } + + err = tmp.publishInDir(dir, func() error { +- dirf, err := os.Open(dir) ++ dirf, err := tmp.fsys.dirAt("open", dir) + if err != nil { + return fmt.Errorf("open parent dir: %w", err) + } +- defer dirf.Close() ++ defer dirf.close() + +- err = linkatOTmpfile(int(procdir.Fd()), int(dirf.Fd()), ++ err = linkatOTmpfile(int(procdir.Fd()), dirf.fd, + srcFDName, filepath.Base(objPath)) + if err != nil { + return fmt.Errorf("link tmpfile (fd %q as %q): %w", +@@ -368,7 +364,7 @@ func (tmp *tmpfile) fallbackLink() error { + err = tmp.publishInDir(filepath.Dir(objPath), func() error { + // rename only works for files within the same filesystem, + // MoveFile falls back to copy otherwise +- return backend.MoveFile(tempname, objPath, tmp.newFilePerm) ++ return backend.MoveFileFS(tmp.fsys, tempname, objPath, tmp.newFilePerm) + }) + if err != nil { + return err +@@ -380,6 +376,20 @@ func (tmp *tmpfile) fallbackLink() error { + func (tmp *tmpfile) cleanup() { + tmp.f.Close() + if !strings.HasPrefix(tmp.f.Name(), procfddir) { +- os.Remove(tmp.f.Name()) ++ tmp.fsys.Remove(tmp.f.Name()) ++ } ++} ++ ++// reopenFile opens the file of f again with flag, through its descriptor. ++func reopenFile(f *os.File, flag int) (*os.File, error) { ++ for { ++ fd, err := unix.Open(filepath.Join(procfddir, strconv.Itoa(int(f.Fd()))), flag|unix.O_CLOEXEC, 0) ++ if err == unix.EINTR { ++ continue ++ } ++ if err != nil { ++ return nil, &os.PathError{Op: "open", Path: f.Name(), Err: err} ++ } ++ return os.NewFile(uintptr(fd), f.Name()), nil + } + } +diff --git a/backend/posix/without_otmpfile.go b/backend/posix/without_otmpfile.go +index 77f2d7c..d306298 100644 +--- a/backend/posix/without_otmpfile.go ++++ b/backend/posix/without_otmpfile.go +@@ -37,6 +37,8 @@ const ( + ) + + type tmpfile struct { ++ // fsys is the backend's file system, which the file is published on ++ fsys *rootFS + f *os.File + bucket string + objname string +@@ -79,7 +81,7 @@ func (p *Posix) openTmpFile(dir, bucket, obj string, size int64, acct auth.Accou + } + return nil, fmt.Errorf("make temp dir: %w", err) + } +- f, err := os.CreateTemp(dir, ++ f, err := p.fsys.CreateTemp(dir, + fmt.Sprintf("%x.", sha256.Sum256([]byte(obj)))) + if err != nil { + if errors.Is(err, syscall.EROFS) { +@@ -92,12 +94,13 @@ func (p *Posix) openTmpFile(dir, bucket, obj string, size int64, acct auth.Accou + err := f.Chown(uid, gid) + if err != nil { + f.Close() +- os.Remove(f.Name()) ++ p.fsys.Remove(f.Name()) + return nil, fmt.Errorf("set temp file ownership: %w", p.chownErr(filepath.Join(bucket, obj), uid, gid, err)) + } + } + + return &tmpfile{ ++ fsys: p.fsys, + f: f, + bucket: bucket, + objname: obj, +@@ -139,7 +142,7 @@ func (tmp *tmpfile) link() error { + } + + err = tmp.publishInDir(filepath.Dir(objPath), func() error { +- return backend.MoveFile(tempname, objPath, tmp.newFilePerm) ++ return backend.MoveFileFS(tmp.fsys, tempname, objPath, tmp.newFilePerm) + }) + if err != nil { + return err +@@ -149,5 +152,11 @@ func (tmp *tmpfile) link() error { + + func (tmp *tmpfile) cleanup() { + tmp.f.Close() +- os.Remove(tmp.f.Name()) ++ tmp.fsys.Remove(tmp.f.Name()) ++} ++ ++// reopenFile opens the file of f again with flag. Only O_DIRECT, which this ++// platform has no use for, reopens a file. ++func reopenFile(f *os.File, flag int) (*os.File, error) { ++ return os.OpenFile(f.Name(), flag, 0) + } +-- +2.49.0.windows.1 + diff --git a/tests/no-symlinks/bench.py b/tests/no-symlinks/bench.py new file mode 100644 index 0000000..7f86d0b --- /dev/null +++ b/tests/no-symlinks/bench.py @@ -0,0 +1,67 @@ +#!/usr/bin/env python3 +"""Time the S3 calls the no-follow resolution adds syscalls to. + + S3_ENDPOINT=... S3_KEY=... S3_SECRET=... S3_REGION=... S3REQ=.../s3req.py \\ + bench.py + +PUTs 1 KiB objects at bench/a/b/c/obj- (four directories deep), then +GETs and HEADs each, then lists the prefix 10 times (ListObjectsV2, 1000 keys a +page), then DELETEs them. Prints the median and the 90th percentile of each +call in milliseconds, one line per call. One connection per request, as +s3req.py makes them. Python standard library only. +""" + +import http.client +import importlib.util +import os +import statistics +import sys +import time +import urllib.parse + + +def main(argv): + if len(argv) != 2: + sys.exit(__doc__) + bucket, count = argv[0], int(argv[1]) + spec = importlib.util.spec_from_file_location("s3req", os.environ["S3REQ"]) + s3req = importlib.util.module_from_spec(spec) + spec.loader.exec_module(s3req) + endpoint = urllib.parse.urlsplit(os.environ["S3_ENDPOINT"]) + key, secret = os.environ["S3_KEY"], os.environ["S3_SECRET"] + region = os.environ.get("S3_REGION", "us-east-1") + + def request(method, path, query="", body=b""): + headers = {} + s3req.sign(method, endpoint.netloc, path, query, headers, body, key, secret, region) + conn = http.client.HTTPConnection(endpoint.hostname, endpoint.port, timeout=30) + target = s3req.quote(path, safe="/") + ("?" + query if query else "") + t0 = time.perf_counter() + conn.request(method, target, body=body or None, headers=headers) + resp = conn.getresponse() + resp.read() + dt = (time.perf_counter() - t0) * 1000 + conn.close() + if resp.status >= 300: + sys.exit(f"{method} {path}?{query}: {resp.status}") + return dt + + body = os.urandom(1024) + keys = [f"/{bucket}/bench/a/b/c/obj-{n:05d}" for n in range(count)] + times = {} + for name, fn in [ + ("PUT", lambda k: request("PUT", k, body=body)), + ("GET", lambda k: request("GET", k)), + ("HEAD", lambda k: request("HEAD", k)), + ]: + times[name] = [fn(k) for k in keys] + times["LIST"] = [request("GET", f"/{bucket}", f"list-type=2&max-keys=1000&prefix=bench/") for _ in range(10)] + times["DELETE"] = [request("DELETE", k) for k in keys] + for name, ts in times.items(): + ts = sorted(ts) + p90 = ts[min(len(ts) - 1, int(len(ts) * 0.9))] + print(f"{name:6} n={len(ts):5} median {statistics.median(ts):7.2f} ms p90 {p90:7.2f} ms") + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/tests/no-symlinks/bench.sh b/tests/no-symlinks/bench.sh new file mode 100644 index 0000000..7285e28 --- /dev/null +++ b/tests/no-symlinks/bench.sh @@ -0,0 +1,56 @@ +#!/bin/bash +# +# What 0005's resolution costs: one throwaway gateway from the given binary on +# 127.0.0.1:${BENCH_PORT:-7395}, posix on ${BENCH_DIR:-/var/tmp/s3gw-nf-bench}, internal IAM. +# +# sudo bash bench.sh /path/to/versitygw [count] +# +# Times (default 500) PUT, GET, HEAD and DELETE calls of 1 KiB objects +# four directories deep, and ten listings of them (bench.py), then counts the +# gateway's system calls (strace -f -c) for 100 GETs and 100 HEADs of one of +# them. Run it with the patched build and with a stock one on the same node, one +# after the other. Nothing installed is touched; the directory is removed at +# exit. + +set -uo pipefail + +VGW=${1:?usage: bench.sh /path/to/versitygw [count]} +COUNT=${2:-500} +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +export S3REQ=${S3REQ:-$HERE/../owner-scope/s3req.py} +PORT=${BENCH_PORT:-7395} +W=${BENCH_DIR:-/var/tmp/s3gw-nf-bench} +export S3_ENDPOINT=http://127.0.0.1:$PORT S3_REGION=us-east-1 + +[ -x "$VGW" ] || { echo "FATAL: $VGW is not an executable" >&2; exit 2; } +rm -rf "$W" && mkdir -p "$W/iam" "$W/data" || exit 2 +RK=benchroot RS=$(python3 -c 'import secrets; print(secrets.token_hex(16))') +export S3_KEY=bench S3_SECRET=$(python3 -c 'import secrets; print(secrets.token_hex(16))') +"$VGW" --access "$RK" --secret "$RS" --region "$S3_REGION" --port "127.0.0.1:$PORT" --iam-dir "$W/iam" \ + posix "$W/data" >"$W/gateway.log" 2>&1 & +GW=$! +trap 'kill $GW 2>/dev/null; wait $GW 2>/dev/null; rm -rf "$W"' EXIT +for _ in $(seq 1 50); do (exec 3<>"/dev/tcp/127.0.0.1/$PORT") 2>/dev/null && break; sleep 0.2; done +admin() { ADMIN_ACCESS_KEY_ID=$RK ADMIN_SECRET_ACCESS_KEY=$RS "$VGW" admin --region "$S3_REGION" --endpoint-url "$S3_ENDPOINT" "$@"; } +admin create-user --access "$S3_KEY" --secret "$S3_SECRET" --role user --user-id 74990 --group-id 74990 >/dev/null && + admin create-bucket --owner "$S3_KEY" --bucket bench >/dev/null || { echo "FATAL: setup failed" >&2; exit 2; } + +echo "versitygw sha256 $(sha256sum "$VGW" | cut -c1-16), $(uname -r), $(df -T "$W" | awk 'NR==2 {print $2}')" +python3 "$HERE/bench.py" bench "$COUNT" || exit 1 + +if command -v strace >/dev/null; then + printf 'x' >"$W/one" && python3 "$S3REQ" PUT /bench/s/a/b/c/one.txt --body "$W/one" >/dev/null + for method in GET HEAD; do + strace -f -c -o "$W/strace.$method" -p "$GW" 2>/dev/null & + ST=$! + sleep 1 + for _ in $(seq 1 100); do python3 "$S3REQ" "$method" /bench/s/a/b/c/one.txt -o /dev/null >/dev/null; done + sleep 0.5 + kill -INT "$ST"; wait "$ST" 2>/dev/null + # rows: % time, seconds, usecs/call, calls, [errors,] syscall + total=$(awk '$1 ~ /^[0-9.]+$/ && $NF != "total" {s += $4} END {print s + 0}' "$W/strace.$method") + top=$(awk '$1 ~ /^[0-9.]+$/ && $NF != "total" {print $NF ":" $4}' "$W/strace.$method" | + sort -t: -k2 -rn | head -8 | tr '\n' ' ') + echo "$method x100: $total system calls in the gateway ($((total / 100)) a call); most: $top" + done +fi diff --git a/tests/no-symlinks/proof.sh b/tests/no-symlinks/proof.sh new file mode 100644 index 0000000..a6615d8 --- /dev/null +++ b/tests/no-symlinks/proof.sh @@ -0,0 +1,252 @@ +#!/bin/bash +# +# Proof test for patches/v1.11.0/0005-posix-no-symlinks.patch. +# +# sudo bash proof.sh /path/to/versitygw +# +# Starts two throwaway gateways from the given binary, A on 127.0.0.1:${PROOF_PORT:-7393} +# and B on the next port, each on the posix backend rooted at its own namespace +# directory under ${PROOF_DIR:-/var/tmp/s3gw-no-symlinks} (ns-a, ns-b), with its own +# internal IAM, --chuid --chgid and --dir-perms 0700 as leil-rig's gateways run. +# It then replays Norn's M5 stage 13 escape layout: as root, owned by the user's +# UID, it plants in A's home and in B's bucket links to the other namespace's +# marker (absolute and relative), a link to a directory there, a link to another +# user's home in the same namespace, a FIFO, a socket and a device, and drives +# every S3 operation at them. Nothing installed is touched: no package, unit or +# config. Prints one line per check and exits non-zero if any fails. KEEP=1 +# leaves the directory (and both gateways' logs) behind. +# +# The accounts, made by root through each gateway's admin API, on +# leil-cluster's reserved test band: +# +# ns-user uid 74990 user owns "home" on A and "data" on B +# ns-other uid 74991 user owns "sibling" on A (another user's home) +# +# It needs root: it chowns, plants entries as root and makes a device node. + +set -uo pipefail + +VGW=${1:?usage: proof.sh /path/to/versitygw} +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +S3REQ=${S3REQ:-$HERE/../owner-scope/s3req.py} +PORT_A=${PROOF_PORT:-7393} +PORT_B=$((PORT_A + 1)) +W=${PROOF_DIR:-/var/tmp/s3gw-no-symlinks} +export S3_REGION=us-east-1 +UID_USER=74990 UID_OTHER=74991 + +[ -x "$VGW" ] || { echo "FATAL: $VGW is not an executable" >&2; exit 2; } +[ -f "$S3REQ" ] || { echo "FATAL: $S3REQ is missing (tests/owner-scope/s3req.py)" >&2; exit 2; } +[ "$(id -u)" = 0 ] || { echo "FATAL: run as root" >&2; exit 2; } +command -v python3 >/dev/null || { echo "FATAL: python3 is required" >&2; exit 2; } +for port in "$PORT_A" "$PORT_B"; do + if (exec 3<>"/dev/tcp/127.0.0.1/$port") 2>/dev/null; then + echo "FATAL: something already listens on 127.0.0.1:$port (set PROOF_PORT)" >&2 + exit 2 + fi +done + +rm -rf "$W" && mkdir -p "$W/ns-a" "$W/ns-b" "$W/iam-a" "$W/iam-b" "$W/tmp" || exit 2 +chmod 0711 "$W" "$W/ns-a" "$W/ns-b" +secret() { python3 -c 'import secrets; print(secrets.token_hex(16))'; } +declare -A KEY SECRET +for who in root ns-user ns-other; do KEY[$who]=$who SECRET[$who]=$(secret); done +KEY[root]=proofroot + +start() { # start + "$VGW" --access "${KEY[root]}" --secret "${SECRET[root]}" --region "$S3_REGION" \ + --port "127.0.0.1:$2" --iam-dir "$4" \ + posix --chuid --chgid --dir-perms 0700 "$3" >"$W/gateway-$1.log" 2>&1 & + echo $! +} +GW_A=$(start a "$PORT_A" "$W/ns-a" "$W/iam-a") +GW_B=$(start b "$PORT_B" "$W/ns-b" "$W/iam-b") +cleanup() { + kill "$GW_A" "$GW_B" 2>/dev/null + wait "$GW_A" "$GW_B" 2>/dev/null + [ "${KEEP:-0}" = 1 ] && echo "kept $W" || rm -rf "$W" +} +trap cleanup EXIT +for port in "$PORT_A" "$PORT_B"; do + for _ in $(seq 1 50); do + (exec 3<>"/dev/tcp/127.0.0.1/$port") 2>/dev/null && break + kill -0 "$GW_A" 2>/dev/null && kill -0 "$GW_B" 2>/dev/null || + { cat "$W"/gateway-*.log; echo "FATAL: a gateway exited" >&2; exit 2; } + sleep 0.2 + done +done +echo "gateways $("$VGW" --version 2>&1 | head -1) on 127.0.0.1:$PORT_A (A) and :$PORT_B (B), sha256 $(sha256sum "$VGW" | cut -c1-16)" + +port() { [ "$1" = A ] && echo "$PORT_A" || echo "$PORT_B"; } +admin() { # admin + local gw=$1; shift + ADMIN_ACCESS_KEY_ID=${KEY[root]} ADMIN_SECRET_ACCESS_KEY=${SECRET[root]} \ + "$VGW" admin --region "$S3_REGION" --endpoint-url "http://127.0.0.1:$(port "$gw")" "$@" +} +# req -- one request; prints the status +req() { + local gw=$1 who=$2; shift 2 + S3_ENDPOINT=http://127.0.0.1:$(port "$gw") S3_KEY=${KEY[$who]} S3_SECRET=${SECRET[$who]} \ + timeout 20 python3 "$S3REQ" "$@" 2>"$W/tmp/err" || [ -s "$W/tmp/err" ] || echo "no answer in 20 s" >"$W/tmp/err" +} + +PASS=0 FAIL=0 +ok() { PASS=$((PASS + 1)); printf 'PASS %-4s %s %s\n' "$1" "$2" "$3"; } +bad() { FAIL=$((FAIL + 1)); printf 'FAIL %-4s %s (want %s) %s [%s]\n' "$1" "${2:-none}" "$3" "$4" "$5"; } +# check +check() { + local id=$1 want=$2 what=$3; shift 3 + local got + got=$(req "$@") + if [ "$got" = "$want" ]; then ok "$id" "$got" "$what"; else bad "$id" "$got" "$want" "$what" "$(tr '\n' ' ' <"$W/tmp/err")"; fi +} +# check_cmd -- whether the command succeeds +check_cmd() { + local id=$1 want=$2 what=$3; shift 3 + local got=yes + "$@" >"$W/tmp/err" 2>&1 || got=no + if [ "$got" = "$want" ]; then ok "$id" "$got" "$what"; else bad "$id" "$got" "$want" "$what" "$(tr '\n' ' ' <"$W/tmp/err")"; fi +} + +# The namespaces' data, as each gateway stores it +A=$W/ns-a B=$W/ns-b +MARK_A="marker of home namespace A" MARK_B="marker of bucket namespace B" MARK_SIB="marker of another home in A" +is_file() { [ -f "$1" ] && [ ! -L "$1" ]; } +is_link() { [ -L "$1" ]; } +holds() { [ "$(cat "$1" 2>/dev/null)" = "$2" ]; } +absent() { [ ! -e "$1" ] && [ ! -L "$1" ]; } +no_attrs() { [ -z "$(getfattr --absolute-names -d -m '^user\.X-Amz' "$1" 2>/dev/null)" ]; } +markers_intact() { + holds "$A/home/escape/marker.txt" "$MARK_A" && holds "$B/data/escape/marker.txt" "$MARK_B" && + holds "$A/sibling/secret.txt" "$MARK_SIB" && no_attrs "$A/home/escape/marker.txt" && + no_attrs "$B/data/escape/marker.txt" && no_attrs "$A/sibling/secret.txt" +} + +echo "--- setup (root, admin API; then the planted entries, as root)" +for gw in A B; do + check_cmd S1$gw yes "$gw create-user ns-user (uid $UID_USER)" \ + admin "$gw" create-user --access ns-user --secret "${SECRET[ns-user]}" --role user --user-id $UID_USER --group-id $UID_USER +done +check_cmd S2 yes "A create-user ns-other (uid $UID_OTHER)" \ + admin A create-user --access ns-other --secret "${SECRET[ns-other]}" --role user --user-id $UID_OTHER --group-id $UID_OTHER +check_cmd S3 yes "A create-bucket home --owner ns-user" admin A create-bucket --owner ns-user --bucket home +check_cmd S4 yes "A create-bucket sibling --owner ns-other" admin A create-bucket --owner ns-other --bucket sibling +check_cmd S5 yes "B create-bucket data --owner ns-user" admin B create-bucket --owner ns-user --bucket data +printf '%s' "$MARK_A" >"$W/tmp/mark-a"; printf '%s' "$MARK_B" >"$W/tmp/mark-b"; printf '%s' "$MARK_SIB" >"$W/tmp/mark-sib" +check S6 200 "A ns-user PutObject home/escape/marker.txt" A ns-user PUT /home/escape/marker.txt --body "$W/tmp/mark-a" +check S7 200 "B ns-user PutObject data/escape/marker.txt" B ns-user PUT /data/escape/marker.txt --body "$W/tmp/mark-b" +check S8 200 "A ns-other PutObject sibling/secret.txt" A ns-other PUT /sibling/secret.txt --body "$W/tmp/mark-sib" + +plant() { # plant + local d=$1 other=$2 rel=$3 + ln -s "$other/marker.txt" "$d/link-abs" && ln -s "$rel/marker.txt" "$d/link-rel" && + ln -s "$other" "$d/link-dir" && ln -s "$other/marker.txt" "$d/link-del" && + mkfifo "$d/fifo" && python3 -c 'import socket,sys; s=socket.socket(socket.AF_UNIX); s.bind(sys.argv[1])' "$d/sock" && + mknod "$d/dev" c 1 3 && chown -h $UID_USER:$UID_USER "$d"/link-* "$d/fifo" "$d/sock" "$d/dev" +} +check_cmd S9 yes "plant in A home/escape: links to B's marker (abs, ../../../ns-b/...), to B's dir, FIFO, socket, device" \ + plant "$A/home/escape" "$B/data/escape" ../../../ns-b/data/escape +check_cmd S10 yes "plant in B data/escape: links to A's marker (abs, ../../../ns-a/...), to A's dir, FIFO, socket, device" \ + plant "$B/data/escape" "$A/home/escape" ../../../ns-a/home/escape +check_cmd S11 yes "plant in A home/escape: link-sib -> ../../sibling/secret.txt (another home, same namespace)" \ + bash -c "ln -s ../../sibling/secret.txt '$A/home/escape/link-sib' && chown -h $UID_USER:$UID_USER '$A/home/escape/link-sib'" +check_cmd S12 yes "the links resolve on this host (as they did on leil-rig)" \ + bash -c "holds() { [ \"\$(cat \"\$1\")\" = \"\$2\" ]; }; holds '$A/home/escape/link-abs' '$MARK_B' && holds '$A/home/escape/link-rel' '$MARK_B' && holds '$B/data/escape/link-abs' '$MARK_A' && holds '$B/data/escape/link-rel' '$MARK_A' && holds '$A/home/escape/link-sib' '$MARK_SIB'" + +echo "--- reads: a link, FIFO, socket or device is no object (404), at the end of the key or on its way" +n=0 +for gw in A B; do + bk=$([ "$gw" = A ] && echo home || echo data) + for key in link-abs link-rel link-dir/marker.txt link-dir/ fifo sock dev $([ "$gw" = A ] && echo link-sib); do + n=$((n + 1)) + check R$n 404 "$gw GetObject $bk/escape/$key" "$gw" ns-user GET "/$bk/escape/$key" -o "$W/tmp/body" + n=$((n + 1)) + check R$n 404 "$gw HeadObject $bk/escape/$key" "$gw" ns-user HEAD "/$bk/escape/$key" + done +done +check R50 404 "A GetObjectTagging home/escape/link-abs" A ns-user GET /home/escape/link-abs tagging +check R51 404 "A GetObjectAttributes home/escape/link-rel" A ns-user GET /home/escape/link-rel attributes -H "x-amz-object-attributes: ETag,ObjectSize" +check R52 404 "A CopyObject from home/escape/link-abs" A ns-user PUT /home/copied.txt -H "x-amz-copy-source: /home/escape/link-abs" +check R53 404 "A CopyObject from home/escape/link-dir/marker.txt" A ns-user PUT /home/copied.txt -H "x-amz-copy-source: /home/escape/link-dir/marker.txt" +check R54 404 "A CopyObject from home/escape/fifo" A ns-user PUT /home/copied.txt -H "x-amz-copy-source: /home/escape/fifo" +check R55 200 "A GetObject home/escape/marker.txt (its own object still reads)" A ns-user GET /home/escape/marker.txt -o "$W/tmp/body" +check_cmd R56 yes " ...and holds A's marker" holds "$W/tmp/body" "$MARK_A" + +echo "--- listings skip them and never enter them" +listed() { # listed -- the keys and common prefixes, one per line + req "$1" ns-user GET "/$2" "$3" -o "$W/tmp/list.xml" >/dev/null + python3 -c 'import re,sys; d=open(sys.argv[1]).read(); print("\n".join(re.findall(r"<(?:Key|Prefix)>([^<]*)", d)))' "$W/tmp/list.xml" +} +expect_listed() { # expect_listed + local got + got=$(listed "$4" "$5" "$6" | grep -v '^$' | grep -vx "$(sed -n 's/.*prefix=\([^&]*\).*/\1/p' <<<"$6")" | sort | tr '\n' ' ') + if [ "$got" = "$3" ]; then ok "$1" "[$got]" "$2"; else bad "$1" "[$got]" "[$3]" "$2" "$(head -c 300 "$W/tmp/list.xml")"; fi +} +expect_listed L1 "A ListObjectsV2 home prefix escape/: its marker alone" "escape/marker.txt " A home "list-type=2&prefix=escape/" +expect_listed L2 "B ListObjectsV2 data prefix escape/: its marker alone" "escape/marker.txt " B data "list-type=2&prefix=escape/" +expect_listed L3 "A ListObjectsV2 home prefix escape/link-dir/: nothing" "" A home "list-type=2&prefix=escape/link-dir/" +expect_listed L4 "B ListObjects (v1) data prefix escape/link-dir/: nothing" "" B data "prefix=escape/link-dir/" +expect_listed L5 "A ListObjectsV2 home delimiter /, prefix escape/: no link-dir/ prefix" "escape/marker.txt " A home "list-type=2&prefix=escape/&delimiter=/" +expect_listed L6 "A ListObjectVersions home prefix escape/" "escape/marker.txt " A home "versions&prefix=escape/" + +echo "--- writes act on the entry's own name, never through it" +printf 'written by ns-user\n' >"$W/tmp/new" +check W1 200 "A PutObject home/escape/link-abs (over the link)" A ns-user PUT /home/escape/link-abs --body "$W/tmp/new" +check_cmd W2 yes " ...the link is now that object, a file of uid $UID_USER" \ + bash -c "[ -f '$A/home/escape/link-abs' ] && [ ! -L '$A/home/escape/link-abs' ] && [ \$(stat -c %u '$A/home/escape/link-abs') = $UID_USER ]" +check W3 200 "B PutObject data/escape/fifo (over the FIFO)" B ns-user PUT /data/escape/fifo --body "$W/tmp/new" +check_cmd W4 yes " ...now a regular file" is_file "$B/data/escape/fifo" +check W5 200 "A CopyObject home/escape/marker.txt to home/escape/link-rel" A ns-user PUT /home/escape/link-rel -H "x-amz-copy-source: /home/escape/marker.txt" +check_cmd W6 yes " ...link-rel is now a copy of A's marker" bash -c "[ ! -L '$A/home/escape/link-rel' ] && [ \"\$(cat '$A/home/escape/link-rel')\" = '$MARK_A' ]" +check W7 409 "A PutObject home/escape/link-dir/new.txt (under the link)" A ns-user PUT /home/escape/link-dir/new.txt --body "$W/tmp/new" +check W8 409 "B PutObject data/escape/link-dir/new.txt (under the link)" B ns-user PUT /data/escape/link-dir/new.txt --body "$W/tmp/new" +check W9 409 "A CopyObject to home/escape/link-dir/copy.txt" A ns-user PUT /home/escape/link-dir/copy.txt -H "x-amz-copy-source: /home/escape/marker.txt" +check W10 409 "A PutObject home/escape/sock/x (under the socket)" A ns-user PUT /home/escape/sock/x --body "$W/tmp/new" +check_cmd W11 yes " ...nothing was written in B, or in A through B's link" \ + bash -c "[ ! -e '$B/data/escape/new.txt' ] && [ ! -e '$B/data/escape/copy.txt' ] && [ ! -e '$A/home/escape/new.txt' ]" +TAGS=$W/tmp/tags.xml +printf 'kv' >"$TAGS" +check W12 404 "B PutObjectTagging data/escape/link-abs" B ns-user PUT /data/escape/link-abs tagging --body "$TAGS" +check W13 404 "A PutObjectTagging home/escape/link-dir/marker.txt" A ns-user PUT /home/escape/link-dir/marker.txt tagging --body "$TAGS" +check W14 404 "A PutObjectTagging home/escape/link-sib" A ns-user PUT /home/escape/link-sib tagging --body "$TAGS" +# a multipart upload completed over a link (B's link-dir/ has its own marker under it, so complete onto link-del's twin) +ln -s "$A/home/escape/marker.txt" "$B/data/escape/link-mp" && chown -h $UID_USER:$UID_USER "$B/data/escape/link-mp" +req B ns-user POST /data/escape/link-mp uploads -o "$W/tmp/mp.xml" >/dev/null +UPLOAD=$(sed -n 's:.*\([^<]*\).*:\1:p' "$W/tmp/mp.xml") +check W15 200 "B UploadPart data/escape/link-mp" B ns-user PUT /data/escape/link-mp "partNumber=1&uploadId=$UPLOAD" --body "$W/tmp/new" +printf '1"%s"' \ + "$(md5sum <"$W/tmp/new" | cut -d' ' -f1)" >"$W/tmp/complete.xml" +check W16 200 "B CompleteMultipartUpload data/escape/link-mp (over the link)" B ns-user POST /data/escape/link-mp "uploadId=$UPLOAD" --body "$W/tmp/complete.xml" +check_cmd W17 yes " ...link-mp is now that object" bash -c "[ ! -L '$B/data/escape/link-mp' ] && [ \"\$(cat '$B/data/escape/link-mp')\" = 'written by ns-user' ]" + +echo "--- deletes remove the entry itself, never what a link points to" +check D1 204 "A DeleteObject home/escape/link-del" A ns-user DELETE /home/escape/link-del +check_cmd D2 yes " ...the link is gone, B's marker is not" bash -c "[ ! -L '$A/home/escape/link-del' ] && [ -f '$B/data/escape/marker.txt' ]" +check D3 204 "B DeleteObject data/escape/link-dir/marker.txt (under the link)" B ns-user DELETE /data/escape/link-dir/marker.txt +check_cmd D4 yes " ...A's marker is still there, and the link" bash -c "[ -f '$A/home/escape/marker.txt' ] && [ -L '$B/data/escape/link-dir' ]" +check D5 204 "A DeleteObject home/escape/sock" A ns-user DELETE /home/escape/sock +check D6 204 "A DeleteObject home/escape/dev" A ns-user DELETE /home/escape/dev +check_cmd D7 yes " ...both gone" bash -c "[ ! -e '$A/home/escape/sock' ] && [ ! -e '$A/home/escape/dev' ]" +DEL=$W/tmp/delete.xml +printf 'escape/link-delescape/link-dir/marker.txt' >"$DEL" +check D8 200 "B DeleteObjects data: escape/link-del, escape/link-dir/marker.txt" B ns-user POST /data delete --body "$DEL" +check_cmd D9 yes " ...B's link-del is gone, A's marker is not" bash -c "[ ! -L '$B/data/escape/link-del' ] && [ -f '$A/home/escape/marker.txt' ]" + +echo "--- a directory swapped for a link while requests run" +check X0 200 "A ns-user PutObject home/race/obj.txt" A ns-user PUT /home/race/obj.txt --body "$W/tmp/mark-a" +mkdir -p "$B/data/racedir" && printf '%s' "$MARK_B" >"$B/data/racedir/obj.txt" && printf '%s' "$MARK_B" >"$B/data/racedir/victim.txt" && + ln -s "$B/data/racedir" "$A/home/race-alt" +check_cmd X1 yes "3 s of GET, PUT and DELETE under home/race/ while it swaps with a link to B's directory" \ + env S3_ENDPOINT=http://127.0.0.1:$PORT_A S3_KEY=ns-user S3_SECRET="${SECRET[ns-user]}" S3REQ="$S3REQ" \ + python3 "$HERE/race.py" "$A/home/race" "$A/home/race-alt" home race "$MARK_A" "$MARK_B" 3 +sed 's/^/ /' "$W/tmp/err" +check_cmd X2 yes " ...B's directory holds only what it held" \ + bash -c "[ \"\$(ls -A '$B/data/racedir' | sort | tr '\n' ' ')\" = 'obj.txt victim.txt ' ] && [ -z \"\$(getfattr --absolute-names -d -m '^user\.' '$B/data/racedir/obj.txt' 2>/dev/null)\" ]" + +echo "--- the other namespace is as it was" +check_cmd Z1 yes "A's marker, B's marker and the sibling's marker unchanged, and no attributes set on them" markers_intact +check_cmd Z2 yes "the gateways logged no panic" bash -c "! grep -qi panic '$W'/gateway-*.log" + +echo +echo "$PASS passed, $FAIL failed" +[ "$FAIL" = 0 ] diff --git a/tests/no-symlinks/race.py b/tests/no-symlinks/race.py new file mode 100644 index 0000000..495fd9e --- /dev/null +++ b/tests/no-symlinks/race.py @@ -0,0 +1,98 @@ +#!/usr/bin/env python3 +"""Swap a bucket directory with a link while requests run under it. + + S3_ENDPOINT=... S3_KEY=... S3_SECRET=... S3REQ=.../s3req.py \\ + race.py + + is the directory of // on disk, holding obj.txt with the +text . is a link beside it to a directory outside the +namespace, holding obj.txt and victim.txt with the text . For + one thread exchanges the two names (renameat2 RENAME_EXCHANGE) as +fast as it can while this one sends, in turn, GET /obj.txt, PUT +/new-.txt and DELETE /victim.txt. Exits 1 if a GET served +. What reached the other directory, the caller checks on disk. +Python standard library only. +""" + +import ctypes +import http.client +import importlib.util +import os +import sys +import threading +import time +import urllib.parse + +AT_FDCWD = -100 +RENAME_EXCHANGE = 2 + + +def main(argv): + if len(argv) != 7: + sys.exit(__doc__) + d, link, bucket, prefix, inside, outside, seconds = argv + spec = importlib.util.spec_from_file_location("s3req", os.environ["S3REQ"]) + s3req = importlib.util.module_from_spec(spec) + spec.loader.exec_module(s3req) + + libc = ctypes.CDLL(None, use_errno=True) + renameat2 = libc.renameat2 + stop = threading.Event() + swaps = [0] + + def swapper(): + a, b = d.encode(), link.encode() + while not stop.is_set(): + if renameat2(AT_FDCWD, a, AT_FDCWD, b, RENAME_EXCHANGE) != 0: + print("swap failed:", os.strerror(ctypes.get_errno())) + stop.set() + return + swaps[0] += 1 + + endpoint = urllib.parse.urlsplit(os.environ["S3_ENDPOINT"]) + key, secret = os.environ["S3_KEY"], os.environ["S3_SECRET"] + region = os.environ.get("S3_REGION", "us-east-1") + + def request(method, path, body=b""): + headers = {} + s3req.sign(method, endpoint.netloc, path, "", headers, body, key, secret, region) + conn = http.client.HTTPConnection(endpoint.hostname, endpoint.port, timeout=20) + conn.request(method, s3req.quote(path, safe="/"), body=body or None, headers=headers) + resp = conn.getresponse() + data = resp.read() + conn.close() + return resp.status, data + + t = threading.Thread(target=swapper) + t.start() + counts = {} + leaks = 0 + n = 0 + deadline = time.monotonic() + float(seconds) + try: + while time.monotonic() < deadline and not stop.is_set(): + status, data = request("GET", f"/{bucket}/{prefix}/obj.txt") + counts[f"GET {status}"] = counts.get(f"GET {status}", 0) + 1 + if status == 200 and data.decode(errors="replace") != inside: + leaks += 1 + if leaks <= 3: + print("GET served:", data[:80]) + status, _ = request("PUT", f"/{bucket}/{prefix}/new-{n % 20}.txt", inside.encode()) + counts[f"PUT {status}"] = counts.get(f"PUT {status}", 0) + 1 + status, _ = request("DELETE", f"/{bucket}/{prefix}/victim.txt") + counts[f"DELETE {status}"] = counts.get(f"DELETE {status}", 0) + 1 + n += 1 + finally: + stop.set() + t.join() + # leave the directory where it started + if os.path.islink(d): + renameat2(AT_FDCWD, d.encode(), AT_FDCWD, link.encode(), RENAME_EXCHANGE) + print(f"{swaps[0]} swaps, {n} rounds:", ", ".join(f"{k} x{v}" for k, v in sorted(counts.items()))) + if leaks: + print(f"{leaks} GETs served the other side") + sys.exit(1) + + +if __name__ == "__main__": + main(sys.argv[1:]) diff --git a/tests/no-symlinks/rig-replay.sh b/tests/no-symlinks/rig-replay.sh new file mode 100644 index 0000000..e31a66d --- /dev/null +++ b/tests/no-symlinks/rig-replay.sh @@ -0,0 +1,174 @@ +#!/bin/bash +# +# Stage 2 of the proof for patches/v1.11.0/0005-posix-no-symlinks.patch: Norn's M5 stage 13 +# escape layout, replayed on leil-rig's installed gateways. +# +# sudo bash rig-replay.sh [BENCH_COUNT] +# +# Runs as root on the first gateway host (leil-mst-1), which mounts /srv/leilfs/0x0 (home +# namespace) and /srv/leilfs/0x1 (bucket namespace) and serves versitygw@0x0 and versitygw@0x1; +# is the other gateway host's, whose instances it reaches over the rig network. Each +# namespace's root keys are read from /etc/versitygw.d/.conf inside the admin calls and +# never printed. +# +# A throwaway account (, leil-cluster's reserved test band) gets a home nf-home- +# in 0x0 and a bucket nf-data- in 0x1, each with escape/marker.txt. As root, owned by the +# UID, it plants in each a link to the other's marker (absolute, and relative ../../..//...), +# a link to the other's escape directory, a FIFO and a socket, waits out the mounts' cache, and +# drives the S3 calls at them through all four instances. Everything it made is removed at exit, +# through the mounts, with the account. BENCH_COUNT (default 0) also times that many PUT, GET, +# HEAD and DELETE calls and ten listings through the local 0x0 instance, on LeilFS. + +set -uo pipefail + +PEER=${1:?usage: rig-replay.sh [bench count]} +TUID=${2:?test UID} +CACHE=${3:?mount cache seconds} +BENCH=${4:-0} +HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +S3REQ=$HERE/s3req.py +[ "$(id -u)" = 0 ] || { echo "FATAL: run as root" >&2; exit 2; } +[ -f "$S3REQ" ] || { echo "FATAL: $S3REQ is missing (copy tests/owner-scope/s3req.py beside this)" >&2; exit 2; } + +conf() { echo "/etc/versitygw.d/$1.conf"; } +cval() { (set -a; . "$(conf "$1")"; eval "printf '%s' \"\${$2}\""); } # cval , not for secrets +declare -A S3PORT ADMPORT MNT +for ns in 0x0 0x1; do + [ -r "$(conf $ns)" ] || { echo "FATAL: no $(conf $ns)" >&2; exit 2; } + S3PORT[$ns]=$(cval $ns VGW_PORT | tr -d :) ADMPORT[$ns]=$(cval $ns VGW_ADMIN_PORT | tr -d :) MNT[$ns]=$(cval $ns VGW_BACKEND_ARG) + mountpoint -q "${MNT[$ns]}" || { echo "FATAL: ${MNT[$ns]} is not mounted" >&2; exit 2; } +done +STAMP=$(date +%s) +AK=nofollow-$STAMP +SK=$(head -c 24 /dev/urandom | base64 | tr '+/' 'AB' | tr -d '=\n') +HOMEB=nf-home-$STAMP DATAB=nf-data-$STAMP +declare -A BK=([0x0]=$HOMEB [0x1]=$DATAB) +W=$(mktemp -d /var/tmp/s3gw-nf-replay.XXXXXX) +chmod 700 "$W" + +# admin -- signed with this host's root keys for , read here +admin() { + local ns=$1; shift + (set -a; . "$(conf "$ns")"; ADMIN_ACCESS_KEY_ID=$ROOT_ACCESS_KEY_ID ADMIN_SECRET_ACCESS_KEY=$ROOT_SECRET_ACCESS_KEY \ + exec versitygw admin --region "$ns" --endpoint-url "http://127.0.0.1:${ADMPORT[$ns]}" "$@") +} +# req -- one request as the throwaway account; prints the status +req() { + local ns=$1 where=$2 ip=127.0.0.1; shift 2 + [ "$where" = peer ] && ip=$PEER + S3_ENDPOINT=http://$ip:${S3PORT[$ns]} S3_REGION=$ns S3_KEY=$AK S3_SECRET=$SK \ + timeout 20 python3 -I "$S3REQ" "$@" 2>"$W/err" || [ -s "$W/err" ] || echo "no answer in 20 s" >"$W/err" +} + +# mkbucket -- the account's bucket in , made as leil-cluster's leilfs-user makes one +mkbucket() { + admin "$1" create-bucket --owner "$AK" --bucket "${BK[$1]}" --object-ownership BucketOwnerPreferred \ + --create-bucket-configuration "LocationConstraint=$1" && + chown "$TUID:$TUID" "${MNT[$1]}/${BK[$1]}" && chmod 0700 "${MNT[$1]}/${BK[$1]}" +} + +MADE=0 +cleanup() { + if [ "$MADE" = 1 ]; then + for ns in 0x0 0x1; do + rm -rf "${MNT[$ns]}/${BK[$ns]}" "${MNT[$ns]}/.vgwlocks/$(printf %s "${BK[$ns]}" | sha256sum | cut -c1-64)" + admin "$ns" delete-user --access "$AK" >/dev/null 2>&1 || echo "WARN: could not delete $AK in $ns" >&2 + done + echo "removed $AK, ${MNT[0x0]}/$HOMEB and ${MNT[0x1]}/$DATAB" + fi + rm -rf "$W" +} +trap cleanup EXIT + +PASS=0 FAIL=0 +ok() { PASS=$((PASS + 1)); printf 'PASS %-4s %s %s\n' "$1" "$2" "$3"; } +bad() { FAIL=$((FAIL + 1)); printf 'FAIL %-4s %s (want %s) %s [%s]\n' "$1" "${2:-none}" "$3" "$4" "$5"; } +check() { # check + local id=$1 want=$2 what=$3 got; shift 3 + got=$(req "$@") + if [ "$got" = "$want" ]; then ok "$id" "$got" "$what"; else bad "$id" "$got" "$want" "$what" "$(tr '\n' ' ' <"$W/err")"; fi +} +check_cmd() { # check_cmd + local id=$1 want=$2 what=$3 got=yes; shift 3 + "$@" >"$W/err" 2>&1 || got=no + if [ "$got" = "$want" ]; then ok "$id" "$got" "$what"; else bad "$id" "$got" "$want" "$what" "$(tr '\n' ' ' <"$W/err")"; fi +} + +echo "versitygw $(sha256sum /usr/bin/versitygw | cut -c1-12) here; 0x0 S3 :${S3PORT[0x0]}, 0x1 S3 :${S3PORT[0x1]}; peer $PEER; account $AK (uid $TUID)" +echo "--- setup" +for ns in 0x0 0x1; do + check_cmd S1$ns yes "$ns create-user $AK" admin $ns create-user --access "$AK" --secret "$SK" --role user --user-id "$TUID" --group-id "$TUID" + MADE=1 + check_cmd S2$ns yes "$ns create-bucket ${BK[$ns]} --owner $AK, then $TUID:$TUID 0700 as leilfs-user" mkbucket $ns + printf '%s marker' "$ns" >"$W/mark-$ns" + check S3$ns 200 "$ns PutObject ${BK[$ns]}/escape/marker.txt" $ns local PUT "/${BK[$ns]}/escape/marker.txt" --body "$W/mark-$ns" +done +H=${MNT[0x0]}/$HOMEB/escape D=${MNT[0x1]}/$DATAB/escape +plant() { # plant + ln -s "$2/marker.txt" "$1/link-abs" && ln -s "$3/marker.txt" "$1/link-rel" && ln -s "$2" "$1/link-dir" && + ln -s "$2/marker.txt" "$1/link-del" && mkfifo "$1/fifo" && + python3 -c 'import socket,sys; socket.socket(socket.AF_UNIX).bind(sys.argv[1])' "$1/sock" && + chown -h "$TUID:$TUID" "$1"/link-* "$1/fifo" "$1/sock" +} +check_cmd S4 yes "plant in /0x0/$HOMEB/escape: links to 0x1's marker (abs, ../../../0x1/...), to its dir, FIFO, socket" \ + plant "$H" "$D" "../../../0x1/$DATAB/escape" +check_cmd S5 yes "plant in /0x1/$DATAB/escape: links to 0x0's marker (abs, ../../../0x0/...), to its dir, FIFO, socket" \ + plant "$D" "$H" "../../../0x0/$HOMEB/escape" +check_cmd S6 yes "the links resolve on this host" \ + bash -c "[ \"\$(cat '$H/link-abs')\" = '0x1 marker' ] && [ \"\$(cat '$H/link-rel')\" = '0x1 marker' ] && [ \"\$(cat '$D/link-abs')\" = '0x0 marker' ] && [ \"\$(cat '$D/link-rel')\" = '0x0 marker' ]" +sleep $((CACHE + 1)) # the peer's mounts see the planted entries + +echo "--- reads through all four instances: 404" +n=0 +for ns in 0x0 0x1; do + for where in local peer; do + for key in link-abs link-rel link-dir/marker.txt fifo sock; do + n=$((n + 1)); check R$n 404 "$ns $where GetObject ${BK[$ns]}/escape/$key" $ns $where GET "/${BK[$ns]}/escape/$key" -o "$W/body" + n=$((n + 1)); check R$n 404 "$ns $where HeadObject ${BK[$ns]}/escape/$key" $ns $where HEAD "/${BK[$ns]}/escape/$key" + done + n=$((n + 1)); check R$n 404 "$ns $where CopyObject from ${BK[$ns]}/escape/link-abs" $ns $where PUT "/${BK[$ns]}/copied-$where" -H "x-amz-copy-source: /${BK[$ns]}/escape/link-abs" + done +done + +echo "--- listings through all four instances: the marker alone" +n=0 +for ns in 0x0 0x1; do + for where in local peer; do + for prefix in escape/ escape/link-dir/; do + req $ns $where GET "/${BK[$ns]}" "list-type=2&prefix=$prefix" -o "$W/list.xml" >/dev/null + got=$(python3 -I -c 'import re,sys; print(" ".join(re.findall(r"([^<]*)", open(sys.argv[1]).read())))' "$W/list.xml") + want=$([ "$prefix" = escape/ ] && echo escape/marker.txt) + n=$((n + 1)) + if [ "$got" = "$want" ]; then ok L$n "[$got]" "$ns $where ListObjectsV2 prefix $prefix"; else bad L$n "[$got]" "[$want]" "$ns $where ListObjectsV2 prefix $prefix" "$(head -c 200 "$W/list.xml")"; fi + done + done +done + +echo "--- writes and deletes act on the entry itself, never through it" +printf 'written by %s\n' "$AK" >"$W/new" +n=0 +for ns in 0x0 0x1; do + for where in local peer; do + n=$((n + 1)); check W$n 409 "$ns $where PutObject ${BK[$ns]}/escape/link-dir/new-$where.txt (under the link)" $ns $where PUT "/${BK[$ns]}/escape/link-dir/new-$where.txt" --body "$W/new" + n=$((n + 1)); check W$n 204 "$ns $where DeleteObject ${BK[$ns]}/escape/link-dir/marker.txt (under the link)" $ns $where DELETE "/${BK[$ns]}/escape/link-dir/marker.txt" + done +done +check_cmd W10 yes " ...both markers are still there, nothing new beside them" \ + bash -c "[ \"\$(cat '$H/marker.txt')\" = '0x0 marker' ] && [ \"\$(cat '$D/marker.txt')\" = '0x1 marker' ] && ! ls '$H' '$D' | grep -q '^new-'" +check W11 200 "0x0 peer PutObject $HOMEB/escape/link-abs (over the link)" 0x0 peer PUT "/$HOMEB/escape/link-abs" --body "$W/new" +check W12 200 "0x1 local PutObject $DATAB/escape/fifo (over the FIFO)" 0x1 local PUT "/$DATAB/escape/fifo" --body "$W/new" +check W13 204 "0x1 peer DeleteObject $DATAB/escape/link-del" 0x1 peer DELETE "/$DATAB/escape/link-del" +check W14 204 "0x0 local DeleteObject $HOMEB/escape/sock" 0x0 local DELETE "/$HOMEB/escape/sock" +sleep $((CACHE + 1)) +check_cmd W15 yes " ...link-abs and fifo are now files of uid $TUID, link-del and sock are gone, both markers intact" \ + bash -c "[ -f '$H/link-abs' ] && [ ! -L '$H/link-abs' ] && [ \$(stat -c %u '$H/link-abs') = $TUID ] && [ -f '$D/fifo' ] && [ ! -p '$D/fifo' ] && [ ! -L '$D/link-del' ] && [ ! -e '$H/sock' ] && [ \"\$(cat '$H/marker.txt')\" = '0x0 marker' ] && [ \"\$(cat '$D/marker.txt')\" = '0x1 marker' ]" + +if [ "$BENCH" -gt 0 ]; then + echo "--- timing through the local 0x0 instance, on LeilFS ($BENCH objects)" + S3_ENDPOINT=http://127.0.0.1:${S3PORT[0x0]} S3_REGION=0x0 S3_KEY=$AK S3_SECRET=$SK S3REQ=$S3REQ \ + python3 -I "$HERE/bench.py" "$HOMEB" "$BENCH" || bad B1 failed ok "bench" "" +fi + +echo +echo "$PASS passed, $FAIL failed" +[ "$FAIL" = 0 ]