patches: add v1.11.0 no-symlinks patch and its leil-rig proof
build / build (push) Successful in 9m26s

0005-posix-no-symlinks.patch makes VersityGW's posix backend resolve every
path below its root and versioning directory from a descriptor of that
directory, opened once at start: each directory on the way with openat2
and RESOLVE_NO_SYMLINKS|RESOLVE_BENEATH (one O_NOFOLLOW open per element
where openat2 is missing), the last element acted on without following
it. Upstream followed a link anywhere on a key's way, so on a host that
mounts more than one namespace a link planted in a bucket served,
overwrote and deleted another namespace's objects (Norn M5 stage 13).

A link, FIFO, socket or device is no object: at the end of a key it
reads as missing (404) and is never opened, on the way it answers as a
file there does (404, 409 ObjectParentIsFile), listings skip it and
never enter it, and PUT, copy, complete and DELETE act on the entry
itself, never on what a link points to (owner, 2026-11-27).
--bucketlinks still follows a link at the bucket level only.

Proven on leil-rig on 2026-11-27, against a stock 0001-0004 control:
- tests/no-symlinks/proof.sh, throwaway gateways on leil-test-1:
  87/87 (control 38/87).
- tests/no-symlinks/rig-replay.sh, with the build pinned on the rig's
  four instances: 75/75 twice (control 17/75).
- rig-gateway-check.sh 20/20 in both namespaces.
- go test, every package but plugins/: 35/35.
The rig was put back on 26e5a763.

docs/no-symlinks.md has the rules, the proof and what it costs: GET
+3-9%, HEAD +8-25%, listings 2x on a local disk and within noise on
LeilFS. README.md and docs/multi-version-pipeline.md name the patch and
how to check a rebase of it.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
57_WolveandClaude Opus 5.5 committed 2026-11-27 01:50:15 -06:00
1 parent a52f92c100
commit 11d219961a
9 files changed
+4864 -13

No files matched your search

+46 -7
View File
@@ -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
+23 -6
View File
@@ -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
+186
View File
@@ -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/<dir>/<name>`. So a link swapped in while a request runs is refused too. |
| **Fallback** | Where `openat2` is missing (ENOSYS, Linux before 5.6), refused by seccomp (EPERM), or keeps answering EAGAIN, the directories are opened one element at a time with `O_PATH\|O_DIRECTORY\|O_NOFOLLOW`. The guarantee is the same; it takes one call per element. `RESOLVE_BENEATH` alone would not do: it still follows a link that stays under the root, such as one home's link into another home of the same namespace, or a link from a granted folder to an ungranted one in the same bucket. |
| **Not an object** | A symbolic link, FIFO, socket or device as the last element reads as missing: 404 `NoSuchKey`, `NoSuchVersion` with a version id. It is **never opened**: an existing file is first opened with `O_PATH`, which opens no FIFO or device, then checked, and only then opened through its descriptor. Extended attribute calls on it report it missing too. |
| **On the way** | Such an entry as a directory of the key answers as a file there does: reads 404, writes 409 `ObjectParentIsFile`. Nothing is written or removed through it. |
| **Listings** | The listings' file system holds only regular files and directories. A link is neither listed nor entered, and a prefix through one lists nothing. |
| **Writes and deletes** | PUT, a CopyObject destination and CompleteMultipartUpload replace the entry itself: the rename never follows it. A DELETE of its key with no version id and no preconditions removes the entry itself and answers 204, then goes on as for a missing object. A key with a trailing slash names a directory object, and leaves a link at that name alone. What a link points to is never touched. |
| **What is still followed** | The root and the versioning directory, which are opened as the operator named them. With `--bucketlinks` (off everywhere), a link at the bucket level, as that option promises; nothing below a bucket is followed even then. A bucket that is a link without that option is refused as before, now without the race. |
| **Shared helpers** | `backend.MkdirAll` and `backend.MoveFile` take the file system they work on (`MkdirAllFS`, `MoveFileFS`, the `FS` interface; `backend.OS` is the os package's). The posix backend then makes parent directories and moves temporary files through `rootFS`. The xattr metadata storer passed to `posix.New` is wrapped to resolve through `rootFS`. |
A link met on the way, or an entry that is no object, is logged at debug level (`--debug`), with its path.
### What it does not change
- **The sidecar storer** (`--sidecar`) and **ScoutFS's own calls** are as upstream has them. Neither is deployed. The
sidecar directory is outside every namespace mount, and the posix half of the ScoutFS backend is covered.
- **Windows**: `rootFS` is the os package's there, as upstream has it.
- **darwin and FreeBSD** use the element-by-element walk, since they have no `openat2`. With no `O_PATH` either, an
existing file is opened with `O_NONBLOCK` and then checked, so a FIFO is opened for that moment, though never read and
never waited on.
- **Linux needs `/proc`**: `posix.New` refuses to start without `/proc/self/fd`. Upstream's `O_TMPFILE` path already
needed it.
- A **bucket that holds only a link** answers `BucketNotEmpty` to DeleteBucket while its listing is empty. Remove the
link on the host (Norn's agents already skip links), or DELETE its key by name.
### What it costs
Each call on a path opens the directory of its last element and closes it again, a few more system calls than before.
They are mostly lookups the kernel serves from its caches. Measured with
[`tests/no-symlinks/bench.sh`](../tests/no-symlinks/bench.sh) on leil-test-1 (local xfs, one throwaway gateway,
1 KiB objects four directories deep). On LeilFS it was measured through the rig's own instances
(`rig-replay.sh … 300`). Medians, patched vs stock; xfs over three runs each, LeilFS over two patched runs and one stock run:
| Call | xfs: stock | xfs: patched | LeilFS: stock | LeilFS: patched |
|---|---|---|---|---|
| PUT | 3.0–3.1 ms | 3.0–3.3 ms | 23.2 ms | 22.5–22.8 ms |
| GET | 2.3–2.4 ms | 2.5–2.6 ms | 15.9 ms | 16.3–16.4 ms |
| HEAD | 2.2–2.4 ms | 2.7–2.8 ms | 12.1 ms | 13.1 ms |
| LIST (a 500-key page on xfs, 300 on LeilFS) | 51–52 ms | 103–105 ms | 598 ms | 584–616 ms |
| DELETE | 2.0 ms | 2.2 ms | 6.9 ms | 6.6–7.3 ms |
| system calls in the gateway per GET / HEAD (strace) | 102–104 / 85–88 | 124–126 / 150–153 | | |
On LeilFS, where the FUSE round trips dominate, the difference is within the noise except HEAD (+8%). On a local disk,
listings take twice as long. They resolve each entry's directory again for its stat and its three attribute reads, so
reading those relative to the listed directory is the place to win it back if it ever matters. HEAD makes 14
path-based attribute reads.
## Proving the patch is in (on leil-rig)
`--version` reads `1.11.0` with or without the patch, so the proof is behaviour. Two stages, both under the lease:
```bash
RIG_LEASE_WHO="<you>: s3-gateway 0005 proof" ./bin/rig-lease.sh claim --why "s3-gateway 0005 proof" --minutes 120
VGW_SRC_DIR=build-src VGW_TAG=v1.11.0 bash ci/run.sh
```
### Stage 1: throwaway gateways on leil-test-1
[`tests/no-symlinks/proof.sh`](../tests/no-symlinks/proof.sh) runs as root. It starts two gateways from the given
binary: A on `127.0.0.1:7393` and B on `:7394`. Each is on posix, rooted at its own namespace directory under
`/var/tmp/s3gw-no-symlinks`, with its own internal IAM, `--chuid --chgid --dir-perms 0700` as the rig's gateways run.
It replays Norn's stage 13 layout with two accounts on the reserved test band: `ns-user` (UID 74990) owns `home` on A
and `data` on B, and `ns-other` (74991) owns `sibling` on A. As root, owned by the UID, it plants in A's
`home/escape/` and B's `data/escape/`:
- links to the other namespace's marker, absolute and relative (`../../../ns-b/…`);
- a link to the other side's directory;
- a FIFO, a socket and a device;
- in A, a link to `sibling`'s object, another home of the same namespace.
It removes everything at exit; `KEEP=1` keeps it.
```bash
cd ../leil-rig && source bin/rig-lib.sh
on leil-test-1 'install -d -o leil -g leil /var/tmp/s3gw-0005'
rig_scp ../s3-gateway/build-src/dist/versitygw_linux_amd64_v1/versitygw leil-test-1 /var/tmp/s3gw-0005/versitygw
tar -czf /tmp/no-symlinks.tgz -C ../s3-gateway/tests owner-scope no-symlinks
rig_scp /tmp/no-symlinks.tgz leil-test-1 /var/tmp/s3gw-0005/no-symlinks.tgz
on leil-test-1 'cd /var/tmp/s3gw-0005 && chmod 0755 versitygw && tar -xzf no-symlinks.tgz && bash no-symlinks/proof.sh $PWD/versitygw'
```
| Checks | Shows |
|---|---|
| S1–S12 | the accounts, buckets and markers; the entries planted; the links resolve on the host |
| R1–R30 | GET and HEAD of every link, the FIFO, the socket and the device, at the end of the key and through the directory link, on both gateways: 404, each within 20 s |
| R50–R56 | GetObjectTagging, GetObjectAttributes and CopyObject from a link: 404; the bucket's own object still reads |
| L1–L6 | ListObjectsV2, ListObjects and ListObjectVersions, with and without a delimiter: only the marker; a prefix through the link: nothing |
| W1–W17 | PUT, CopyObject and CompleteMultipartUpload replace a link or FIFO with a file of the user's UID; PUT and CopyObject under a link or socket: 409, nothing written on the other side; PutObjectTagging of a link: 404 |
| D1–D9 | DELETE and DeleteObjects remove the link, socket and device themselves, and remove nothing through the directory link |
| X0–X2 | `race.py`: for 3 s a directory of the bucket and a link to the other namespace's directory swap names (`renameat2` `RENAME_EXCHANGE`) as fast as they can, while GET, PUT and DELETE run under it. No GET serves the other side, and its directory holds only what it held. |
| Z1–Z2 | the markers and their attributes are unchanged; no gateway panicked |
### Stage 2: the rig's installed gateways, on LeilFS
Pin the build on the rig's four instances through a git-ignored `versitygw.auto.tfvars` with the build's three
`versitygw_*` pins, and run `bin/rig-versitygw.sh --rpm <rpm>`. Then `bin/rig-gateway-check.sh`, and
[`tests/no-symlinks/rig-replay.sh`](../tests/no-symlinks/rig-replay.sh) as root on leil-mst-1, with `s3req.py` and
`bench.py` beside it. Its arguments are the peer's IP, a UID from the test band and the mount cache time:
```bash
on leil-mst-1 'bash /var/tmp/s3gw-nf-tools/rig-replay.sh 192.168.100.43 74995 5 300'
```
It makes a throwaway account in `0x0` and `0x1`, a home `nf-home-<stamp>` and a bucket `nf-data-<stamp>`. Each root
key is read from `/etc/versitygw.d/<ns>.conf` only inside the admin calls, and never printed. It plants Norn's links
across the two mounts (`../../../0x1/…` and back), a directory link, a FIFO and a socket, waits out the mount cache,
and drives GET, HEAD, CopyObject, listings, PUT and DELETE at them through all four instances. It then removes
everything through the mounts, with the account. The fourth argument also times that many calls on LeilFS. Then remove
`versitygw.auto.tfvars`, run `bin/rig-versitygw.sh`, `bin/rig-gateway-check.sh` and `bin/rig-status.sh`, and release
the lease.
### Result on leil-rig, 2026-11-27: **PASSED**
Run under the lease. leil-test-1 and the gateway hosts run AlmaLinux 9.8 with kernel 5.14.0-687.53.1; the rig has
LeilFS `274875f2`, OpenBao 2.6.2 and Vault IAM:
| | |
|---|---|
| Build | `VGW_TAG=v1.11.0 bash ci/run.sh` (fresh clone of `v1.11.0`, 0001–0005 by `git am --3way`, GoReleaser, go1.27.3); `--version` 1.11.0, `Build` `a4152e88` |
| `versitygw` (linux amd64) sha256 | `7213faedd150294b2890d986392b20ff5b6e5d24dfa317cc956913451e9ab7a9` |
| `versitygw_1.11.0_linux_amd64.rpm` sha256 | `1148ed7a8f079b2da60530a9b139a7cacd82cffc5349a4c293cf16510d63990a` (built locally; not published, not pinned) |
| Unit tests on leil-test-1 (go1.27.3 linux/amd64) | the new tests: ok, as `leil` and as root, with `openat2` and with the walk, with relative and absolute paths, and with `-race`. The swap test made about 120 000 swaps a run, and every GET that answered served the bucket's own data. Every package but `plugins/`: 35 of 35 ok. |
| `proof.sh` (stage 1) | **87 passed, 0 failed**. Race: 53 344 swaps, 258 rounds; GET 200 ×42 (own data), 404 ×216; PUT 200 ×175, 409 ×82, 500 ×1; the other side untouched. |
| `rig-replay.sh` (stage 2), patched build pinned | **75 passed, 0 failed**, twice: 44 reads through the four instances answered 404, the listings showed the marker alone, and the writes and deletes acted on the entry itself. `rig-gateway-check.sh` passed 0x0 20/20 and 0x1 20/20. |
**Control: stock 0001–0004.** Same scripts. On leil-test-1 the control was built by `ci/run.sh` from the same
repository state, with `PATCH_DIR` holding 0001–0004 (binary `c522187e…`). On the rig it was the pinned release
`26e5a763…`.
- `proof.sh`: **38 passed, 49 failed**.
- Every link GET and HEAD answered 200 with the other namespace's marker, and so did the other home's.
- The FIFO GET and the copy from it did not answer in 20 s. The socket GET answered 500, and the device GET 200.
- The listings showed every planted entry, and the prefix through the link listed the other side.
- PUT and CopyObject under the link answered 200, written in the other namespace.
- DELETE under it removed the other namespace's marker.
- Tagging went through to the target.
- In the race, 165 GETs served the other side.
- `rig-replay.sh`: **17 passed, 58 failed**, Norn's finding on all four instances and more:
- all 44 reads were served;
- the FIFO GETs did not answer;
- the listings entered the link;
- PUT under the link wrote into the other namespace;
- DELETE under the link removed 0x0's marker.
The rig was put back after the trial. Every node runs `26e5a763ab3f` again; `rig-gateway-check.sh` passed 20/20 in both
namespaces, and `rig-status.sh` reads as before. Under a swap race as fast as `race.py`'s, a PUT can answer 500 rather
than 409, as one did in one of two runs; nothing is written through the link.
Run this test again before pinning any build that carries 0005, in leil-rig or leil-cluster.
File diff suppressed because it is too large. Load diff
+67
View File
@@ -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 <bucket> <count>
PUTs <count> 1 KiB objects at bench/a/b/c/obj-<n> (four directories deep), then
GETs and HEADs each, then lists the prefix 10 times (ListObjectsV2, 1000 keys a
page), then DELETEs them. Prints the median and the 90th percentile of each
call in milliseconds, one line per call. One connection per request, as
s3req.py makes them. Python standard library only.
"""
import http.client
import importlib.util
import os
import statistics
import sys
import time
import urllib.parse
def main(argv):
if len(argv) != 2:
sys.exit(__doc__)
bucket, count = argv[0], int(argv[1])
spec = importlib.util.spec_from_file_location("s3req", os.environ["S3REQ"])
s3req = importlib.util.module_from_spec(spec)
spec.loader.exec_module(s3req)
endpoint = urllib.parse.urlsplit(os.environ["S3_ENDPOINT"])
key, secret = os.environ["S3_KEY"], os.environ["S3_SECRET"]
region = os.environ.get("S3_REGION", "us-east-1")
def request(method, path, query="", body=b""):
headers = {}
s3req.sign(method, endpoint.netloc, path, query, headers, body, key, secret, region)
conn = http.client.HTTPConnection(endpoint.hostname, endpoint.port, timeout=30)
target = s3req.quote(path, safe="/") + ("?" + query if query else "")
t0 = time.perf_counter()
conn.request(method, target, body=body or None, headers=headers)
resp = conn.getresponse()
resp.read()
dt = (time.perf_counter() - t0) * 1000
conn.close()
if resp.status >= 300:
sys.exit(f"{method} {path}?{query}: {resp.status}")
return dt
body = os.urandom(1024)
keys = [f"/{bucket}/bench/a/b/c/obj-{n:05d}" for n in range(count)]
times = {}
for name, fn in [
("PUT", lambda k: request("PUT", k, body=body)),
("GET", lambda k: request("GET", k)),
("HEAD", lambda k: request("HEAD", k)),
]:
times[name] = [fn(k) for k in keys]
times["LIST"] = [request("GET", f"/{bucket}", f"list-type=2&max-keys=1000&prefix=bench/") for _ in range(10)]
times["DELETE"] = [request("DELETE", k) for k in keys]
for name, ts in times.items():
ts = sorted(ts)
p90 = ts[min(len(ts) - 1, int(len(ts) * 0.9))]
print(f"{name:6} n={len(ts):5} median {statistics.median(ts):7.2f} ms p90 {p90:7.2f} ms")
if __name__ == "__main__":
main(sys.argv[1:])
+56
View File
@@ -0,0 +1,56 @@
#!/bin/bash
#
# What 0005's resolution costs: one throwaway gateway from the given binary on
# 127.0.0.1:${BENCH_PORT:-7395}, posix on ${BENCH_DIR:-/var/tmp/s3gw-nf-bench}, internal IAM.
#
# sudo bash bench.sh /path/to/versitygw [count]
#
# Times <count> (default 500) PUT, GET, HEAD and DELETE calls of 1 KiB objects
# four directories deep, and ten listings of them (bench.py), then counts the
# gateway's system calls (strace -f -c) for 100 GETs and 100 HEADs of one of
# them. Run it with the patched build and with a stock one on the same node, one
# after the other. Nothing installed is touched; the directory is removed at
# exit.
set -uo pipefail
VGW=${1:?usage: bench.sh /path/to/versitygw [count]}
COUNT=${2:-500}
HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
export S3REQ=${S3REQ:-$HERE/../owner-scope/s3req.py}
PORT=${BENCH_PORT:-7395}
W=${BENCH_DIR:-/var/tmp/s3gw-nf-bench}
export S3_ENDPOINT=http://127.0.0.1:$PORT S3_REGION=us-east-1
[ -x "$VGW" ] || { echo "FATAL: $VGW is not an executable" >&2; exit 2; }
rm -rf "$W" && mkdir -p "$W/iam" "$W/data" || exit 2
RK=benchroot RS=$(python3 -c 'import secrets; print(secrets.token_hex(16))')
export S3_KEY=bench S3_SECRET=$(python3 -c 'import secrets; print(secrets.token_hex(16))')
"$VGW" --access "$RK" --secret "$RS" --region "$S3_REGION" --port "127.0.0.1:$PORT" --iam-dir "$W/iam" \
posix "$W/data" >"$W/gateway.log" 2>&1 &
GW=$!
trap 'kill $GW 2>/dev/null; wait $GW 2>/dev/null; rm -rf "$W"' EXIT
for _ in $(seq 1 50); do (exec 3<>"/dev/tcp/127.0.0.1/$PORT") 2>/dev/null && break; sleep 0.2; done
admin() { ADMIN_ACCESS_KEY_ID=$RK ADMIN_SECRET_ACCESS_KEY=$RS "$VGW" admin --region "$S3_REGION" --endpoint-url "$S3_ENDPOINT" "$@"; }
admin create-user --access "$S3_KEY" --secret "$S3_SECRET" --role user --user-id 74990 --group-id 74990 >/dev/null &&
admin create-bucket --owner "$S3_KEY" --bucket bench >/dev/null || { echo "FATAL: setup failed" >&2; exit 2; }
echo "versitygw sha256 $(sha256sum "$VGW" | cut -c1-16), $(uname -r), $(df -T "$W" | awk 'NR==2 {print $2}')"
python3 "$HERE/bench.py" bench "$COUNT" || exit 1
if command -v strace >/dev/null; then
printf 'x' >"$W/one" && python3 "$S3REQ" PUT /bench/s/a/b/c/one.txt --body "$W/one" >/dev/null
for method in GET HEAD; do
strace -f -c -o "$W/strace.$method" -p "$GW" 2>/dev/null &
ST=$!
sleep 1
for _ in $(seq 1 100); do python3 "$S3REQ" "$method" /bench/s/a/b/c/one.txt -o /dev/null >/dev/null; done
sleep 0.5
kill -INT "$ST"; wait "$ST" 2>/dev/null
# rows: % time, seconds, usecs/call, calls, [errors,] syscall
total=$(awk '$1 ~ /^[0-9.]+$/ && $NF != "total" {s += $4} END {print s + 0}' "$W/strace.$method")
top=$(awk '$1 ~ /^[0-9.]+$/ && $NF != "total" {print $NF ":" $4}' "$W/strace.$method" |
sort -t: -k2 -rn | head -8 | tr '\n' ' ')
echo "$method x100: $total system calls in the gateway ($((total / 100)) a call); most: $top"
done
fi
+252
View File
@@ -0,0 +1,252 @@
#!/bin/bash
#
# Proof test for patches/v1.11.0/0005-posix-no-symlinks.patch.
#
# sudo bash proof.sh /path/to/versitygw
#
# Starts two throwaway gateways from the given binary, A on 127.0.0.1:${PROOF_PORT:-7393}
# and B on the next port, each on the posix backend rooted at its own namespace
# directory under ${PROOF_DIR:-/var/tmp/s3gw-no-symlinks} (ns-a, ns-b), with its own
# internal IAM, --chuid --chgid and --dir-perms 0700 as leil-rig's gateways run.
# It then replays Norn's M5 stage 13 escape layout: as root, owned by the user's
# UID, it plants in A's home and in B's bucket links to the other namespace's
# marker (absolute and relative), a link to a directory there, a link to another
# user's home in the same namespace, a FIFO, a socket and a device, and drives
# every S3 operation at them. Nothing installed is touched: no package, unit or
# config. Prints one line per check and exits non-zero if any fails. KEEP=1
# leaves the directory (and both gateways' logs) behind.
#
# The accounts, made by root through each gateway's admin API, on
# leil-cluster's reserved test band:
#
# ns-user uid 74990 user owns "home" on A and "data" on B
# ns-other uid 74991 user owns "sibling" on A (another user's home)
#
# It needs root: it chowns, plants entries as root and makes a device node.
set -uo pipefail
VGW=${1:?usage: proof.sh /path/to/versitygw}
HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
S3REQ=${S3REQ:-$HERE/../owner-scope/s3req.py}
PORT_A=${PROOF_PORT:-7393}
PORT_B=$((PORT_A + 1))
W=${PROOF_DIR:-/var/tmp/s3gw-no-symlinks}
export S3_REGION=us-east-1
UID_USER=74990 UID_OTHER=74991
[ -x "$VGW" ] || { echo "FATAL: $VGW is not an executable" >&2; exit 2; }
[ -f "$S3REQ" ] || { echo "FATAL: $S3REQ is missing (tests/owner-scope/s3req.py)" >&2; exit 2; }
[ "$(id -u)" = 0 ] || { echo "FATAL: run as root" >&2; exit 2; }
command -v python3 >/dev/null || { echo "FATAL: python3 is required" >&2; exit 2; }
for port in "$PORT_A" "$PORT_B"; do
if (exec 3<>"/dev/tcp/127.0.0.1/$port") 2>/dev/null; then
echo "FATAL: something already listens on 127.0.0.1:$port (set PROOF_PORT)" >&2
exit 2
fi
done
rm -rf "$W" && mkdir -p "$W/ns-a" "$W/ns-b" "$W/iam-a" "$W/iam-b" "$W/tmp" || exit 2
chmod 0711 "$W" "$W/ns-a" "$W/ns-b"
secret() { python3 -c 'import secrets; print(secrets.token_hex(16))'; }
declare -A KEY SECRET
for who in root ns-user ns-other; do KEY[$who]=$who SECRET[$who]=$(secret); done
KEY[root]=proofroot
start() { # start <name> <port> <root> <iam>
"$VGW" --access "${KEY[root]}" --secret "${SECRET[root]}" --region "$S3_REGION" \
--port "127.0.0.1:$2" --iam-dir "$4" \
posix --chuid --chgid --dir-perms 0700 "$3" >"$W/gateway-$1.log" 2>&1 &
echo $!
}
GW_A=$(start a "$PORT_A" "$W/ns-a" "$W/iam-a")
GW_B=$(start b "$PORT_B" "$W/ns-b" "$W/iam-b")
cleanup() {
kill "$GW_A" "$GW_B" 2>/dev/null
wait "$GW_A" "$GW_B" 2>/dev/null
[ "${KEEP:-0}" = 1 ] && echo "kept $W" || rm -rf "$W"
}
trap cleanup EXIT
for port in "$PORT_A" "$PORT_B"; do
for _ in $(seq 1 50); do
(exec 3<>"/dev/tcp/127.0.0.1/$port") 2>/dev/null && break
kill -0 "$GW_A" 2>/dev/null && kill -0 "$GW_B" 2>/dev/null ||
{ cat "$W"/gateway-*.log; echo "FATAL: a gateway exited" >&2; exit 2; }
sleep 0.2
done
done
echo "gateways $("$VGW" --version 2>&1 | head -1) on 127.0.0.1:$PORT_A (A) and :$PORT_B (B), sha256 $(sha256sum "$VGW" | cut -c1-16)"
port() { [ "$1" = A ] && echo "$PORT_A" || echo "$PORT_B"; }
admin() { # admin <A|B> <args...>
local gw=$1; shift
ADMIN_ACCESS_KEY_ID=${KEY[root]} ADMIN_SECRET_ACCESS_KEY=${SECRET[root]} \
"$VGW" admin --region "$S3_REGION" --endpoint-url "http://127.0.0.1:$(port "$gw")" "$@"
}
# req <A|B> <who> <s3req.py args...> -- one request; prints the status
req() {
local gw=$1 who=$2; shift 2
S3_ENDPOINT=http://127.0.0.1:$(port "$gw") S3_KEY=${KEY[$who]} S3_SECRET=${SECRET[$who]} \
timeout 20 python3 "$S3REQ" "$@" 2>"$W/tmp/err" || [ -s "$W/tmp/err" ] || echo "no answer in 20 s" >"$W/tmp/err"
}
PASS=0 FAIL=0
ok() { PASS=$((PASS + 1)); printf 'PASS %-4s %s %s\n' "$1" "$2" "$3"; }
bad() { FAIL=$((FAIL + 1)); printf 'FAIL %-4s %s (want %s) %s [%s]\n' "$1" "${2:-none}" "$3" "$4" "$5"; }
# check <id> <want> <what> <A|B> <who> <s3req.py args...>
check() {
local id=$1 want=$2 what=$3; shift 3
local got
got=$(req "$@")
if [ "$got" = "$want" ]; then ok "$id" "$got" "$what"; else bad "$id" "$got" "$want" "$what" "$(tr '\n' ' ' <"$W/tmp/err")"; fi
}
# check_cmd <id> <want: yes|no> <what> <command...> -- whether the command succeeds
check_cmd() {
local id=$1 want=$2 what=$3; shift 3
local got=yes
"$@" >"$W/tmp/err" 2>&1 || got=no
if [ "$got" = "$want" ]; then ok "$id" "$got" "$what"; else bad "$id" "$got" "$want" "$what" "$(tr '\n' ' ' <"$W/tmp/err")"; fi
}
# The namespaces' data, as each gateway stores it
A=$W/ns-a B=$W/ns-b
MARK_A="marker of home namespace A" MARK_B="marker of bucket namespace B" MARK_SIB="marker of another home in A"
is_file() { [ -f "$1" ] && [ ! -L "$1" ]; }
is_link() { [ -L "$1" ]; }
holds() { [ "$(cat "$1" 2>/dev/null)" = "$2" ]; }
absent() { [ ! -e "$1" ] && [ ! -L "$1" ]; }
no_attrs() { [ -z "$(getfattr --absolute-names -d -m '^user\.X-Amz' "$1" 2>/dev/null)" ]; }
markers_intact() {
holds "$A/home/escape/marker.txt" "$MARK_A" && holds "$B/data/escape/marker.txt" "$MARK_B" &&
holds "$A/sibling/secret.txt" "$MARK_SIB" && no_attrs "$A/home/escape/marker.txt" &&
no_attrs "$B/data/escape/marker.txt" && no_attrs "$A/sibling/secret.txt"
}
echo "--- setup (root, admin API; then the planted entries, as root)"
for gw in A B; do
check_cmd S1$gw yes "$gw create-user ns-user (uid $UID_USER)" \
admin "$gw" create-user --access ns-user --secret "${SECRET[ns-user]}" --role user --user-id $UID_USER --group-id $UID_USER
done
check_cmd S2 yes "A create-user ns-other (uid $UID_OTHER)" \
admin A create-user --access ns-other --secret "${SECRET[ns-other]}" --role user --user-id $UID_OTHER --group-id $UID_OTHER
check_cmd S3 yes "A create-bucket home --owner ns-user" admin A create-bucket --owner ns-user --bucket home
check_cmd S4 yes "A create-bucket sibling --owner ns-other" admin A create-bucket --owner ns-other --bucket sibling
check_cmd S5 yes "B create-bucket data --owner ns-user" admin B create-bucket --owner ns-user --bucket data
printf '%s' "$MARK_A" >"$W/tmp/mark-a"; printf '%s' "$MARK_B" >"$W/tmp/mark-b"; printf '%s' "$MARK_SIB" >"$W/tmp/mark-sib"
check S6 200 "A ns-user PutObject home/escape/marker.txt" A ns-user PUT /home/escape/marker.txt --body "$W/tmp/mark-a"
check S7 200 "B ns-user PutObject data/escape/marker.txt" B ns-user PUT /data/escape/marker.txt --body "$W/tmp/mark-b"
check S8 200 "A ns-other PutObject sibling/secret.txt" A ns-other PUT /sibling/secret.txt --body "$W/tmp/mark-sib"
plant() { # plant <dir in a namespace> <other namespace's escape dir> <relative prefix to it>
local d=$1 other=$2 rel=$3
ln -s "$other/marker.txt" "$d/link-abs" && ln -s "$rel/marker.txt" "$d/link-rel" &&
ln -s "$other" "$d/link-dir" && ln -s "$other/marker.txt" "$d/link-del" &&
mkfifo "$d/fifo" && python3 -c 'import socket,sys; s=socket.socket(socket.AF_UNIX); s.bind(sys.argv[1])' "$d/sock" &&
mknod "$d/dev" c 1 3 && chown -h $UID_USER:$UID_USER "$d"/link-* "$d/fifo" "$d/sock" "$d/dev"
}
check_cmd S9 yes "plant in A home/escape: links to B's marker (abs, ../../../ns-b/...), to B's dir, FIFO, socket, device" \
plant "$A/home/escape" "$B/data/escape" ../../../ns-b/data/escape
check_cmd S10 yes "plant in B data/escape: links to A's marker (abs, ../../../ns-a/...), to A's dir, FIFO, socket, device" \
plant "$B/data/escape" "$A/home/escape" ../../../ns-a/home/escape
check_cmd S11 yes "plant in A home/escape: link-sib -> ../../sibling/secret.txt (another home, same namespace)" \
bash -c "ln -s ../../sibling/secret.txt '$A/home/escape/link-sib' && chown -h $UID_USER:$UID_USER '$A/home/escape/link-sib'"
check_cmd S12 yes "the links resolve on this host (as they did on leil-rig)" \
bash -c "holds() { [ \"\$(cat \"\$1\")\" = \"\$2\" ]; }; holds '$A/home/escape/link-abs' '$MARK_B' && holds '$A/home/escape/link-rel' '$MARK_B' && holds '$B/data/escape/link-abs' '$MARK_A' && holds '$B/data/escape/link-rel' '$MARK_A' && holds '$A/home/escape/link-sib' '$MARK_SIB'"
echo "--- reads: a link, FIFO, socket or device is no object (404), at the end of the key or on its way"
n=0
for gw in A B; do
bk=$([ "$gw" = A ] && echo home || echo data)
for key in link-abs link-rel link-dir/marker.txt link-dir/ fifo sock dev $([ "$gw" = A ] && echo link-sib); do
n=$((n + 1))
check R$n 404 "$gw GetObject $bk/escape/$key" "$gw" ns-user GET "/$bk/escape/$key" -o "$W/tmp/body"
n=$((n + 1))
check R$n 404 "$gw HeadObject $bk/escape/$key" "$gw" ns-user HEAD "/$bk/escape/$key"
done
done
check R50 404 "A GetObjectTagging home/escape/link-abs" A ns-user GET /home/escape/link-abs tagging
check R51 404 "A GetObjectAttributes home/escape/link-rel" A ns-user GET /home/escape/link-rel attributes -H "x-amz-object-attributes: ETag,ObjectSize"
check R52 404 "A CopyObject from home/escape/link-abs" A ns-user PUT /home/copied.txt -H "x-amz-copy-source: /home/escape/link-abs"
check R53 404 "A CopyObject from home/escape/link-dir/marker.txt" A ns-user PUT /home/copied.txt -H "x-amz-copy-source: /home/escape/link-dir/marker.txt"
check R54 404 "A CopyObject from home/escape/fifo" A ns-user PUT /home/copied.txt -H "x-amz-copy-source: /home/escape/fifo"
check R55 200 "A GetObject home/escape/marker.txt (its own object still reads)" A ns-user GET /home/escape/marker.txt -o "$W/tmp/body"
check_cmd R56 yes " ...and holds A's marker" holds "$W/tmp/body" "$MARK_A"
echo "--- listings skip them and never enter them"
listed() { # listed <A|B> <bucket> <query> -- the keys and common prefixes, one per line
req "$1" ns-user GET "/$2" "$3" -o "$W/tmp/list.xml" >/dev/null
python3 -c 'import re,sys; d=open(sys.argv[1]).read(); print("\n".join(re.findall(r"<(?:Key|Prefix)>([^<]*)</(?:Key|Prefix)>", d)))' "$W/tmp/list.xml"
}
expect_listed() { # expect_listed <id> <what> <want> <A|B> <bucket> <query>
local got
got=$(listed "$4" "$5" "$6" | grep -v '^$' | grep -vx "$(sed -n 's/.*prefix=\([^&]*\).*/\1/p' <<<"$6")" | sort | tr '\n' ' ')
if [ "$got" = "$3" ]; then ok "$1" "[$got]" "$2"; else bad "$1" "[$got]" "[$3]" "$2" "$(head -c 300 "$W/tmp/list.xml")"; fi
}
expect_listed L1 "A ListObjectsV2 home prefix escape/: its marker alone" "escape/marker.txt " A home "list-type=2&prefix=escape/"
expect_listed L2 "B ListObjectsV2 data prefix escape/: its marker alone" "escape/marker.txt " B data "list-type=2&prefix=escape/"
expect_listed L3 "A ListObjectsV2 home prefix escape/link-dir/: nothing" "" A home "list-type=2&prefix=escape/link-dir/"
expect_listed L4 "B ListObjects (v1) data prefix escape/link-dir/: nothing" "" B data "prefix=escape/link-dir/"
expect_listed L5 "A ListObjectsV2 home delimiter /, prefix escape/: no link-dir/ prefix" "escape/marker.txt " A home "list-type=2&prefix=escape/&delimiter=/"
expect_listed L6 "A ListObjectVersions home prefix escape/" "escape/marker.txt " A home "versions&prefix=escape/"
echo "--- writes act on the entry's own name, never through it"
printf 'written by ns-user\n' >"$W/tmp/new"
check W1 200 "A PutObject home/escape/link-abs (over the link)" A ns-user PUT /home/escape/link-abs --body "$W/tmp/new"
check_cmd W2 yes " ...the link is now that object, a file of uid $UID_USER" \
bash -c "[ -f '$A/home/escape/link-abs' ] && [ ! -L '$A/home/escape/link-abs' ] && [ \$(stat -c %u '$A/home/escape/link-abs') = $UID_USER ]"
check W3 200 "B PutObject data/escape/fifo (over the FIFO)" B ns-user PUT /data/escape/fifo --body "$W/tmp/new"
check_cmd W4 yes " ...now a regular file" is_file "$B/data/escape/fifo"
check W5 200 "A CopyObject home/escape/marker.txt to home/escape/link-rel" A ns-user PUT /home/escape/link-rel -H "x-amz-copy-source: /home/escape/marker.txt"
check_cmd W6 yes " ...link-rel is now a copy of A's marker" bash -c "[ ! -L '$A/home/escape/link-rel' ] && [ \"\$(cat '$A/home/escape/link-rel')\" = '$MARK_A' ]"
check W7 409 "A PutObject home/escape/link-dir/new.txt (under the link)" A ns-user PUT /home/escape/link-dir/new.txt --body "$W/tmp/new"
check W8 409 "B PutObject data/escape/link-dir/new.txt (under the link)" B ns-user PUT /data/escape/link-dir/new.txt --body "$W/tmp/new"
check W9 409 "A CopyObject to home/escape/link-dir/copy.txt" A ns-user PUT /home/escape/link-dir/copy.txt -H "x-amz-copy-source: /home/escape/marker.txt"
check W10 409 "A PutObject home/escape/sock/x (under the socket)" A ns-user PUT /home/escape/sock/x --body "$W/tmp/new"
check_cmd W11 yes " ...nothing was written in B, or in A through B's link" \
bash -c "[ ! -e '$B/data/escape/new.txt' ] && [ ! -e '$B/data/escape/copy.txt' ] && [ ! -e '$A/home/escape/new.txt' ]"
TAGS=$W/tmp/tags.xml
printf '<Tagging xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><TagSet><Tag><Key>k</Key><Value>v</Value></Tag></TagSet></Tagging>' >"$TAGS"
check W12 404 "B PutObjectTagging data/escape/link-abs" B ns-user PUT /data/escape/link-abs tagging --body "$TAGS"
check W13 404 "A PutObjectTagging home/escape/link-dir/marker.txt" A ns-user PUT /home/escape/link-dir/marker.txt tagging --body "$TAGS"
check W14 404 "A PutObjectTagging home/escape/link-sib" A ns-user PUT /home/escape/link-sib tagging --body "$TAGS"
# a multipart upload completed over a link (B's link-dir/ has its own marker under it, so complete onto link-del's twin)
ln -s "$A/home/escape/marker.txt" "$B/data/escape/link-mp" && chown -h $UID_USER:$UID_USER "$B/data/escape/link-mp"
req B ns-user POST /data/escape/link-mp uploads -o "$W/tmp/mp.xml" >/dev/null
UPLOAD=$(sed -n 's:.*<UploadId>\([^<]*\)</UploadId>.*:\1:p' "$W/tmp/mp.xml")
check W15 200 "B UploadPart data/escape/link-mp" B ns-user PUT /data/escape/link-mp "partNumber=1&uploadId=$UPLOAD" --body "$W/tmp/new"
printf '<CompleteMultipartUpload xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Part><PartNumber>1</PartNumber><ETag>"%s"</ETag></Part></CompleteMultipartUpload>' \
"$(md5sum <"$W/tmp/new" | cut -d' ' -f1)" >"$W/tmp/complete.xml"
check W16 200 "B CompleteMultipartUpload data/escape/link-mp (over the link)" B ns-user POST /data/escape/link-mp "uploadId=$UPLOAD" --body "$W/tmp/complete.xml"
check_cmd W17 yes " ...link-mp is now that object" bash -c "[ ! -L '$B/data/escape/link-mp' ] && [ \"\$(cat '$B/data/escape/link-mp')\" = 'written by ns-user' ]"
echo "--- deletes remove the entry itself, never what a link points to"
check D1 204 "A DeleteObject home/escape/link-del" A ns-user DELETE /home/escape/link-del
check_cmd D2 yes " ...the link is gone, B's marker is not" bash -c "[ ! -L '$A/home/escape/link-del' ] && [ -f '$B/data/escape/marker.txt' ]"
check D3 204 "B DeleteObject data/escape/link-dir/marker.txt (under the link)" B ns-user DELETE /data/escape/link-dir/marker.txt
check_cmd D4 yes " ...A's marker is still there, and the link" bash -c "[ -f '$A/home/escape/marker.txt' ] && [ -L '$B/data/escape/link-dir' ]"
check D5 204 "A DeleteObject home/escape/sock" A ns-user DELETE /home/escape/sock
check D6 204 "A DeleteObject home/escape/dev" A ns-user DELETE /home/escape/dev
check_cmd D7 yes " ...both gone" bash -c "[ ! -e '$A/home/escape/sock' ] && [ ! -e '$A/home/escape/dev' ]"
DEL=$W/tmp/delete.xml
printf '<Delete xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Object><Key>escape/link-del</Key></Object><Object><Key>escape/link-dir/marker.txt</Key></Object></Delete>' >"$DEL"
check D8 200 "B DeleteObjects data: escape/link-del, escape/link-dir/marker.txt" B ns-user POST /data delete --body "$DEL"
check_cmd D9 yes " ...B's link-del is gone, A's marker is not" bash -c "[ ! -L '$B/data/escape/link-del' ] && [ -f '$A/home/escape/marker.txt' ]"
echo "--- a directory swapped for a link while requests run"
check X0 200 "A ns-user PutObject home/race/obj.txt" A ns-user PUT /home/race/obj.txt --body "$W/tmp/mark-a"
mkdir -p "$B/data/racedir" && printf '%s' "$MARK_B" >"$B/data/racedir/obj.txt" && printf '%s' "$MARK_B" >"$B/data/racedir/victim.txt" &&
ln -s "$B/data/racedir" "$A/home/race-alt"
check_cmd X1 yes "3 s of GET, PUT and DELETE under home/race/ while it swaps with a link to B's directory" \
env S3_ENDPOINT=http://127.0.0.1:$PORT_A S3_KEY=ns-user S3_SECRET="${SECRET[ns-user]}" S3REQ="$S3REQ" \
python3 "$HERE/race.py" "$A/home/race" "$A/home/race-alt" home race "$MARK_A" "$MARK_B" 3
sed 's/^/ /' "$W/tmp/err"
check_cmd X2 yes " ...B's directory holds only what it held" \
bash -c "[ \"\$(ls -A '$B/data/racedir' | sort | tr '\n' ' ')\" = 'obj.txt victim.txt ' ] && [ -z \"\$(getfattr --absolute-names -d -m '^user\.' '$B/data/racedir/obj.txt' 2>/dev/null)\" ]"
echo "--- the other namespace is as it was"
check_cmd Z1 yes "A's marker, B's marker and the sibling's marker unchanged, and no attributes set on them" markers_intact
check_cmd Z2 yes "the gateways logged no panic" bash -c "! grep -qi panic '$W'/gateway-*.log"
echo
echo "$PASS passed, $FAIL failed"
[ "$FAIL" = 0 ]
+98
View File
@@ -0,0 +1,98 @@
#!/usr/bin/env python3
"""Swap a bucket directory with a link while requests run under it.
S3_ENDPOINT=... S3_KEY=... S3_SECRET=... S3REQ=.../s3req.py \\
race.py <dir> <link> <bucket> <prefix> <inside> <outside> <seconds>
<dir> is the directory of <bucket>/<prefix>/ on disk, holding obj.txt with the
text <inside>. <link> is a link beside it to a directory outside the
namespace, holding obj.txt and victim.txt with the text <outside>. For
<seconds> one thread exchanges the two names (renameat2 RENAME_EXCHANGE) as
fast as it can while this one sends, in turn, GET <prefix>/obj.txt, PUT
<prefix>/new-<n>.txt and DELETE <prefix>/victim.txt. Exits 1 if a GET served
<outside>. What reached the other directory, the caller checks on disk.
Python standard library only.
"""
import ctypes
import http.client
import importlib.util
import os
import sys
import threading
import time
import urllib.parse
AT_FDCWD = -100
RENAME_EXCHANGE = 2
def main(argv):
if len(argv) != 7:
sys.exit(__doc__)
d, link, bucket, prefix, inside, outside, seconds = argv
spec = importlib.util.spec_from_file_location("s3req", os.environ["S3REQ"])
s3req = importlib.util.module_from_spec(spec)
spec.loader.exec_module(s3req)
libc = ctypes.CDLL(None, use_errno=True)
renameat2 = libc.renameat2
stop = threading.Event()
swaps = [0]
def swapper():
a, b = d.encode(), link.encode()
while not stop.is_set():
if renameat2(AT_FDCWD, a, AT_FDCWD, b, RENAME_EXCHANGE) != 0:
print("swap failed:", os.strerror(ctypes.get_errno()))
stop.set()
return
swaps[0] += 1
endpoint = urllib.parse.urlsplit(os.environ["S3_ENDPOINT"])
key, secret = os.environ["S3_KEY"], os.environ["S3_SECRET"]
region = os.environ.get("S3_REGION", "us-east-1")
def request(method, path, body=b""):
headers = {}
s3req.sign(method, endpoint.netloc, path, "", headers, body, key, secret, region)
conn = http.client.HTTPConnection(endpoint.hostname, endpoint.port, timeout=20)
conn.request(method, s3req.quote(path, safe="/"), body=body or None, headers=headers)
resp = conn.getresponse()
data = resp.read()
conn.close()
return resp.status, data
t = threading.Thread(target=swapper)
t.start()
counts = {}
leaks = 0
n = 0
deadline = time.monotonic() + float(seconds)
try:
while time.monotonic() < deadline and not stop.is_set():
status, data = request("GET", f"/{bucket}/{prefix}/obj.txt")
counts[f"GET {status}"] = counts.get(f"GET {status}", 0) + 1
if status == 200 and data.decode(errors="replace") != inside:
leaks += 1
if leaks <= 3:
print("GET served:", data[:80])
status, _ = request("PUT", f"/{bucket}/{prefix}/new-{n % 20}.txt", inside.encode())
counts[f"PUT {status}"] = counts.get(f"PUT {status}", 0) + 1
status, _ = request("DELETE", f"/{bucket}/{prefix}/victim.txt")
counts[f"DELETE {status}"] = counts.get(f"DELETE {status}", 0) + 1
n += 1
finally:
stop.set()
t.join()
# leave the directory where it started
if os.path.islink(d):
renameat2(AT_FDCWD, d.encode(), AT_FDCWD, link.encode(), RENAME_EXCHANGE)
print(f"{swaps[0]} swaps, {n} rounds:", ", ".join(f"{k} x{v}" for k, v in sorted(counts.items())))
if leaks:
print(f"{leaks} GETs served the other side")
sys.exit(1)
if __name__ == "__main__":
main(sys.argv[1:])
+174
View File
@@ -0,0 +1,174 @@
#!/bin/bash
#
# Stage 2 of the proof for patches/v1.11.0/0005-posix-no-symlinks.patch: Norn's M5 stage 13
# escape layout, replayed on leil-rig's installed gateways.
#
# sudo bash rig-replay.sh <peer IP> <test UID> <mount cache seconds> [BENCH_COUNT]
#
# Runs as root on the first gateway host (leil-mst-1), which mounts /srv/leilfs/0x0 (home
# namespace) and /srv/leilfs/0x1 (bucket namespace) and serves versitygw@0x0 and versitygw@0x1;
# <peer IP> is the other gateway host's, whose instances it reaches over the rig network. Each
# namespace's root keys are read from /etc/versitygw.d/<ns>.conf inside the admin calls and
# never printed.
#
# A throwaway account (<test UID>, leil-cluster's reserved test band) gets a home nf-home-<stamp>
# in 0x0 and a bucket nf-data-<stamp> in 0x1, each with escape/marker.txt. As root, owned by the
# UID, it plants in each a link to the other's marker (absolute, and relative ../../../<ns>/...),
# a link to the other's escape directory, a FIFO and a socket, waits out the mounts' cache, and
# drives the S3 calls at them through all four instances. Everything it made is removed at exit,
# through the mounts, with the account. BENCH_COUNT (default 0) also times that many PUT, GET,
# HEAD and DELETE calls and ten listings through the local 0x0 instance, on LeilFS.
set -uo pipefail
PEER=${1:?usage: rig-replay.sh <peer IP> <test UID> <mount cache seconds> [bench count]}
TUID=${2:?test UID}
CACHE=${3:?mount cache seconds}
BENCH=${4:-0}
HERE=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
S3REQ=$HERE/s3req.py
[ "$(id -u)" = 0 ] || { echo "FATAL: run as root" >&2; exit 2; }
[ -f "$S3REQ" ] || { echo "FATAL: $S3REQ is missing (copy tests/owner-scope/s3req.py beside this)" >&2; exit 2; }
conf() { echo "/etc/versitygw.d/$1.conf"; }
cval() { (set -a; . "$(conf "$1")"; eval "printf '%s' \"\${$2}\""); } # cval <ns> <var>, not for secrets
declare -A S3PORT ADMPORT MNT
for ns in 0x0 0x1; do
[ -r "$(conf $ns)" ] || { echo "FATAL: no $(conf $ns)" >&2; exit 2; }
S3PORT[$ns]=$(cval $ns VGW_PORT | tr -d :) ADMPORT[$ns]=$(cval $ns VGW_ADMIN_PORT | tr -d :) MNT[$ns]=$(cval $ns VGW_BACKEND_ARG)
mountpoint -q "${MNT[$ns]}" || { echo "FATAL: ${MNT[$ns]} is not mounted" >&2; exit 2; }
done
STAMP=$(date +%s)
AK=nofollow-$STAMP
SK=$(head -c 24 /dev/urandom | base64 | tr '+/' 'AB' | tr -d '=\n')
HOMEB=nf-home-$STAMP DATAB=nf-data-$STAMP
declare -A BK=([0x0]=$HOMEB [0x1]=$DATAB)
W=$(mktemp -d /var/tmp/s3gw-nf-replay.XXXXXX)
chmod 700 "$W"
# admin <ns> <args...> -- signed with this host's root keys for <ns>, read here
admin() {
local ns=$1; shift
(set -a; . "$(conf "$ns")"; ADMIN_ACCESS_KEY_ID=$ROOT_ACCESS_KEY_ID ADMIN_SECRET_ACCESS_KEY=$ROOT_SECRET_ACCESS_KEY \
exec versitygw admin --region "$ns" --endpoint-url "http://127.0.0.1:${ADMPORT[$ns]}" "$@")
}
# req <ns> <local|peer> <s3req.py args...> -- one request as the throwaway account; prints the status
req() {
local ns=$1 where=$2 ip=127.0.0.1; shift 2
[ "$where" = peer ] && ip=$PEER
S3_ENDPOINT=http://$ip:${S3PORT[$ns]} S3_REGION=$ns S3_KEY=$AK S3_SECRET=$SK \
timeout 20 python3 -I "$S3REQ" "$@" 2>"$W/err" || [ -s "$W/err" ] || echo "no answer in 20 s" >"$W/err"
}
# mkbucket <ns> -- the account's bucket in <ns>, made as leil-cluster's leilfs-user makes one
mkbucket() {
admin "$1" create-bucket --owner "$AK" --bucket "${BK[$1]}" --object-ownership BucketOwnerPreferred \
--create-bucket-configuration "LocationConstraint=$1" &&
chown "$TUID:$TUID" "${MNT[$1]}/${BK[$1]}" && chmod 0700 "${MNT[$1]}/${BK[$1]}"
}
MADE=0
cleanup() {
if [ "$MADE" = 1 ]; then
for ns in 0x0 0x1; do
rm -rf "${MNT[$ns]}/${BK[$ns]}" "${MNT[$ns]}/.vgwlocks/$(printf %s "${BK[$ns]}" | sha256sum | cut -c1-64)"
admin "$ns" delete-user --access "$AK" >/dev/null 2>&1 || echo "WARN: could not delete $AK in $ns" >&2
done
echo "removed $AK, ${MNT[0x0]}/$HOMEB and ${MNT[0x1]}/$DATAB"
fi
rm -rf "$W"
}
trap cleanup EXIT
PASS=0 FAIL=0
ok() { PASS=$((PASS + 1)); printf 'PASS %-4s %s %s\n' "$1" "$2" "$3"; }
bad() { FAIL=$((FAIL + 1)); printf 'FAIL %-4s %s (want %s) %s [%s]\n' "$1" "${2:-none}" "$3" "$4" "$5"; }
check() { # check <id> <want> <what> <ns> <local|peer> <s3req.py args...>
local id=$1 want=$2 what=$3 got; shift 3
got=$(req "$@")
if [ "$got" = "$want" ]; then ok "$id" "$got" "$what"; else bad "$id" "$got" "$want" "$what" "$(tr '\n' ' ' <"$W/err")"; fi
}
check_cmd() { # check_cmd <id> <want: yes|no> <what> <command...>
local id=$1 want=$2 what=$3 got=yes; shift 3
"$@" >"$W/err" 2>&1 || got=no
if [ "$got" = "$want" ]; then ok "$id" "$got" "$what"; else bad "$id" "$got" "$want" "$what" "$(tr '\n' ' ' <"$W/err")"; fi
}
echo "versitygw $(sha256sum /usr/bin/versitygw | cut -c1-12) here; 0x0 S3 :${S3PORT[0x0]}, 0x1 S3 :${S3PORT[0x1]}; peer $PEER; account $AK (uid $TUID)"
echo "--- setup"
for ns in 0x0 0x1; do
check_cmd S1$ns yes "$ns create-user $AK" admin $ns create-user --access "$AK" --secret "$SK" --role user --user-id "$TUID" --group-id "$TUID"
MADE=1
check_cmd S2$ns yes "$ns create-bucket ${BK[$ns]} --owner $AK, then $TUID:$TUID 0700 as leilfs-user" mkbucket $ns
printf '%s marker' "$ns" >"$W/mark-$ns"
check S3$ns 200 "$ns PutObject ${BK[$ns]}/escape/marker.txt" $ns local PUT "/${BK[$ns]}/escape/marker.txt" --body "$W/mark-$ns"
done
H=${MNT[0x0]}/$HOMEB/escape D=${MNT[0x1]}/$DATAB/escape
plant() { # plant <dir> <other escape dir> <relative way to it>
ln -s "$2/marker.txt" "$1/link-abs" && ln -s "$3/marker.txt" "$1/link-rel" && ln -s "$2" "$1/link-dir" &&
ln -s "$2/marker.txt" "$1/link-del" && mkfifo "$1/fifo" &&
python3 -c 'import socket,sys; socket.socket(socket.AF_UNIX).bind(sys.argv[1])' "$1/sock" &&
chown -h "$TUID:$TUID" "$1"/link-* "$1/fifo" "$1/sock"
}
check_cmd S4 yes "plant in /0x0/$HOMEB/escape: links to 0x1's marker (abs, ../../../0x1/...), to its dir, FIFO, socket" \
plant "$H" "$D" "../../../0x1/$DATAB/escape"
check_cmd S5 yes "plant in /0x1/$DATAB/escape: links to 0x0's marker (abs, ../../../0x0/...), to its dir, FIFO, socket" \
plant "$D" "$H" "../../../0x0/$HOMEB/escape"
check_cmd S6 yes "the links resolve on this host" \
bash -c "[ \"\$(cat '$H/link-abs')\" = '0x1 marker' ] && [ \"\$(cat '$H/link-rel')\" = '0x1 marker' ] && [ \"\$(cat '$D/link-abs')\" = '0x0 marker' ] && [ \"\$(cat '$D/link-rel')\" = '0x0 marker' ]"
sleep $((CACHE + 1)) # the peer's mounts see the planted entries
echo "--- reads through all four instances: 404"
n=0
for ns in 0x0 0x1; do
for where in local peer; do
for key in link-abs link-rel link-dir/marker.txt fifo sock; do
n=$((n + 1)); check R$n 404 "$ns $where GetObject ${BK[$ns]}/escape/$key" $ns $where GET "/${BK[$ns]}/escape/$key" -o "$W/body"
n=$((n + 1)); check R$n 404 "$ns $where HeadObject ${BK[$ns]}/escape/$key" $ns $where HEAD "/${BK[$ns]}/escape/$key"
done
n=$((n + 1)); check R$n 404 "$ns $where CopyObject from ${BK[$ns]}/escape/link-abs" $ns $where PUT "/${BK[$ns]}/copied-$where" -H "x-amz-copy-source: /${BK[$ns]}/escape/link-abs"
done
done
echo "--- listings through all four instances: the marker alone"
n=0
for ns in 0x0 0x1; do
for where in local peer; do
for prefix in escape/ escape/link-dir/; do
req $ns $where GET "/${BK[$ns]}" "list-type=2&prefix=$prefix" -o "$W/list.xml" >/dev/null
got=$(python3 -I -c 'import re,sys; print(" ".join(re.findall(r"<Key>([^<]*)</Key>", open(sys.argv[1]).read())))' "$W/list.xml")
want=$([ "$prefix" = escape/ ] && echo escape/marker.txt)
n=$((n + 1))
if [ "$got" = "$want" ]; then ok L$n "[$got]" "$ns $where ListObjectsV2 prefix $prefix"; else bad L$n "[$got]" "[$want]" "$ns $where ListObjectsV2 prefix $prefix" "$(head -c 200 "$W/list.xml")"; fi
done
done
done
echo "--- writes and deletes act on the entry itself, never through it"
printf 'written by %s\n' "$AK" >"$W/new"
n=0
for ns in 0x0 0x1; do
for where in local peer; do
n=$((n + 1)); check W$n 409 "$ns $where PutObject ${BK[$ns]}/escape/link-dir/new-$where.txt (under the link)" $ns $where PUT "/${BK[$ns]}/escape/link-dir/new-$where.txt" --body "$W/new"
n=$((n + 1)); check W$n 204 "$ns $where DeleteObject ${BK[$ns]}/escape/link-dir/marker.txt (under the link)" $ns $where DELETE "/${BK[$ns]}/escape/link-dir/marker.txt"
done
done
check_cmd W10 yes " ...both markers are still there, nothing new beside them" \
bash -c "[ \"\$(cat '$H/marker.txt')\" = '0x0 marker' ] && [ \"\$(cat '$D/marker.txt')\" = '0x1 marker' ] && ! ls '$H' '$D' | grep -q '^new-'"
check W11 200 "0x0 peer PutObject $HOMEB/escape/link-abs (over the link)" 0x0 peer PUT "/$HOMEB/escape/link-abs" --body "$W/new"
check W12 200 "0x1 local PutObject $DATAB/escape/fifo (over the FIFO)" 0x1 local PUT "/$DATAB/escape/fifo" --body "$W/new"
check W13 204 "0x1 peer DeleteObject $DATAB/escape/link-del" 0x1 peer DELETE "/$DATAB/escape/link-del"
check W14 204 "0x0 local DeleteObject $HOMEB/escape/sock" 0x0 local DELETE "/$HOMEB/escape/sock"
sleep $((CACHE + 1))
check_cmd W15 yes " ...link-abs and fifo are now files of uid $TUID, link-del and sock are gone, both markers intact" \
bash -c "[ -f '$H/link-abs' ] && [ ! -L '$H/link-abs' ] && [ \$(stat -c %u '$H/link-abs') = $TUID ] && [ -f '$D/fifo' ] && [ ! -p '$D/fifo' ] && [ ! -L '$D/link-del' ] && [ ! -e '$H/sock' ] && [ \"\$(cat '$H/marker.txt')\" = '0x0 marker' ] && [ \"\$(cat '$D/marker.txt')\" = '0x1 marker' ]"
if [ "$BENCH" -gt 0 ]; then
echo "--- timing through the local 0x0 instance, on LeilFS ($BENCH objects)"
S3_ENDPOINT=http://127.0.0.1:${S3PORT[0x0]} S3_REGION=0x0 S3_KEY=$AK S3_SECRET=$SK S3REQ=$S3REQ \
python3 -I "$HERE/bench.py" "$HOMEB" "$BENCH" || bad B1 failed ok "bench" ""
fi
echo
echo "$PASS passed, $FAIL failed"
[ "$FAIL" = 0 ]