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/
([^<]*)`).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