mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-05 18:47:20 +01:00
Compare commits
66
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
89e7753ed5 | ||
|
|
495e24a476 | ||
|
|
1f15e7865a | ||
|
|
521a19c567 | ||
|
|
dd75add62f | ||
|
|
58aa9acfb0 | ||
|
|
8227ae3f49 | ||
|
|
3fd5e4c329 | ||
|
|
9d3907e36c | ||
|
|
bd953b0f84 | ||
|
|
7944cb4ba2 | ||
|
|
15d3c65e0c | ||
|
|
fea14c01a7 | ||
|
|
f2498e122a | ||
|
|
62481f1673 | ||
|
|
b8f074b7d3 | ||
|
|
cc1ec48151 | ||
|
|
5ece8dd63c | ||
|
|
67f7fad987 | ||
|
|
2b057eccbf | ||
|
|
8fdcf69eb0 | ||
|
|
988fc4f7ba | ||
|
|
11e8c4c288 | ||
|
|
d3cd061c22 | ||
|
|
895d49b55b | ||
|
|
95e0b74fb6 | ||
|
|
0978e7f833 | ||
|
|
38ce95d960 | ||
|
|
9a454bbe2b | ||
|
|
757917f564 | ||
|
|
a033ab76e5 | ||
|
|
5fcf12c080 | ||
|
|
5da137233d | ||
|
|
62d4f9152a | ||
|
|
a901c1a5e2 | ||
|
|
67b19b2db5 | ||
|
|
c54f1fe69c | ||
|
|
818ff69270 | ||
|
|
db89ed198b | ||
|
|
f7b5ca826b | ||
|
|
878d23b95a | ||
|
|
1e0b243aed | ||
|
|
79e2abdfbf | ||
|
|
530be3e373 | ||
|
|
9b3b12c607 | ||
|
|
3abdef3202 | ||
|
|
43fd5b8d82 | ||
|
|
150a69fe11 | ||
|
|
4fec65d949 | ||
|
|
f564918685 | ||
|
|
f9289f0570 | ||
|
|
4303b3aa4c | ||
|
|
a0ee7ba314 | ||
|
|
a976b21010 | ||
|
|
e57f8c4d87 | ||
|
|
67691a1eea | ||
|
|
02353444ac | ||
|
|
68944e83a3 | ||
|
|
00310f6588 | ||
|
|
5c9c424a84 | ||
|
|
5218e68554 | ||
|
|
00cffa028c | ||
|
|
a261f90e18 | ||
|
|
be29f44d87 | ||
|
|
2864bc0fe8 | ||
|
|
ab95d58b7c |
No files matched your search
@@ -27,7 +27,7 @@ jobs:
|
||||
|
||||
# Initializes the CodeQL tools for scanning.
|
||||
- name: Initialize CodeQL
|
||||
uses: github/codeql-action/init@v4.38.1
|
||||
uses: github/codeql-action/init@v4.38.2
|
||||
# Override language selection by uncommenting this and choosing your languages
|
||||
with:
|
||||
languages: go
|
||||
@@ -35,7 +35,7 @@ jobs:
|
||||
# Autobuild attempts to build any compiled languages (C/C++, C#, or Java).
|
||||
# If this step fails, then you should remove it and run the build manually (see below).
|
||||
- name: Autobuild
|
||||
uses: github/codeql-action/autobuild@v4.38.1
|
||||
uses: github/codeql-action/autobuild@v4.38.2
|
||||
|
||||
# ℹ️ Command-line programs to run using the OS shell.
|
||||
# 📚 See https://docs.github.com/en/actions/using-workflows/workflow-syntax-for-github-actions#jobsjob_idstepsrun
|
||||
@@ -49,4 +49,4 @@ jobs:
|
||||
# make release
|
||||
|
||||
- name: Perform CodeQL Analysis
|
||||
uses: github/codeql-action/analyze@v4.38.1
|
||||
uses: github/codeql-action/analyze@v4.38.2
|
||||
@@ -156,7 +156,7 @@ jobs:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
matrix:
|
||||
platform: [amd64, arm64, arm, 386]
|
||||
platform: [amd64, arm64, arm, 386, ppc64le, s390x]
|
||||
variant: ${{ fromJSON(needs.setup.outputs.variants) }}
|
||||
|
||||
steps:
|
||||
@@ -405,7 +405,7 @@ jobs:
|
||||
output: trivy-results.sarif
|
||||
exit-code: '0'
|
||||
- name: Upload Trivy scan results to GitHub Security
|
||||
uses: github/codeql-action/upload-sarif@v4.38.1
|
||||
uses: github/codeql-action/upload-sarif@v4.38.2
|
||||
if: always()
|
||||
with:
|
||||
sarif_file: trivy-results.sarif
|
||||
@@ -505,7 +505,9 @@ jobs:
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-amd64 \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-arm64 \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-arm \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-386
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-386 \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-ppc64le \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-s390x
|
||||
# The copy and the signature below use the digest this run pushed, not whatever the tag points at by then.
|
||||
DIGEST=$(jq -er '."containerimage.descriptor".digest' /tmp/manifest.json)
|
||||
echo "digest=${DIGEST}" >> "$GITHUB_OUTPUT"
|
||||
@@ -549,13 +551,15 @@ jobs:
|
||||
echo "Using skopeo to copy..."
|
||||
retry_with_backoff skopeo copy --all docker://ghcr.io/chrislusf/seaweedfs@${DIGEST} docker://chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}
|
||||
else
|
||||
echo "Using docker buildx imagetools (pulling 4 images from Docker Hub)..."
|
||||
echo "Using docker buildx imagetools (pulling 6 images from Docker Hub)..."
|
||||
# Fallback: create manifest directly on Docker Hub (pulls from Docker Hub - rate limited)
|
||||
retry_with_backoff docker buildx imagetools create -t chrislusf/seaweedfs:${BASE_TAG}${SUFFIX} \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-amd64 \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-arm64 \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-arm \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-386
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-386 \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-ppc64le \
|
||||
ghcr.io/chrislusf/seaweedfs:${BASE_TAG}${SUFFIX}-s390x
|
||||
fi
|
||||
|
||||
- name: Sign
|
||||
|
||||
@@ -149,12 +149,16 @@ jobs:
|
||||
- { variant: normal, tag_suffix: "", dockerfile: ./docker/Dockerfile.go_build, build_args: "", rust_variant: normal, platform: linux/arm64, arch: arm64, runner: ubuntu-24.04-arm, qemu: false }
|
||||
- { variant: normal, tag_suffix: "", dockerfile: ./docker/Dockerfile.go_build, build_args: "", rust_variant: normal, platform: linux/arm/v7, arch: armv7, runner: ubuntu-latest, qemu: true }
|
||||
- { variant: normal, tag_suffix: "", dockerfile: ./docker/Dockerfile.go_build, build_args: "", rust_variant: normal, platform: linux/386, arch: i386, runner: ubuntu-latest, qemu: false }
|
||||
- { variant: normal, tag_suffix: "", dockerfile: ./docker/Dockerfile.go_build, build_args: "", rust_variant: normal, platform: linux/ppc64le, arch: ppc64le, runner: ubuntu-latest, qemu: true }
|
||||
- { variant: normal, tag_suffix: "", dockerfile: ./docker/Dockerfile.go_build, build_args: "", rust_variant: normal, platform: linux/s390x, arch: s390x, runner: ubuntu-latest, qemu: true }
|
||||
|
||||
# Large disk - multi-arch
|
||||
- { variant: large_disk, tag_suffix: _large_disk, dockerfile: ./docker/Dockerfile.go_build, build_args: TAGS=5BytesOffset, rust_variant: large-disk, platform: linux/amd64, arch: amd64, runner: ubuntu-latest, qemu: false }
|
||||
- { variant: large_disk, tag_suffix: _large_disk, dockerfile: ./docker/Dockerfile.go_build, build_args: TAGS=5BytesOffset, rust_variant: large-disk, platform: linux/arm64, arch: arm64, runner: ubuntu-24.04-arm, qemu: false }
|
||||
- { variant: large_disk, tag_suffix: _large_disk, dockerfile: ./docker/Dockerfile.go_build, build_args: TAGS=5BytesOffset, rust_variant: large-disk, platform: linux/arm/v7, arch: armv7, runner: ubuntu-latest, qemu: true }
|
||||
- { variant: large_disk, tag_suffix: _large_disk, dockerfile: ./docker/Dockerfile.go_build, build_args: TAGS=5BytesOffset, rust_variant: large-disk, platform: linux/386, arch: i386, runner: ubuntu-latest, qemu: false }
|
||||
- { variant: large_disk, tag_suffix: _large_disk, dockerfile: ./docker/Dockerfile.go_build, build_args: TAGS=5BytesOffset, rust_variant: large-disk, platform: linux/ppc64le, arch: ppc64le, runner: ubuntu-latest, qemu: true }
|
||||
- { variant: large_disk, tag_suffix: _large_disk, dockerfile: ./docker/Dockerfile.go_build, build_args: TAGS=5BytesOffset, rust_variant: large-disk, platform: linux/s390x, arch: s390x, runner: ubuntu-latest, qemu: true }
|
||||
|
||||
# Full tags - multi-arch
|
||||
- { variant: full, tag_suffix: _full, dockerfile: ./docker/Dockerfile.go_build, build_args: "TAGS=elastic,gocdk,rclone,sqlite,tarantool,tikv,ydb", rust_variant: normal, platform: linux/amd64, arch: amd64, runner: ubuntu-latest, qemu: false }
|
||||
@@ -456,7 +460,7 @@ jobs:
|
||||
|
||||
- name: Upload Trivy scan results to GitHub Security
|
||||
if: always()
|
||||
uses: github/codeql-action/upload-sarif@v4.38.1
|
||||
uses: github/codeql-action/upload-sarif@v4.38.2
|
||||
with:
|
||||
sarif_file: trivy-results.sarif
|
||||
category: trivy-${{ matrix.variant }}
|
||||
|
||||
@@ -289,6 +289,7 @@ jobs:
|
||||
s3tests/functional/test_s3.py::test_object_write_check_etag \
|
||||
s3tests/functional/test_s3.py::test_object_write_cache_control \
|
||||
s3tests/functional/test_s3.py::test_object_write_expires \
|
||||
s3tests/functional/test_s3.py::test_object_content_encoding_aws_chunked \
|
||||
s3tests/functional/test_s3.py::test_object_write_read_update_read_delete \
|
||||
s3tests/functional/test_s3.py::test_object_metadata_replaced_on_put \
|
||||
s3tests/functional/test_s3.py::test_object_write_file \
|
||||
@@ -311,6 +312,7 @@ jobs:
|
||||
s3tests/functional/test_s3.py::test_get_object_ifmodifiedsince_good \
|
||||
s3tests/functional/test_s3.py::test_get_object_ifmodifiedsince_failed \
|
||||
s3tests/functional/test_s3.py::test_get_object_ifunmodifiedsince_failed \
|
||||
s3tests/functional/test_s3.py::test_get_checksum_object_attributes \
|
||||
s3tests/functional/test_s3.py::test_bucket_head \
|
||||
s3tests/functional/test_s3.py::test_bucket_head_notexist \
|
||||
s3tests/functional/test_s3.py::test_object_raw_authenticated \
|
||||
@@ -1149,6 +1151,7 @@ jobs:
|
||||
s3tests/functional/test_s3.py::test_object_write_check_etag \
|
||||
s3tests/functional/test_s3.py::test_object_write_cache_control \
|
||||
s3tests/functional/test_s3.py::test_object_write_expires \
|
||||
s3tests/functional/test_s3.py::test_object_content_encoding_aws_chunked \
|
||||
s3tests/functional/test_s3.py::test_object_write_read_update_read_delete \
|
||||
s3tests/functional/test_s3.py::test_object_metadata_replaced_on_put \
|
||||
s3tests/functional/test_s3.py::test_object_write_file \
|
||||
@@ -1171,6 +1174,7 @@ jobs:
|
||||
s3tests/functional/test_s3.py::test_get_object_ifmodifiedsince_good \
|
||||
s3tests/functional/test_s3.py::test_get_object_ifmodifiedsince_failed \
|
||||
s3tests/functional/test_s3.py::test_get_object_ifunmodifiedsince_failed \
|
||||
s3tests/functional/test_s3.py::test_get_checksum_object_attributes \
|
||||
s3tests/functional/test_s3.py::test_bucket_head \
|
||||
s3tests/functional/test_s3.py::test_bucket_head_notexist \
|
||||
s3tests/functional/test_s3.py::test_object_raw_authenticated \
|
||||
|
||||
@@ -14,7 +14,7 @@ require (
|
||||
github.com/coreos/go-semver v0.3.1 // indirect
|
||||
github.com/coreos/go-systemd/v22 v22.7.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/dustin/go-humanize v1.0.1
|
||||
github.com/dustin/go-humanize v1.1.0
|
||||
github.com/eapache/go-resiliency v1.6.0 // indirect
|
||||
github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 // indirect
|
||||
github.com/eapache/queue v1.1.0 // indirect
|
||||
@@ -94,7 +94,7 @@ require (
|
||||
golang.org/x/exp v0.0.0-20260709172345-9ea1abe57597
|
||||
golang.org/x/image v0.46.0
|
||||
golang.org/x/net v0.58.0
|
||||
golang.org/x/oauth2 v0.36.0
|
||||
golang.org/x/oauth2 v0.37.0
|
||||
golang.org/x/sys v0.48.0
|
||||
golang.org/x/text v0.42.0 // indirect
|
||||
golang.org/x/tools v0.49.0 // indirect
|
||||
@@ -111,7 +111,7 @@ require (
|
||||
)
|
||||
|
||||
require (
|
||||
cloud.google.com/go/kms v1.34.0
|
||||
cloud.google.com/go/kms v1.35.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/keyvault/azkeys v0.10.0
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2
|
||||
github.com/Jille/raft-grpc-transport v1.6.1
|
||||
@@ -154,7 +154,7 @@ require (
|
||||
github.com/tarantool/go-tarantool/v3 v3.0.2
|
||||
github.com/testcontainers/testcontainers-go v0.44.0
|
||||
github.com/tikv/client-go/v2 v2.0.7
|
||||
github.com/twmb/avro v1.8.0
|
||||
github.com/twmb/avro v1.9.0
|
||||
github.com/xeipuuv/gojsonschema v1.2.0
|
||||
github.com/ydb-platform/ydb-go-sdk-auth-environ v0.5.2
|
||||
github.com/ydb-platform/ydb-go-sdk/v3 v3.151.1
|
||||
@@ -302,13 +302,13 @@ require (
|
||||
cloud.google.com/go/iam v1.12.0 // indirect
|
||||
cloud.google.com/go/monitoring v1.30.0 // indirect
|
||||
filippo.io/edwards25519 v1.2.0 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.1
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.8.0
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.7.0 // indirect
|
||||
github.com/Azure/go-ntlmssp v0.1.1 // indirect
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.7.2 // indirect
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.8.0 // indirect
|
||||
github.com/Files-com/files-sdk-go/v3 v3.3.194 // indirect
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.35.0 // indirect
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/exporter/metric v0.57.0 // indirect
|
||||
|
||||
@@ -298,8 +298,8 @@ cloud.google.com/go/kms v1.4.0/go.mod h1:fajBHndQ+6ubNw6Ss2sSd+SWvjL26RNo/dr7uxs
|
||||
cloud.google.com/go/kms v1.5.0/go.mod h1:QJS2YY0eJGBg3mnDfuaCyLauWwBJiHRboYxJ++1xJNg=
|
||||
cloud.google.com/go/kms v1.6.0/go.mod h1:Jjy850yySiasBUDi6KFUwUv2n1+o7QZFyuUJg6OgjA0=
|
||||
cloud.google.com/go/kms v1.9.0/go.mod h1:qb1tPTgfF9RQP8e1wq4cLFErVuTJv7UsSC915J8dh3w=
|
||||
cloud.google.com/go/kms v1.34.0 h1:mxWcXEiyjxwFH5gclulLx+B8Y2OEpKJRZ5FOF78c2XE=
|
||||
cloud.google.com/go/kms v1.34.0/go.mod h1:FbxZWUiihmyjxlaBha84OK5+fmJHPrS6F5/mBFdJk6A=
|
||||
cloud.google.com/go/kms v1.35.0 h1:nJ/ktaqspx1nPM9vIcO0SHbhqCAm8nvAxL1siuVgKm0=
|
||||
cloud.google.com/go/kms v1.35.0/go.mod h1:0++71pIHvJL+GmMa8K4jOWFq7gNOX3jm2PRMSJwTKJw=
|
||||
cloud.google.com/go/language v1.4.0/go.mod h1:F9dRpNFQmJbkaop6g0JhSBXCNlO90e1KWx5iDdxbWic=
|
||||
cloud.google.com/go/language v1.6.0/go.mod h1:6dJ8t3B+lUYfStgls25GusK04NLh3eDLQnWM3mdEbhI=
|
||||
cloud.google.com/go/language v1.7.0/go.mod h1:DJ6dYN/W+SQOjF8e1hLQXMF21AkH2w9wiPzPCJa2MIE=
|
||||
@@ -553,10 +553,10 @@ gioui.org v0.0.0-20210308172011-57750fc8a0a6/go.mod h1:RSH6KIUZ0p2xy5zHDxgAM4zum
|
||||
git.sr.ht/~sbinet/gg v0.3.1/go.mod h1:KGYtlADtqsqANL9ueOFkWymvzUvLMQllU5Ixo+8v3pc=
|
||||
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6 h1:He8afgbRMd7mFxO99hRNu+6tazq8nFF9lIwo9JFroBk=
|
||||
github.com/AdaLogics/go-fuzz-headers v0.0.0-20240806141605-e8a1dd7889d6/go.mod h1:8o94RPi1/7XTJvwPpRSzSUedZrtlirdB3r9Z20bi2f8=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0 h1:aokoqcHvaGjiM3VpjKDfMMnF/8epJ+Q1HLJ7CudztqE=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.22.0/go.mod h1:/WYEx9pcM9Y+Dd/APJaNlSvVSvzl54rrMdZT5+Oi2LM=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.0 h1:CU4+EJeJi3TKYWEcYuSdWsjzw0nVsK/H0MSQOiPcymU=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.0/go.mod h1:q0+UTSRvShwUCrR/s5HtyInYphN7Wvxb7snFM3u+SLA=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.1 h1:zvXfGJCWvywnCA814d8ZiVyt+fm9nnTE8xSb99zRyfo=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azcore v1.23.1/go.mod h1:iptorS+VYKFL2N6PnebpS91dubG35eAOEERnT4PJbQU=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1 h1:u93s+zU2JD62im61Bm5CZIc1ZrOJaIAWEg0WOrMVkEo=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity v1.14.1/go.mod h1:oXtinPO4OLj9d1DOTrqrL1oRwGhcqadvAmrl6wTeGlk=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.4.0 h1:xFaZZ+IubdftrDHnGGwZ6QvQ3KHTtWl2MCK+GMt2vxs=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/azidentity/cache v0.4.0/go.mod h1:mCBhUhlMjLLJKr5aqw2TNS/VqJOie8MzWq3DAMJeKso=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.12.0 h1:fhqpLE3UEXi9lPaBRpQ6XuRW0nU7hgg4zlmZZa+a9q4=
|
||||
@@ -577,8 +577,8 @@ github.com/Azure/go-ntlmssp v0.1.1 h1:l+FM/EEMb0U9QZE7mKNEDw5Mu3mFiaa2GKOoTSsNDP
|
||||
github.com/Azure/go-ntlmssp v0.1.1/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk=
|
||||
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1 h1:WJTmL004Abzc5wDB5VtZG2PJk5ndYDgVacGqfirKxjM=
|
||||
github.com/AzureAD/microsoft-authentication-extensions-for-go/cache v0.1.1/go.mod h1:tCcJZ0uHAmvjsVYzEFivsRTN00oz5BEsRgQHu5JZ9WE=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.7.2 h1:RHK7bS+HQMslb1sZpAokUt+zTVmue0hKSs2C791hhzU=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.7.2/go.mod h1:HKpQxkWaGLJ+D/5H8QRpyQXA1eKjxkFlOMwck5+33Jk=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.8.0 h1:Nljr4q1GRA/5vCrMONS+g4u4LRHNgOXVSh3O43J2CnI=
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.8.0/go.mod h1:Y33QHnf0FfdVewFFISOGe20mkZbxX4H839o955/PoeI=
|
||||
github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03qcyfWMU=
|
||||
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||
github.com/Codefor/geohash v0.0.0-20140723084247-1b41c28e3a9d h1:iG9B49Q218F/XxXNRM7k/vWf7MKmLIS8AcJV9cGN4nA=
|
||||
@@ -953,8 +953,8 @@ github.com/dropbox/dropbox-sdk-go-unofficial/v6 v6.4.0/go.mod h1:gDXhl0OElhzYoDs
|
||||
github.com/dsnet/try v0.0.3 h1:ptR59SsrcFUYbT/FhAbKTV6iLkeD6O18qfIWRml2fqI=
|
||||
github.com/dsnet/try v0.0.3/go.mod h1:WBM8tRpUmnXXhY1U6/S8dt6UWdHTQ7y8A5YSkRCkq40=
|
||||
github.com/dustin/go-humanize v1.0.0/go.mod h1:HtrtbFcZ19U5GC7JDqmcUSB87Iq5E25KnS6fMYU6eOk=
|
||||
github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
|
||||
github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
|
||||
github.com/dustin/go-humanize v1.1.0 h1:dbKTrvD0klcbBV/h4AWJdMuZogJACoMlvWIWZ5b2xWg=
|
||||
github.com/dustin/go-humanize v1.1.0/go.mod h1:hc1CvRkJMsgxqjmjMQF3QNRAZBwY8AXBAzKYoSX9sFI=
|
||||
github.com/eapache/go-resiliency v1.6.0 h1:CqGDTLtpwuWKn6Nj3uNUdflaq+/kIPsg0gfNzHton30=
|
||||
github.com/eapache/go-resiliency v1.6.0/go.mod h1:5yPzW0MIvSe0JDsv0v+DvcjEv2FyD6iZYSs1ZI+iQho=
|
||||
github.com/eapache/go-xerial-snappy v0.0.0-20230731223053-c322873962e3 h1:Oy0F4ALJ04o5Qqpdz8XLIpNA3WM/iSIXqxtqo7UGVws=
|
||||
@@ -1965,8 +1965,8 @@ github.com/tsuna/gohbase v0.0.0-20201125011725-348991136365/go.mod h1:zj0GJHGvyf
|
||||
github.com/tv42/httpunix v0.0.0-20150427012821-b75d8614f926/go.mod h1:9ESjWnEqriFuLhtthL60Sar/7RFoluCcXsuvEwTV5KM=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/twmb/avro v1.8.0 h1:UMWLg+nH4P3yad5Om7yFSohYLy2RG1s7BcFFiOvmK9Q=
|
||||
github.com/twmb/avro v1.8.0/go.mod h1:X0fT1dY2xcbV4YuCE4mYro+qljHl4kUF5uA/2z1rgSk=
|
||||
github.com/twmb/avro v1.9.0 h1:JSiqewo3AANj7vlVCQXBsIZTA3LiiBble7Xp8T4lbtA=
|
||||
github.com/twmb/avro v1.9.0/go.mod h1:X0fT1dY2xcbV4YuCE4mYro+qljHl4kUF5uA/2z1rgSk=
|
||||
github.com/twmb/murmur3 v1.1.8 h1:8Yt9taO/WN3l08xErzjeschgZU2QSrwm1kclYq+0aRg=
|
||||
github.com/twmb/murmur3 v1.1.8/go.mod h1:Qq/R7NUyOfr65zD+6Q5IHKsJLwP7exErjN6lyyq3OSQ=
|
||||
github.com/twpayne/go-geom v1.6.1 h1:iLE+Opv0Ihm/ABIcvQFGIiFBXd76oBIar9drAwHFhR4=
|
||||
@@ -2354,8 +2354,8 @@ golang.org/x/oauth2 v0.0.0-20221014153046-6fdb5e3db783/go.mod h1:h4gKUeWbJ4rQPri
|
||||
golang.org/x/oauth2 v0.4.0/go.mod h1:RznEsdpjGAINPTOF0UH/t+xJ75L18YO3Ho6Pyn+uRec=
|
||||
golang.org/x/oauth2 v0.5.0/go.mod h1:9/XBHVqLaWO3/BRHs5jbpYCnOZVjj5V0ndyaAM7KB4I=
|
||||
golang.org/x/oauth2 v0.6.0/go.mod h1:ycmewcwgD4Rpr3eZJLSB4Kyyljb3qDh40vJ8STE5HKw=
|
||||
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
|
||||
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
|
||||
golang.org/x/oauth2 v0.37.0 h1:JUlcxA8oAtauLfiH8FX2/FkAWHAdi0QtGCGc+hofE98=
|
||||
golang.org/x/oauth2 v0.37.0/go.mod h1:IxwZNxUULJmpBFf9K/9NTMSIfZZuvuTy1gGxhigP/58=
|
||||
golang.org/x/sync v0.0.0-20180314180146-1d60e4601c6f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
golang.org/x/sync v0.0.0-20181221193216-37e7f081c4d4/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.47"
|
||||
appVersion: "4.48"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.47.1
|
||||
version: 4.48.0
|
||||
@@ -25,6 +25,10 @@ spec:
|
||||
organizations:
|
||||
- "SeaweedFS CA"
|
||||
dnsNames:
|
||||
- '{{ include "seaweedfs.fullname" . }}-admin'
|
||||
- '{{ include "seaweedfs.fullname" . }}-admin.{{ .Release.Namespace }}'
|
||||
- '{{ include "seaweedfs.fullname" . }}-admin.{{ .Release.Namespace }}.svc'
|
||||
- '{{ include "seaweedfs.fullname" . }}-admin.{{ .Release.Namespace }}.svc.cluster.local'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-admin'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-admin.{{ .Release.Namespace }}'
|
||||
- '*.{{ include "seaweedfs.fullname" . }}-admin.{{ .Release.Namespace }}.svc'
|
||||
|
||||
+1005
-1009
File diff suppressed because it is too large.
Load diff
|
Before Width: | Height: | Size: 53 KiB After Width: | Height: | Size: 53 KiB |
@@ -168,6 +168,7 @@ message VacuumVolumeCheckRequest {
|
||||
}
|
||||
message VacuumVolumeCheckResponse {
|
||||
double garbage_ratio = 1;
|
||||
bool disk_space_low = 4; // the volume is read-only solely because its disk is low on space — a cause compaction itself reclaims
|
||||
}
|
||||
|
||||
message VacuumVolumeCompactRequest {
|
||||
@@ -475,6 +476,7 @@ message VolumeEcShardsDeleteRequest {
|
||||
repeated uint32 shard_ids = 3;
|
||||
bool full_teardown = 4; // pre-encode cleanup: wipe every EC artifact + generation for this volume, not just shard_ids
|
||||
int64 encode_ts_ns = 5; // full_teardown generation fence: delete only a disk whose .vif generation is strictly OLDER than this; preserve same-or-newer, generation 0, and an unreadable .vif. 0 => wipe-all (shell pre-encode / pre-upgrade)
|
||||
uint32 delete_generations_older_than = 6; // post-commit cleanup: delete only staged <base>.*.v<N> artifacts with N strictly below this; 0 disables
|
||||
}
|
||||
message VolumeEcShardsDeleteResponse {
|
||||
bool full_teardown_done = 1; // set by a new server that performed full_teardown; absent from an old server lets the caller detect the silent no-op
|
||||
|
||||
@@ -209,7 +209,7 @@ impl RemoteStorageClient for S3RemoteStorageClient {
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
pub(crate) mod tests {
|
||||
use super::*;
|
||||
use aws_sdk_s3::config::http::{HttpRequest, HttpResponse};
|
||||
use aws_sdk_s3::config::retry::RetryConfig;
|
||||
@@ -224,9 +224,9 @@ mod tests {
|
||||
/// so the error-mapping paths can be exercised without a network or a
|
||||
/// running S3 server.
|
||||
#[derive(Debug, Clone)]
|
||||
struct CannedResponse {
|
||||
status: u16,
|
||||
body: &'static str,
|
||||
pub(crate) struct CannedResponse {
|
||||
pub(crate) status: u16,
|
||||
pub(crate) body: &'static str,
|
||||
}
|
||||
|
||||
impl HttpConnector for CannedResponse {
|
||||
@@ -272,7 +272,7 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
const NO_SUCH_KEY: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
pub(crate) const NO_SUCH_KEY: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
<Error><Code>NoSuchKey</Code><Message>The specified key does not exist.</Message><Key>dir/missing</Key></Error>"#;
|
||||
|
||||
const NOT_FOUND_BODY: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
|
||||
|
||||
@@ -8,8 +8,11 @@ use std::future::Future;
|
||||
use std::sync::{Arc, OnceLock, RwLock};
|
||||
|
||||
use aws_sdk_s3::Client;
|
||||
use aws_sdk_s3::config::http::HttpResponse;
|
||||
use aws_sdk_s3::config::{BehaviorVersion, Credentials, Region};
|
||||
use aws_sdk_s3::error::DisplayErrorContext;
|
||||
use aws_sdk_s3::error::{DisplayErrorContext, SdkError};
|
||||
use aws_sdk_s3::operation::get_object::GetObjectError;
|
||||
use aws_sdk_s3::operation::head_object::HeadObjectError;
|
||||
use aws_sdk_s3::types::{CompletedMultipartUpload, CompletedPart};
|
||||
use tokio::io::{AsyncReadExt, AsyncSeekExt, AsyncWriteExt};
|
||||
use tokio::sync::Semaphore;
|
||||
@@ -17,6 +20,53 @@ use tokio::sync::Semaphore;
|
||||
/// Concurrency limit for multipart upload/download (matches Go's s3manager).
|
||||
const CONCURRENCY: usize = 5;
|
||||
|
||||
/// A tier transfer failure. The variant is what callers match on; the
|
||||
/// message is the operator-facing text.
|
||||
#[derive(Debug, thiserror::Error)]
|
||||
pub enum TierError {
|
||||
/// The remote object does not exist.
|
||||
#[error("{0}")]
|
||||
NotFound(String),
|
||||
/// An S3 request or a local file operation failed.
|
||||
#[error("{0}")]
|
||||
Io(String),
|
||||
/// The tier I/O runtime could not be built or dropped the task.
|
||||
#[error("{0}")]
|
||||
RuntimeUnavailable(String),
|
||||
/// The progress callback asked to stop.
|
||||
#[error("{0}")]
|
||||
Aborted(String),
|
||||
}
|
||||
|
||||
// Not-found rules as in remote_storage/s3.rs: HEAD by the raw 404 status,
|
||||
// GET by the NoSuchKey code only.
|
||||
fn head_object_error(key: &str, e: SdkError<HeadObjectError, HttpResponse>) -> TierError {
|
||||
let message = format!("failed to head object {}: {}", key, DisplayErrorContext(&e));
|
||||
match e {
|
||||
SdkError::ServiceError(ref se) if se.raw().status().as_u16() == 404 => {
|
||||
TierError::NotFound(message)
|
||||
}
|
||||
_ => TierError::Io(message),
|
||||
}
|
||||
}
|
||||
|
||||
fn get_object_error(
|
||||
key: &str,
|
||||
range: &str,
|
||||
e: SdkError<GetObjectError, HttpResponse>,
|
||||
) -> TierError {
|
||||
let message = format!(
|
||||
"failed to get object {} range {}: {}",
|
||||
key,
|
||||
range,
|
||||
DisplayErrorContext(&e)
|
||||
);
|
||||
match e {
|
||||
SdkError::ServiceError(ref se) if se.err().is_no_such_key() => TierError::NotFound(message),
|
||||
_ => TierError::Io(message),
|
||||
}
|
||||
}
|
||||
|
||||
/// Configuration for an S3 tier backend.
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct S3TierConfig {
|
||||
@@ -90,7 +140,7 @@ impl S3TierBackend {
|
||||
&self,
|
||||
file_path: &str,
|
||||
progress_fn: F,
|
||||
) -> Result<(String, u64), String>
|
||||
) -> Result<(String, u64), TierError>
|
||||
where
|
||||
F: FnMut(i64, f32) -> Result<(), String> + Send + Sync + 'static,
|
||||
{
|
||||
@@ -98,7 +148,7 @@ impl S3TierBackend {
|
||||
|
||||
let metadata = tokio::fs::metadata(file_path)
|
||||
.await
|
||||
.map_err(|e| format!("failed to stat file {}: {}", file_path, e))?;
|
||||
.map_err(|e| TierError::Io(format!("failed to stat file {}: {}", file_path, e)))?;
|
||||
let file_size = metadata.len();
|
||||
|
||||
// Calculate part size: start at 64MB, scale up for very large files (matches Go)
|
||||
@@ -121,15 +171,15 @@ impl S3TierBackend {
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
TierError::Io(format!(
|
||||
"failed to create multipart upload: {}",
|
||||
DisplayErrorContext(&e)
|
||||
)
|
||||
))
|
||||
})?;
|
||||
|
||||
let upload_id = create_resp
|
||||
.upload_id()
|
||||
.ok_or_else(|| "no upload_id in multipart upload response".to_string())?
|
||||
.ok_or_else(|| TierError::Io("no upload_id in multipart upload response".to_string()))?
|
||||
.to_string();
|
||||
|
||||
// Build list of (part_number, offset, size) for all parts
|
||||
@@ -165,19 +215,21 @@ impl S3TierBackend {
|
||||
let _permit = sem
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(|e| format!("semaphore error: {}", e))?;
|
||||
.map_err(|e| TierError::Io(format!("semaphore error: {}", e)))?;
|
||||
|
||||
// Read this part's data from the file at the correct offset
|
||||
let mut file = tokio::fs::File::open(&fp)
|
||||
.await
|
||||
.map_err(|e| format!("failed to open file {}: {}", fp, e))?;
|
||||
.map_err(|e| TierError::Io(format!("failed to open file {}: {}", fp, e)))?;
|
||||
file.seek(std::io::SeekFrom::Start(off))
|
||||
.await
|
||||
.map_err(|e| format!("failed to seek to offset {}: {}", off, e))?;
|
||||
.map_err(|e| {
|
||||
TierError::Io(format!("failed to seek to offset {}: {}", off, e))
|
||||
})?;
|
||||
let mut buf = vec![0u8; size];
|
||||
file.read_exact(&mut buf)
|
||||
.await
|
||||
.map_err(|e| format!("failed to read file at offset {}: {}", off, e))?;
|
||||
file.read_exact(&mut buf).await.map_err(|e| {
|
||||
TierError::Io(format!("failed to read file at offset {}: {}", off, e))
|
||||
})?;
|
||||
|
||||
let upload_part_resp = client
|
||||
.upload_part()
|
||||
@@ -189,12 +241,12 @@ impl S3TierBackend {
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
TierError::Io(format!(
|
||||
"failed to upload part {} at offset {}: {}",
|
||||
pn,
|
||||
off,
|
||||
DisplayErrorContext(&e)
|
||||
)
|
||||
))
|
||||
})?;
|
||||
|
||||
let e_tag = upload_part_resp.e_tag().unwrap_or_default().to_string();
|
||||
@@ -213,9 +265,9 @@ impl S3TierBackend {
|
||||
};
|
||||
(guard.1)(uploaded as i64, pct)
|
||||
};
|
||||
progress_result?;
|
||||
progress_result.map_err(TierError::Aborted)?;
|
||||
|
||||
Ok::<_, String>(
|
||||
Ok::<_, TierError>(
|
||||
CompletedPart::builder()
|
||||
.e_tag(e_tag)
|
||||
.part_number(pn)
|
||||
@@ -230,7 +282,7 @@ impl S3TierBackend {
|
||||
for handle in handles {
|
||||
let part = handle
|
||||
.await
|
||||
.map_err(|e| format!("upload task panicked: {}", e))??;
|
||||
.map_err(|e| TierError::Io(format!("upload task panicked: {}", e)))??;
|
||||
completed_parts.push(part);
|
||||
}
|
||||
|
||||
@@ -248,13 +300,13 @@ impl S3TierBackend {
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
TierError::Io(format!(
|
||||
"failed to complete multipart upload: {}",
|
||||
DisplayErrorContext(&e)
|
||||
)
|
||||
))
|
||||
})?;
|
||||
|
||||
Ok::<(), String>(())
|
||||
Ok::<(), TierError>(())
|
||||
}
|
||||
.await;
|
||||
|
||||
@@ -297,7 +349,7 @@ impl S3TierBackend {
|
||||
dest_path: &str,
|
||||
key: &str,
|
||||
progress_fn: F,
|
||||
) -> Result<u64, String>
|
||||
) -> Result<u64, TierError>
|
||||
where
|
||||
F: FnMut(i64, f32) -> Result<(), String> + Send + Sync + 'static,
|
||||
{
|
||||
@@ -309,7 +361,7 @@ impl S3TierBackend {
|
||||
.key(key)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| format!("failed to head object {}: {}", key, DisplayErrorContext(&e)))?;
|
||||
.map_err(|e| head_object_error(key, e))?;
|
||||
|
||||
let file_size = head_resp.content_length().unwrap_or(0) as u64;
|
||||
|
||||
@@ -321,10 +373,12 @@ impl S3TierBackend {
|
||||
.truncate(true)
|
||||
.open(dest_path)
|
||||
.await
|
||||
.map_err(|e| format!("failed to open dest file {}: {}", dest_path, e))?;
|
||||
.map_err(|e| {
|
||||
TierError::Io(format!("failed to open dest file {}: {}", dest_path, e))
|
||||
})?;
|
||||
file.set_len(file_size)
|
||||
.await
|
||||
.map_err(|e| format!("failed to set file length: {}", e))?;
|
||||
.map_err(|e| TierError::Io(format!("failed to set file length: {}", e)))?;
|
||||
}
|
||||
|
||||
let part_size: u64 = 64 * 1024 * 1024;
|
||||
@@ -360,7 +414,7 @@ impl S3TierBackend {
|
||||
let _permit = sem
|
||||
.acquire()
|
||||
.await
|
||||
.map_err(|e| format!("semaphore error: {}", e))?;
|
||||
.map_err(|e| TierError::Io(format!("semaphore error: {}", e)))?;
|
||||
|
||||
let end = off + size - 1;
|
||||
let range = format!("bytes={}-{}", off, end);
|
||||
@@ -372,20 +426,13 @@ impl S3TierBackend {
|
||||
.range(&range)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
"failed to get object {} range {}: {}",
|
||||
key,
|
||||
range,
|
||||
DisplayErrorContext(&e)
|
||||
)
|
||||
})?;
|
||||
.map_err(|e| get_object_error(&key, &range, e))?;
|
||||
|
||||
let body = get_resp
|
||||
.body
|
||||
.collect()
|
||||
.await
|
||||
.map_err(|e| format!("failed to read body: {}", e))?;
|
||||
.map_err(|e| TierError::Io(format!("failed to read body: {}", e)))?;
|
||||
let bytes = body.into_bytes();
|
||||
|
||||
// Write at the correct offset (like Go's WriteAt)
|
||||
@@ -393,13 +440,17 @@ impl S3TierBackend {
|
||||
.write(true)
|
||||
.open(&dp)
|
||||
.await
|
||||
.map_err(|e| format!("failed to open dest file {}: {}", dp, e))?;
|
||||
.map_err(|e| {
|
||||
TierError::Io(format!("failed to open dest file {}: {}", dp, e))
|
||||
})?;
|
||||
file.seek(std::io::SeekFrom::Start(off))
|
||||
.await
|
||||
.map_err(|e| format!("failed to seek to offset {}: {}", off, e))?;
|
||||
.map_err(|e| {
|
||||
TierError::Io(format!("failed to seek to offset {}: {}", off, e))
|
||||
})?;
|
||||
file.write_all(&bytes)
|
||||
.await
|
||||
.map_err(|e| format!("failed to write to {}: {}", dp, e))?;
|
||||
.map_err(|e| TierError::Io(format!("failed to write to {}: {}", dp, e)))?;
|
||||
|
||||
// Report progress. The lock is released before the result is
|
||||
// propagated so an aborting callback cannot poison the mutex
|
||||
@@ -415,9 +466,9 @@ impl S3TierBackend {
|
||||
};
|
||||
(guard.1)(downloaded as i64, pct)
|
||||
};
|
||||
progress_result?;
|
||||
progress_result.map_err(TierError::Aborted)?;
|
||||
|
||||
Ok::<_, String>(())
|
||||
Ok::<_, TierError>(())
|
||||
}));
|
||||
}
|
||||
|
||||
@@ -425,7 +476,7 @@ impl S3TierBackend {
|
||||
for handle in handles {
|
||||
handle
|
||||
.await
|
||||
.map_err(|e| format!("download task panicked: {}", e))??;
|
||||
.map_err(|e| TierError::Io(format!("download task panicked: {}", e)))??;
|
||||
}
|
||||
|
||||
// fsync the file so its content is durable before the caller trims the .vif
|
||||
@@ -434,16 +485,21 @@ impl S3TierBackend {
|
||||
.write(true)
|
||||
.open(dest_path)
|
||||
.await
|
||||
.map_err(|e| format!("failed to open {} for fsync: {}", dest_path, e))?;
|
||||
.map_err(|e| TierError::Io(format!("failed to open {} for fsync: {}", dest_path, e)))?;
|
||||
synced
|
||||
.sync_all()
|
||||
.await
|
||||
.map_err(|e| format!("failed to fsync {}: {}", dest_path, e))?;
|
||||
.map_err(|e| TierError::Io(format!("failed to fsync {}: {}", dest_path, e)))?;
|
||||
|
||||
Ok(file_size)
|
||||
}
|
||||
|
||||
pub async fn read_range(&self, key: &str, offset: u64, size: usize) -> Result<Vec<u8>, String> {
|
||||
pub async fn read_range(
|
||||
&self,
|
||||
key: &str,
|
||||
offset: u64,
|
||||
size: usize,
|
||||
) -> Result<Vec<u8>, TierError> {
|
||||
let end = offset + (size as u64).saturating_sub(1);
|
||||
let range = format!("bytes={}-{}", offset, end);
|
||||
let resp = self
|
||||
@@ -454,25 +510,18 @@ impl S3TierBackend {
|
||||
.range(&range)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
"failed to get object {} range {}: {}",
|
||||
key,
|
||||
range,
|
||||
DisplayErrorContext(&e)
|
||||
)
|
||||
})?;
|
||||
.map_err(|e| get_object_error(key, &range, e))?;
|
||||
|
||||
let body = resp
|
||||
.body
|
||||
.collect()
|
||||
.await
|
||||
.map_err(|e| format!("failed to read object {} body: {}", key, e))?;
|
||||
.map_err(|e| TierError::Io(format!("failed to read object {} body: {}", key, e)))?;
|
||||
Ok(body.into_bytes().to_vec())
|
||||
}
|
||||
|
||||
/// Delete a file from S3.
|
||||
pub async fn delete_file(&self, key: &str) -> Result<(), String> {
|
||||
pub async fn delete_file(&self, key: &str) -> Result<(), TierError> {
|
||||
self.client
|
||||
.delete_object()
|
||||
.bucket(&self.bucket)
|
||||
@@ -480,16 +529,16 @@ impl S3TierBackend {
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
TierError::Io(format!(
|
||||
"failed to delete object {}: {}",
|
||||
key,
|
||||
DisplayErrorContext(&e)
|
||||
)
|
||||
))
|
||||
})?;
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub fn delete_file_blocking(&self, key: &str) -> Result<(), String> {
|
||||
pub fn delete_file_blocking(&self, key: &str) -> Result<(), TierError> {
|
||||
let client = self.client.clone();
|
||||
let bucket = self.bucket.clone();
|
||||
let key = key.to_string();
|
||||
@@ -501,11 +550,11 @@ impl S3TierBackend {
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
TierError::Io(format!(
|
||||
"failed to delete object {}: {}",
|
||||
key,
|
||||
DisplayErrorContext(&e)
|
||||
)
|
||||
))
|
||||
})?;
|
||||
Ok(())
|
||||
})
|
||||
@@ -516,7 +565,7 @@ impl S3TierBackend {
|
||||
key: &str,
|
||||
offset: u64,
|
||||
size: usize,
|
||||
) -> Result<Vec<u8>, String> {
|
||||
) -> Result<Vec<u8>, TierError> {
|
||||
let client = self.client.clone();
|
||||
let bucket = self.bucket.clone();
|
||||
let key = key.to_string();
|
||||
@@ -530,20 +579,12 @@ impl S3TierBackend {
|
||||
.range(&range)
|
||||
.send()
|
||||
.await
|
||||
.map_err(|e| {
|
||||
format!(
|
||||
"failed to get object {} range {}: {}",
|
||||
key,
|
||||
range,
|
||||
DisplayErrorContext(&e)
|
||||
)
|
||||
})?;
|
||||
.map_err(|e| get_object_error(&key, &range, e))?;
|
||||
|
||||
let body = resp
|
||||
.body
|
||||
.collect()
|
||||
.await
|
||||
.map_err(|e| format!("failed to read object {} body: {}", key, e))?;
|
||||
let body =
|
||||
resp.body.collect().await.map_err(|e| {
|
||||
TierError::Io(format!("failed to read object {} body: {}", key, e))
|
||||
})?;
|
||||
Ok(body.into_bytes().to_vec())
|
||||
})
|
||||
}
|
||||
@@ -615,7 +656,7 @@ pub fn global_s3_tier_registry() -> &'static RwLock<S3TierRegistry> {
|
||||
static TIER_RUNTIME: std::sync::Mutex<Option<tokio::runtime::Runtime>> =
|
||||
std::sync::Mutex::new(None);
|
||||
|
||||
fn tier_handle() -> Result<tokio::runtime::Handle, String> {
|
||||
fn tier_handle() -> Result<tokio::runtime::Handle, TierError> {
|
||||
let mut slot = TIER_RUNTIME
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner());
|
||||
@@ -625,7 +666,12 @@ fn tier_handle() -> Result<tokio::runtime::Handle, String> {
|
||||
.thread_name("tier-io")
|
||||
.enable_all()
|
||||
.build()
|
||||
.map_err(|e| format!("failed to build the tier I/O tokio runtime: {}", e))?;
|
||||
.map_err(|e| {
|
||||
TierError::RuntimeUnavailable(format!(
|
||||
"failed to build the tier I/O tokio runtime: {}",
|
||||
e
|
||||
))
|
||||
})?;
|
||||
*slot = Some(runtime);
|
||||
}
|
||||
Ok(slot.as_ref().expect("just initialised").handle().clone())
|
||||
@@ -635,9 +681,9 @@ fn tier_handle() -> Result<tokio::runtime::Handle, String> {
|
||||
/// finishes. The caller may be a worker of *another* tokio runtime, so this
|
||||
/// waits on a channel rather than `Handle::block_on`, which panics when
|
||||
/// called from inside any runtime context.
|
||||
fn block_on_tier_future<F, T>(future: F) -> Result<T, String>
|
||||
fn block_on_tier_future<F, T>(future: F) -> Result<T, TierError>
|
||||
where
|
||||
F: Future<Output = Result<T, String>> + Send + 'static,
|
||||
F: Future<Output = Result<T, TierError>> + Send + 'static,
|
||||
T: Send + 'static,
|
||||
{
|
||||
let handle = tier_handle()?;
|
||||
@@ -651,13 +697,15 @@ where
|
||||
match rx.recv() {
|
||||
Ok(Ok(result)) => result,
|
||||
Ok(Err(join_error)) => Err(describe_join_error(join_error)),
|
||||
Err(_) => Err("tier I/O runtime dropped the task before it finished".to_string()),
|
||||
Err(_) => Err(TierError::RuntimeUnavailable(
|
||||
"tier I/O runtime dropped the task before it finished".to_string(),
|
||||
)),
|
||||
}
|
||||
}
|
||||
|
||||
/// Turn a `JoinError` into a message that keeps the panic payload, so an
|
||||
/// SDK panic surfaces as "boom" rather than a fixed "thread panicked".
|
||||
fn describe_join_error(join_error: tokio::task::JoinError) -> String {
|
||||
fn describe_join_error(join_error: tokio::task::JoinError) -> TierError {
|
||||
if join_error.is_panic() {
|
||||
let payload = join_error.into_panic();
|
||||
let message = if let Some(s) = payload.downcast_ref::<&str>() {
|
||||
@@ -667,19 +715,20 @@ fn describe_join_error(join_error: tokio::task::JoinError) -> String {
|
||||
} else {
|
||||
"non-string panic payload".to_string()
|
||||
};
|
||||
format!("tier I/O task panicked: {}", message)
|
||||
TierError::Io(format!("tier I/O task panicked: {}", message))
|
||||
} else {
|
||||
format!("tier I/O task failed: {}", join_error)
|
||||
TierError::RuntimeUnavailable(format!("tier I/O task failed: {}", join_error))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
use crate::remote_storage::s3::tests::{CannedResponse, NO_SUCH_KEY};
|
||||
use std::collections::HashSet;
|
||||
use tokio::runtime::Handle;
|
||||
|
||||
fn probe() -> Result<(tokio::runtime::Id, Option<String>), String> {
|
||||
fn probe() -> Result<(tokio::runtime::Id, Option<String>), TierError> {
|
||||
block_on_tier_future(async {
|
||||
Ok((
|
||||
Handle::current().id(),
|
||||
@@ -709,10 +758,12 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn block_on_tier_future_returns_the_value_and_the_error() {
|
||||
assert_eq!(block_on_tier_future(async { Ok(7u32) }), Ok(7));
|
||||
assert_eq!(
|
||||
block_on_tier_future::<_, u32>(async { Err("nope".to_string()) }),
|
||||
Err("nope".to_string())
|
||||
assert_eq!(block_on_tier_future(async { Ok(7u32) }).unwrap(), 7);
|
||||
let err = block_on_tier_future::<_, u32>(async { Err(TierError::NotFound("nope".into())) })
|
||||
.unwrap_err();
|
||||
assert!(
|
||||
matches!(&err, TierError::NotFound(m) if m == "nope"),
|
||||
"{err:?}"
|
||||
);
|
||||
}
|
||||
|
||||
@@ -761,8 +812,9 @@ mod tests {
|
||||
Ok(())
|
||||
})
|
||||
.expect_err("a panicking future must be an error");
|
||||
assert!(err.contains("boom 42"), "got: {err}");
|
||||
assert!(err.contains("panicked"), "got: {err}");
|
||||
assert!(matches!(err, TierError::Io(_)), "got: {err:?}");
|
||||
assert!(err.to_string().contains("boom 42"), "got: {err}");
|
||||
assert!(err.to_string().contains("panicked"), "got: {err}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -774,7 +826,83 @@ mod tests {
|
||||
Ok(())
|
||||
})
|
||||
.expect_err("a panicking future must be an error");
|
||||
assert!(err.contains("static boom"), "got: {err}");
|
||||
assert!(err.to_string().contains("static boom"), "got: {err}");
|
||||
}
|
||||
|
||||
fn backend_answering(status: u16, body: &'static str) -> S3TierBackend {
|
||||
let config = aws_sdk_s3::Config::builder()
|
||||
.behavior_version(BehaviorVersion::latest())
|
||||
.region(Region::new("us-east-1"))
|
||||
.credentials_provider(Credentials::new("AKIATEST", "secret", None, None, "test"))
|
||||
.endpoint_url("http://127.0.0.1:1")
|
||||
.force_path_style(true)
|
||||
.http_client(CannedResponse { status, body })
|
||||
.retry_config(aws_sdk_s3::config::retry::RetryConfig::disabled())
|
||||
.build();
|
||||
S3TierBackend {
|
||||
client: Client::from_conf(config),
|
||||
bucket: "bucket".to_string(),
|
||||
storage_class: "STANDARD".to_string(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_head_404_is_not_found() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dest = tmp.path().join("1.dat");
|
||||
let err = backend_answering(404, "")
|
||||
.download_file(dest.to_str().unwrap(), "missing", |_, _| Ok(()))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, TierError::NotFound(_)), "{err:?}");
|
||||
assert!(
|
||||
err.to_string()
|
||||
.starts_with("failed to head object missing: "),
|
||||
"{err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn download_head_403_is_io() {
|
||||
let tmp = tempfile::tempdir().unwrap();
|
||||
let dest = tmp.path().join("1.dat");
|
||||
let err = backend_answering(403, "")
|
||||
.download_file(dest.to_str().unwrap(), "denied", |_, _| Ok(()))
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, TierError::Io(_)), "{err:?}");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_range_no_such_key_is_not_found() {
|
||||
let err = backend_answering(404, NO_SUCH_KEY)
|
||||
.read_range("missing", 0, 8)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, TierError::NotFound(_)), "{err:?}");
|
||||
assert!(
|
||||
err.to_string()
|
||||
.starts_with("failed to get object missing range bytes=0-7: "),
|
||||
"{err}"
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn read_range_bare_404_is_io() {
|
||||
// As in Go, GET is not-found by the NoSuchKey code, not the status.
|
||||
let err = backend_answering(404, "")
|
||||
.read_range("missing", 0, 8)
|
||||
.await
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, TierError::Io(_)), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_range_blocking_no_such_key_is_not_found() {
|
||||
let err = backend_answering(404, NO_SUCH_KEY)
|
||||
.read_range_blocking("missing", 0, 8)
|
||||
.unwrap_err();
|
||||
assert!(matches!(err, TierError::NotFound(_)), "{err:?}");
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -143,6 +143,78 @@ const STREAMING_THRESHOLD: u32 = 1024 * 1024; // 1 MB
|
||||
/// Default chunk size for streaming reads from the dat file.
|
||||
const DEFAULT_STREAMING_CHUNK_SIZE: usize = 64 * 1024; // 64 KB
|
||||
|
||||
/// Whether a GET/HEAD can be answered from the needle meta and the data file.
|
||||
#[derive(Clone, Copy)]
|
||||
struct SourceReadRequest {
|
||||
is_head: bool,
|
||||
has_range: bool,
|
||||
has_image_ops: bool,
|
||||
bypass_cm: bool,
|
||||
}
|
||||
|
||||
impl SourceReadRequest {
|
||||
/// The payload can be served as stored.
|
||||
fn direct(&self, n: &Needle) -> bool {
|
||||
!n.is_compressed() && !(n.is_chunk_manifest() && !self.bypass_cm) && !self.has_image_ops
|
||||
}
|
||||
|
||||
/// HEAD, a range, or a stream.
|
||||
fn served_from_source(&self, n: &Needle) -> bool {
|
||||
self.is_head || (self.direct(n) && (self.has_range || n.data_size > STREAMING_THRESHOLD))
|
||||
}
|
||||
|
||||
/// Meta first only if the needle could be served from source; its data
|
||||
/// size is below its index size.
|
||||
fn try_meta_first(&self, size: Size) -> bool {
|
||||
self.is_head
|
||||
|| (!self.has_image_ops && (self.has_range || size.0 > STREAMING_THRESHOLD as i32))
|
||||
}
|
||||
}
|
||||
|
||||
/// Blocking part of a GET/HEAD: the store guard is dropped before any needle
|
||||
/// I/O, so a slow or tiered read cannot park store writers. `Ok(None)` is a
|
||||
/// cookie mismatch.
|
||||
fn read_needle_for_get(
|
||||
state: &VolumeServerState,
|
||||
vid: VolumeId,
|
||||
needle_id: NeedleId,
|
||||
cookie: Cookie,
|
||||
read_deleted: bool,
|
||||
request: SourceReadRequest,
|
||||
) -> Result<
|
||||
Option<(Needle, Option<crate::storage::volume::NeedleStreamInfo>)>,
|
||||
crate::storage::volume::VolumeError,
|
||||
> {
|
||||
let mut plan = state
|
||||
.store
|
||||
.read()
|
||||
.unwrap()
|
||||
.needle_read_plan(vid, needle_id, read_deleted)?;
|
||||
let blank = || Needle {
|
||||
id: needle_id,
|
||||
cookie,
|
||||
..Needle::default()
|
||||
};
|
||||
let mut n = blank();
|
||||
if request.try_meta_first(plan.size()) {
|
||||
plan.read_meta(&mut n)?;
|
||||
if n.cookie != cookie {
|
||||
return Ok(None);
|
||||
}
|
||||
if request.served_from_source(&n) {
|
||||
let info = plan.into_stream_info(&n);
|
||||
return Ok(Some((n, Some(info))));
|
||||
}
|
||||
// Compressed or a chunk manifest: the payload is needed after all.
|
||||
n = blank();
|
||||
}
|
||||
plan.read_full(&mut n)?;
|
||||
if n.cookie != cookie {
|
||||
return Ok(None);
|
||||
}
|
||||
Ok(Some((n, None)))
|
||||
}
|
||||
|
||||
/// A body that streams needle data from the dat file in chunks using pread,
|
||||
/// avoiding loading the entire payload into memory at once.
|
||||
struct StreamingBody {
|
||||
@@ -878,7 +950,7 @@ async fn proxy_request(
|
||||
if name.as_str().eq_ignore_ascii_case("server") {
|
||||
continue;
|
||||
}
|
||||
response_headers.insert(name.clone(), value.clone());
|
||||
response_headers.append(name.clone(), value.clone());
|
||||
}
|
||||
|
||||
// Stream the proxy response body instead of buffering it entirely
|
||||
@@ -1112,11 +1184,7 @@ async fn get_or_head_handler_inner(
|
||||
|
||||
// Read needle — branching between regular volume and EC volume paths.
|
||||
// EC volumes always do a full read (no streaming/meta-only).
|
||||
let mut n = Needle {
|
||||
id: needle_id,
|
||||
cookie,
|
||||
..Needle::default()
|
||||
};
|
||||
let n: Needle;
|
||||
|
||||
let read_deleted = query.read_deleted.as_deref() == Some("true");
|
||||
let has_range = headers.contains_key(header::RANGE);
|
||||
@@ -1193,24 +1261,49 @@ async fn get_or_head_handler_inner(
|
||||
can_handle_range_from_source = false;
|
||||
} else {
|
||||
// ---- Regular volume read path (with streaming support) ----
|
||||
bypass_cm = query.cm.as_deref() == Some("false");
|
||||
track_download = download_guard.is_some();
|
||||
let request_kind = SourceReadRequest {
|
||||
is_head: method == Method::HEAD,
|
||||
has_range,
|
||||
has_image_ops,
|
||||
bypass_cm,
|
||||
};
|
||||
|
||||
// Try meta-only read first for potential streaming
|
||||
let store = state.store.read().unwrap();
|
||||
let si_result = store.read_volume_needle_stream_info(vid, &mut n, read_deleted);
|
||||
stream_info = match si_result {
|
||||
Ok(info) => Some(info),
|
||||
Err(crate::storage::volume::VolumeError::StreamingUnsupported) => None,
|
||||
Err(crate::storage::volume::VolumeError::NotFound) => {
|
||||
let read_state = state.clone();
|
||||
let read = tokio::task::spawn_blocking(move || {
|
||||
read_needle_for_get(
|
||||
&read_state,
|
||||
vid,
|
||||
needle_id,
|
||||
cookie,
|
||||
read_deleted,
|
||||
request_kind,
|
||||
)
|
||||
})
|
||||
.await;
|
||||
(n, stream_info) = match read {
|
||||
Ok(Ok(Some(found))) => found,
|
||||
// Cookie mismatch
|
||||
Ok(Ok(None)) => return StatusCode::NOT_FOUND.into_response(),
|
||||
Ok(Err(
|
||||
crate::storage::volume::VolumeError::NotFound
|
||||
| crate::storage::volume::VolumeError::Deleted,
|
||||
)) => {
|
||||
metrics::HANDLER_COUNTER
|
||||
.with_label_values(&[metrics::ERROR_GET_NOT_FOUND])
|
||||
.inc();
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
}
|
||||
Err(crate::storage::volume::VolumeError::Deleted) => {
|
||||
Ok(Err(e)) => {
|
||||
metrics::HANDLER_COUNTER
|
||||
.with_label_values(&[metrics::ERROR_GET_NOT_FOUND])
|
||||
.with_label_values(&[metrics::ERROR_GET_INTERNAL])
|
||||
.inc();
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("read error: {}", e),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
Err(e) => {
|
||||
metrics::HANDLER_COUNTER
|
||||
@@ -1223,19 +1316,9 @@ async fn get_or_head_handler_inner(
|
||||
.into_response();
|
||||
}
|
||||
};
|
||||
drop(store);
|
||||
|
||||
// Validate cookie
|
||||
if n.cookie != cookie {
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
}
|
||||
|
||||
bypass_cm = query.cm.as_deref() == Some("false");
|
||||
track_download = download_guard.is_some();
|
||||
let can_direct_source_read = stream_info.is_some()
|
||||
&& !n.is_compressed()
|
||||
&& !(n.is_chunk_manifest() && !bypass_cm)
|
||||
&& !has_image_ops;
|
||||
// Stream info is only returned for a reply served from the data file.
|
||||
let can_direct_source_read = stream_info.is_some() && request_kind.direct(&n);
|
||||
|
||||
// Determine if we can stream (large, direct-source eligible, no range)
|
||||
can_stream = can_direct_source_read
|
||||
@@ -1246,41 +1329,6 @@ async fn get_or_head_handler_inner(
|
||||
// Go uses meta-only reads for all HEAD requests, regardless of compression/chunked files.
|
||||
can_handle_head_from_meta = stream_info.is_some() && method == Method::HEAD;
|
||||
can_handle_range_from_source = can_direct_source_read && has_range;
|
||||
|
||||
// For chunk manifest or any non-streaming path, we need the full data.
|
||||
// If we can't stream, do a full read now.
|
||||
if !can_stream && !can_handle_head_from_meta && !can_handle_range_from_source {
|
||||
// Re-read with full data
|
||||
let mut n_full = Needle {
|
||||
id: needle_id,
|
||||
cookie,
|
||||
..Needle::default()
|
||||
};
|
||||
let store = state.store.read().unwrap();
|
||||
match store.read_volume_needle_opt(vid, &mut n_full, read_deleted) {
|
||||
Ok(count) => {
|
||||
if count < 0 {
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
}
|
||||
}
|
||||
Err(crate::storage::volume::VolumeError::NotFound) => {
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
}
|
||||
Err(crate::storage::volume::VolumeError::Deleted) => {
|
||||
return StatusCode::NOT_FOUND.into_response();
|
||||
}
|
||||
Err(e) => {
|
||||
return (
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("read error: {}", e),
|
||||
)
|
||||
.into_response();
|
||||
}
|
||||
}
|
||||
drop(store);
|
||||
// Use the full needle from here (it has the same metadata + data)
|
||||
n = n_full;
|
||||
}
|
||||
}
|
||||
|
||||
// Build ETag and Last-Modified BEFORE conditional checks and chunk manifest expansion
|
||||
@@ -1565,12 +1613,19 @@ async fn get_or_head_handler_inner(
|
||||
&& let (Some(range_header), Some(info)) = (headers.get(header::RANGE), stream_info)
|
||||
&& let Ok(range_str) = range_header.to_str()
|
||||
{
|
||||
return handle_range_request_from_source(
|
||||
range_str,
|
||||
info,
|
||||
response_headers,
|
||||
track_download.then(|| state.clone()),
|
||||
);
|
||||
let range_str = range_str.to_string();
|
||||
let tracking = track_download.then(|| state.clone());
|
||||
return tokio::task::spawn_blocking(move || {
|
||||
handle_range_request_from_source(&range_str, info, response_headers, tracking)
|
||||
})
|
||||
.await
|
||||
.unwrap_or_else(|e| {
|
||||
(
|
||||
StatusCode::INTERNAL_SERVER_ERROR,
|
||||
format!("range read error: {}", e),
|
||||
)
|
||||
.into_response()
|
||||
});
|
||||
}
|
||||
|
||||
// ---- Buffered path: small files, compressed, images, range requests ----
|
||||
@@ -4616,16 +4671,78 @@ mod tests {
|
||||
server.abort();
|
||||
}
|
||||
|
||||
/// Repeated target response headers (e.g. Set-Cookie) must all reach the
|
||||
/// client, as Go's `w.Header().Add` does; only `Server` is dropped.
|
||||
#[tokio::test]
|
||||
async fn test_proxy_request_keeps_repeated_response_headers() {
|
||||
use axum::{Router, routing::get};
|
||||
|
||||
let app = Router::new().route(
|
||||
"/3,01637037d6",
|
||||
get(|| async {
|
||||
(
|
||||
axum::response::AppendHeaders([
|
||||
(header::SET_COOKIE, "a=1"),
|
||||
(header::SET_COOKIE, "b=2"),
|
||||
(header::SERVER, "target"),
|
||||
]),
|
||||
"payload",
|
||||
)
|
||||
}),
|
||||
);
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
let server = tokio::spawn(async move {
|
||||
axum::serve(listener, app).await.unwrap();
|
||||
});
|
||||
|
||||
let info = ProxyRequestInfo {
|
||||
original_headers: HeaderMap::new(),
|
||||
original_query: String::new(),
|
||||
path: "/3,01637037d6".to_string(),
|
||||
vid_str: "3".to_string(),
|
||||
fid_str: "01637037d6".to_string(),
|
||||
};
|
||||
let target = VolumeLocation {
|
||||
url: addr.to_string(),
|
||||
public_url: String::new(),
|
||||
grpc_port: 0,
|
||||
read_only: false,
|
||||
read_only_can_delete: false,
|
||||
};
|
||||
|
||||
let response = proxy_request(&streaming_test_state(), &info, &target).await;
|
||||
assert_eq!(response.status(), StatusCode::OK);
|
||||
let cookies: Vec<_> = response
|
||||
.headers()
|
||||
.get_all(header::SET_COOKIE)
|
||||
.iter()
|
||||
.map(|v| v.to_str().unwrap().to_string())
|
||||
.collect();
|
||||
assert_eq!(cookies, vec!["a=1", "b=2"]);
|
||||
assert!(response.headers().get(header::SERVER).is_none());
|
||||
let body = axum::body::to_bytes(response.into_body(), usize::MAX)
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(&body[..], b"payload");
|
||||
|
||||
server.abort();
|
||||
}
|
||||
|
||||
fn streaming_test_state() -> Arc<VolumeServerState> {
|
||||
use crate::security::{Guard, SigningKey};
|
||||
use crate::server::volume_server::RuntimeMetricsConfig;
|
||||
use crate::storage::needle_map::NeedleMapKind;
|
||||
use crate::storage::store::Store;
|
||||
test_state_with_store(Store::new(NeedleMapKind::InMemory))
|
||||
}
|
||||
|
||||
fn test_state_with_store(store: crate::storage::store::Store) -> Arc<VolumeServerState> {
|
||||
use crate::security::{Guard, SigningKey};
|
||||
use crate::server::volume_server::RuntimeMetricsConfig;
|
||||
use std::sync::RwLock;
|
||||
use std::sync::atomic::{AtomicBool, AtomicI64, AtomicU32};
|
||||
|
||||
Arc::new(VolumeServerState {
|
||||
store: RwLock::new(Store::new(NeedleMapKind::InMemory)),
|
||||
store: RwLock::new(store),
|
||||
guard: RwLock::new(Guard::new(
|
||||
&[],
|
||||
SigningKey(vec![]),
|
||||
@@ -4738,4 +4855,278 @@ mod tests {
|
||||
assert!(saw_err, "corrupted stream must fail");
|
||||
assert!(got < data.len(), "delivered {got} of {} bytes", data.len());
|
||||
}
|
||||
|
||||
const TEST_COOKIE: u32 = 0x1234_5678;
|
||||
|
||||
/// State whose store holds volume 1 in `tmp`.
|
||||
fn volume_test_state(tmp: &tempfile::TempDir) -> Arc<VolumeServerState> {
|
||||
use crate::storage::needle_map::NeedleMapKind;
|
||||
use crate::storage::store::Store;
|
||||
use crate::storage::volume::VolumeSpec;
|
||||
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut store = Store::new(NeedleMapKind::InMemory);
|
||||
store
|
||||
.add_location(
|
||||
dir,
|
||||
dir,
|
||||
10,
|
||||
DiskType::HardDrive,
|
||||
crate::config::MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
store
|
||||
.add_volume(VolumeId(1), DiskType::HardDrive, &VolumeSpec::default())
|
||||
.unwrap();
|
||||
test_state_with_store(store)
|
||||
}
|
||||
|
||||
/// Write a needle to volume 1 and return its URL path.
|
||||
fn put_test_needle(state: &VolumeServerState, id: u64, data: &[u8]) -> String {
|
||||
put_test_needle_with(state, id, data, |_| {})
|
||||
}
|
||||
|
||||
fn put_test_needle_with(
|
||||
state: &VolumeServerState,
|
||||
id: u64,
|
||||
data: &[u8],
|
||||
prepare: impl FnOnce(&mut Needle),
|
||||
) -> String {
|
||||
let mut n = Needle {
|
||||
id: NeedleId(id),
|
||||
cookie: Cookie(TEST_COOKIE),
|
||||
data: data.to_vec(),
|
||||
data_size: data.len() as u32,
|
||||
..Needle::default()
|
||||
};
|
||||
prepare(&mut n);
|
||||
state
|
||||
.store
|
||||
.write()
|
||||
.unwrap()
|
||||
.write_volume_needle(VolumeId(1), &mut n, false)
|
||||
.unwrap();
|
||||
format!("/1,{:x}{:08x}", id, TEST_COOKIE)
|
||||
}
|
||||
|
||||
async fn send_read(
|
||||
state: &Arc<VolumeServerState>,
|
||||
method: Method,
|
||||
path: &str,
|
||||
range: Option<&str>,
|
||||
) -> (StatusCode, HeaderMap, Vec<u8>) {
|
||||
use tower::ServiceExt;
|
||||
let mut req = Request::builder().method(method).uri(path);
|
||||
if let Some(range) = range {
|
||||
req = req.header(header::RANGE, range);
|
||||
}
|
||||
let resp = super::super::volume_server::build_public_router(state.clone())
|
||||
.oneshot(req.body(Body::empty()).unwrap())
|
||||
.await
|
||||
.unwrap();
|
||||
let status = resp.status();
|
||||
let headers = resp.headers().clone();
|
||||
let body = axum::body::to_bytes(resp.into_body(), usize::MAX)
|
||||
.await
|
||||
.unwrap()
|
||||
.to_vec();
|
||||
(status, headers, body)
|
||||
}
|
||||
|
||||
/// A GET whose needle read is parked must not hold the store lock: a
|
||||
/// writer, here a real append to the same volume, must get through.
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
||||
async fn test_get_needle_read_runs_off_the_store_lock() {
|
||||
use crate::storage::volume::needle_read_hook;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::mpsc;
|
||||
use std::time::Duration;
|
||||
|
||||
const ID: u64 = 0x6e7a_0001;
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let state = volume_test_state(&tmp);
|
||||
let data = b"parked needle".to_vec();
|
||||
let path = put_test_needle(&state, ID, &data);
|
||||
|
||||
let (entered_tx, entered_rx) = mpsc::channel::<()>();
|
||||
let (release_tx, release_rx) = mpsc::channel::<()>();
|
||||
let release_rx = Mutex::new(release_rx);
|
||||
let _hook = needle_read_hook::register(NeedleId(ID), move |_| {
|
||||
let _ = entered_tx.send(());
|
||||
// Returns once released, or at once when the sender is gone.
|
||||
let _ = release_rx.lock().unwrap().recv();
|
||||
});
|
||||
|
||||
let get = tokio::spawn({
|
||||
let state = state.clone();
|
||||
async move { send_read(&state, Method::GET, &path, None).await }
|
||||
});
|
||||
tokio::task::spawn_blocking(move || entered_rx.recv_timeout(Duration::from_secs(10)))
|
||||
.await
|
||||
.unwrap()
|
||||
.expect("the GET never reached its needle read");
|
||||
|
||||
let try_write_ok = state.store.try_write().is_ok();
|
||||
let (wrote_tx, wrote_rx) = mpsc::channel();
|
||||
std::thread::spawn({
|
||||
let state = state.clone();
|
||||
move || {
|
||||
put_test_needle(&state, ID + 1, b"written meanwhile");
|
||||
let _ = wrote_tx.send(());
|
||||
}
|
||||
});
|
||||
let write_done = tokio::task::spawn_blocking(move || {
|
||||
wrote_rx.recv_timeout(Duration::from_secs(5)).is_ok()
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
drop(release_tx);
|
||||
|
||||
assert!(
|
||||
try_write_ok,
|
||||
"a parked GET read must not hold the store lock"
|
||||
);
|
||||
assert!(write_done, "an append must not wait for a parked GET read");
|
||||
let (status, _, body) = get.await.unwrap();
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(body, data);
|
||||
}
|
||||
|
||||
/// A small needle is read from disk once, not once for its meta and
|
||||
/// again in full; a large one never reads its payload before streaming.
|
||||
#[tokio::test]
|
||||
async fn test_get_reads_small_needle_once_and_large_needle_meta_only() {
|
||||
use crate::storage::volume::needle_read_hook;
|
||||
use std::sync::Mutex;
|
||||
|
||||
const SMALL: u64 = 0x6e7a_0101;
|
||||
const LARGE: u64 = 0x6e7a_0102;
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let state = volume_test_state(&tmp);
|
||||
let small = b"small needle".to_vec();
|
||||
let large: Vec<u8> = (0..(STREAMING_THRESHOLD as usize + 4096))
|
||||
.map(|i| (i % 251) as u8)
|
||||
.collect();
|
||||
let small_path = put_test_needle(&state, SMALL, &small);
|
||||
let large_path = put_test_needle(&state, LARGE, &large);
|
||||
|
||||
let small_reads = Arc::new(Mutex::new(Vec::new()));
|
||||
let large_reads = Arc::new(Mutex::new(Vec::new()));
|
||||
let _small_hook = needle_read_hook::register(NeedleId(SMALL), {
|
||||
let reads = small_reads.clone();
|
||||
move |len| reads.lock().unwrap().push(len)
|
||||
});
|
||||
let _large_hook = needle_read_hook::register(NeedleId(LARGE), {
|
||||
let reads = large_reads.clone();
|
||||
move |len| reads.lock().unwrap().push(len)
|
||||
});
|
||||
|
||||
let (status, _, body) = send_read(&state, Method::GET, &small_path, None).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(body, small);
|
||||
let reads = small_reads.lock().unwrap().clone();
|
||||
assert_eq!(reads.len(), 1, "reads of the small needle: {reads:?}");
|
||||
|
||||
let (status, _, body) = send_read(&state, Method::GET, &large_path, None).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(body, large);
|
||||
let reads = large_reads.lock().unwrap().clone();
|
||||
assert!(
|
||||
!reads.is_empty() && reads.iter().all(|&len| len < 64 * 1024),
|
||||
"the large needle's payload must not be read before streaming: {reads:?}"
|
||||
);
|
||||
}
|
||||
|
||||
/// HEAD and ranged reads keep answering from the needle meta and the
|
||||
/// data file, and a missing or wrong-cookie needle is still a 404.
|
||||
#[tokio::test]
|
||||
async fn test_get_head_range_and_not_found_after_single_read() {
|
||||
const ID: u64 = 0x6e7a_0201;
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let state = volume_test_state(&tmp);
|
||||
let data: Vec<u8> = (0..4096u32).map(|i| (i % 251) as u8).collect();
|
||||
let path = put_test_needle(&state, ID, &data);
|
||||
|
||||
let (status, headers, body) = send_read(&state, Method::HEAD, &path, None).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert!(body.is_empty());
|
||||
assert_eq!(headers[header::CONTENT_LENGTH], data.len().to_string());
|
||||
assert!(headers.contains_key(header::ETAG));
|
||||
|
||||
let (status, headers, body) =
|
||||
send_read(&state, Method::GET, &path, Some("bytes=10-19")).await;
|
||||
assert_eq!(status, StatusCode::PARTIAL_CONTENT);
|
||||
assert_eq!(body, &data[10..20]);
|
||||
assert_eq!(
|
||||
headers["Content-Range"],
|
||||
format!("bytes 10-19/{}", data.len())
|
||||
);
|
||||
|
||||
let wrong_cookie = format!("/1,{:x}{:08x}", ID, TEST_COOKIE ^ 1);
|
||||
let (status, _, _) = send_read(&state, Method::GET, &wrong_cookie, None).await;
|
||||
assert_eq!(status, StatusCode::NOT_FOUND);
|
||||
let missing = format!("/1,{:x}{:08x}", ID + 1, TEST_COOKIE);
|
||||
let (status, _, _) = send_read(&state, Method::GET, &missing, None).await;
|
||||
assert_eq!(status, StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
/// A large compressed needle cannot be streamed as stored: its meta is
|
||||
/// read first, then the payload exactly once.
|
||||
#[tokio::test]
|
||||
async fn test_get_large_compressed_needle_reads_payload_once() {
|
||||
use crate::storage::volume::needle_read_hook;
|
||||
use std::sync::Mutex;
|
||||
|
||||
const ID: u64 = 0x6e7a_0301;
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let state = volume_test_state(&tmp);
|
||||
// Incompressible, so the stored gzip stays above the stream threshold.
|
||||
let mut x = 0x2545_f491_u32;
|
||||
let plain: Vec<u8> = (0..(STREAMING_THRESHOLD as usize + 64 * 1024))
|
||||
.map(|_| {
|
||||
x ^= x << 13;
|
||||
x ^= x >> 17;
|
||||
x ^= x << 5;
|
||||
x as u8
|
||||
})
|
||||
.collect();
|
||||
let gz = try_gzip_data(&plain).unwrap();
|
||||
assert!(gz.len() > STREAMING_THRESHOLD as usize);
|
||||
let path = put_test_needle_with(&state, ID, &gz, |n| n.set_is_compressed());
|
||||
|
||||
let reads = Arc::new(Mutex::new(Vec::new()));
|
||||
let _hook = needle_read_hook::register(NeedleId(ID), {
|
||||
let reads = reads.clone();
|
||||
move |len| reads.lock().unwrap().push(len)
|
||||
});
|
||||
let (status, _, body) = send_read(&state, Method::GET, &path, None).await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
assert_eq!(body, plain);
|
||||
let reads = reads.lock().unwrap().clone();
|
||||
let full = reads.iter().filter(|&&len| len >= gz.len()).count();
|
||||
assert_eq!(full, 1, "reads: {reads:?}");
|
||||
}
|
||||
|
||||
/// The single full read still verifies the needle checksum.
|
||||
#[tokio::test]
|
||||
async fn test_get_small_needle_with_bad_checksum_fails() {
|
||||
const ID: u64 = 0x6e7a_0401;
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let state = volume_test_state(&tmp);
|
||||
let data = b"checksummed payload, to be corrupted".to_vec();
|
||||
let path = put_test_needle(&state, ID, &data);
|
||||
|
||||
let dat = tmp.path().join("1.dat");
|
||||
let mut bytes = std::fs::read(&dat).unwrap();
|
||||
let at = bytes
|
||||
.windows(data.len())
|
||||
.position(|w| w == data.as_slice())
|
||||
.unwrap();
|
||||
bytes[at] ^= 0xff;
|
||||
std::fs::write(&dat, bytes).unwrap();
|
||||
|
||||
let (status, _, _) = send_read(&state, Method::GET, &path, None).await;
|
||||
assert_eq!(status, StatusCode::INTERNAL_SERVER_ERROR);
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1,5 +1,6 @@
|
||||
use tonic::Status;
|
||||
|
||||
use crate::remote_storage::s3_tier::TierError;
|
||||
use crate::storage::volume::VolumeError;
|
||||
|
||||
#[cfg(unix)]
|
||||
@@ -23,8 +24,12 @@ impl From<VolumeError> for Status {
|
||||
fn from(err: VolumeError) -> Self {
|
||||
let message = err.to_string();
|
||||
match err {
|
||||
VolumeError::NotFound | VolumeError::VolumeNotFound(_) => Status::not_found(message),
|
||||
VolumeError::ReadOnly | VolumeError::NotEmpty => Status::failed_precondition(message),
|
||||
VolumeError::NotFound
|
||||
| VolumeError::VolumeNotFound(_)
|
||||
| VolumeError::Tier(TierError::NotFound(_)) => Status::not_found(message),
|
||||
VolumeError::ReadOnly(_) | VolumeError::NotEmpty => {
|
||||
Status::failed_precondition(message)
|
||||
}
|
||||
VolumeError::InsufficientSpace { .. } => Status::resource_exhausted(message),
|
||||
VolumeError::AlreadyExists => Status::already_exists(message),
|
||||
_ => Status::internal(message),
|
||||
@@ -66,7 +71,14 @@ mod tests {
|
||||
Code::NotFound
|
||||
);
|
||||
assert_eq!(code(VolumeError::NotFound), Code::NotFound);
|
||||
assert_eq!(code(VolumeError::ReadOnly), Code::FailedPrecondition);
|
||||
assert_eq!(
|
||||
code(VolumeError::ReadOnly(VolumeId(7))),
|
||||
Code::FailedPrecondition
|
||||
);
|
||||
assert_eq!(
|
||||
VolumeError::ReadOnly(VolumeId(7)).to_string(),
|
||||
"volume 7 is read only"
|
||||
);
|
||||
assert_eq!(
|
||||
code(VolumeError::InsufficientSpace {
|
||||
vid: VolumeId(7),
|
||||
@@ -77,6 +89,27 @@ mod tests {
|
||||
);
|
||||
assert_eq!(code(VolumeError::AlreadyExists), Code::AlreadyExists);
|
||||
assert_eq!(code(VolumeError::NotInitialized), Code::Internal);
|
||||
assert_eq!(
|
||||
code(TierError::NotFound("gone".into()).into()),
|
||||
Code::NotFound
|
||||
);
|
||||
for tier in [
|
||||
TierError::Io("io".into()),
|
||||
TierError::RuntimeUnavailable("rt".into()),
|
||||
TierError::Aborted("bye".into()),
|
||||
] {
|
||||
assert_eq!(code(tier.into()), Code::Internal);
|
||||
}
|
||||
|
||||
let status = status_with_context(
|
||||
"backend s3.default copy file /data/1.dat",
|
||||
TierError::NotFound("failed to head object k: NotFound".into()).into(),
|
||||
);
|
||||
assert_eq!(status.code(), Code::NotFound);
|
||||
assert_eq!(
|
||||
status.message(),
|
||||
"backend s3.default copy file /data/1.dat: failed to head object k: NotFound"
|
||||
);
|
||||
|
||||
let status = status_with_context(
|
||||
"compact volume 7",
|
||||
|
||||
@@ -95,20 +95,41 @@ struct Snapshot {
|
||||
encode_ts_ns: i64,
|
||||
}
|
||||
|
||||
/// Top-level entry point. Returns `Ok(None)` for "not found" (matches
|
||||
/// Go's `ReadEcShardNeedle`); errors propagate as `io::Error`.
|
||||
/// Why a distributed EC read has no needle to return.
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub enum EcMiss {
|
||||
NotFound,
|
||||
/// Tombstoned in the local `.ecx`/`.ecj`, or reported deleted by a peer.
|
||||
Deleted,
|
||||
VolumeNotFound,
|
||||
}
|
||||
|
||||
/// Top-level entry point. Returns `Ok(None)` for any miss — absent,
|
||||
/// deleted, or volume gone; errors propagate as `io::Error`.
|
||||
pub async fn read_ec_shard_needle_distributed(
|
||||
state: &Arc<VolumeServerState>,
|
||||
vid: VolumeId,
|
||||
needle_id: NeedleId,
|
||||
) -> io::Result<Option<Needle>> {
|
||||
Ok(read_ec_shard_needle_or_miss(state, vid, needle_id)
|
||||
.await?
|
||||
.ok())
|
||||
}
|
||||
|
||||
/// Like `read_ec_shard_needle_distributed`, but says why there is no needle,
|
||||
/// as Go's `ReadEcShardNeedle` tells `ErrorDeleted` from not-found.
|
||||
pub async fn read_ec_shard_needle_or_miss(
|
||||
state: &Arc<VolumeServerState>,
|
||||
vid: VolumeId,
|
||||
needle_id: NeedleId,
|
||||
) -> io::Result<Result<Needle, EcMiss>> {
|
||||
// Phase A — under the Store read lock, locate the needle, compute
|
||||
// intervals, and read any locally-mounted shard intervals. We must
|
||||
// not `.await` while holding this guard (std::sync::RwLockReadGuard
|
||||
// is !Send).
|
||||
let mut snapshot = match snapshot_under_lock(state, vid, needle_id)? {
|
||||
Some(s) => s,
|
||||
None => return Ok(None),
|
||||
Ok(s) => s,
|
||||
Err(miss) => return Ok(Err(miss)),
|
||||
};
|
||||
|
||||
// Phase B — refresh the shard_locations cache from the master if
|
||||
@@ -210,17 +231,11 @@ pub async fn read_ec_shard_needle_distributed(
|
||||
.collect()
|
||||
.await;
|
||||
|
||||
let mut assembled: Vec<Vec<u8>> = Vec::with_capacity(fetched.len());
|
||||
for res in fetched {
|
||||
let (buf, is_deleted) = res?;
|
||||
// A peer reports the needle deleted (a cross-server window where the
|
||||
// local index still shows it live): treat as not-found rather than
|
||||
// serving zeros, mirroring Go's ErrorDeleted.
|
||||
if is_deleted {
|
||||
return Ok(None);
|
||||
}
|
||||
assembled.push(buf);
|
||||
}
|
||||
// A peer reports the needle deleted (a cross-server window where the
|
||||
// local index still shows it live): answer deleted rather than serving zeros.
|
||||
let Some(assembled) = gather_intervals(fetched)? else {
|
||||
return Ok(Err(EcMiss::Deleted));
|
||||
};
|
||||
|
||||
// Phase D — assemble and parse the Needle. Mirrors the tail of
|
||||
// `EcVolume::read_ec_shard_needle`.
|
||||
@@ -252,7 +267,20 @@ pub async fn read_ec_shard_needle_distributed(
|
||||
snapshot.version,
|
||||
)
|
||||
.map_err(|e| io::Error::new(io::ErrorKind::InvalidData, format!("{}", e)))?;
|
||||
Ok(Some(n))
|
||||
Ok(Ok(n))
|
||||
}
|
||||
|
||||
/// `None` when any holder reported the needle deleted. That outranks another
|
||||
/// interval's error: deletes are never invented, so the needle is gone either way.
|
||||
fn gather_intervals(fetched: Vec<io::Result<(Vec<u8>, bool)>>) -> io::Result<Option<Vec<Vec<u8>>>> {
|
||||
if fetched.iter().any(|r| matches!(r, Ok((_, true)))) {
|
||||
return Ok(None);
|
||||
}
|
||||
fetched
|
||||
.into_iter()
|
||||
.map(|r| r.map(|(buf, _)| buf))
|
||||
.collect::<io::Result<_>>()
|
||||
.map(Some)
|
||||
}
|
||||
|
||||
/// What one EC delete RPC carries — `VolumeEcBlobDeleteRequest` minus tonic.
|
||||
@@ -864,11 +892,10 @@ fn snapshot_under_lock(
|
||||
state: &Arc<VolumeServerState>,
|
||||
vid: VolumeId,
|
||||
needle_id: NeedleId,
|
||||
) -> io::Result<Option<Snapshot>> {
|
||||
) -> io::Result<Result<Snapshot, EcMiss>> {
|
||||
let store = state.store.read().unwrap();
|
||||
let ecv = match store.find_ec_volume(vid) {
|
||||
Some(v) => v,
|
||||
None => return Ok(None),
|
||||
let Some(ecv) = store.find_ec_volume(vid) else {
|
||||
return Ok(Err(EcMiss::VolumeNotFound));
|
||||
};
|
||||
|
||||
// Reuse EcVolume::locate_needle for offset/size resolution AND
|
||||
@@ -876,11 +903,17 @@ fn snapshot_under_lock(
|
||||
// local-only read path uses, so we stay byte-identical on the
|
||||
// shard-size + interval boundaries. locate_needle applies the runtime
|
||||
// delete mask, which is correct for serving reads.
|
||||
let (offset, size, intervals) = match ecv.locate_needle(needle_id)? {
|
||||
Some(v) => v,
|
||||
None => return Ok(None),
|
||||
let Some((offset, size, intervals)) = ecv.locate_needle(needle_id)? else {
|
||||
// locate_needle folds a tombstone into not-found.
|
||||
let deleted =
|
||||
matches!(ecv.find_needle_from_ecx(needle_id)?, Some((_, s)) if s.is_deleted());
|
||||
return Ok(Err(if deleted {
|
||||
EcMiss::Deleted
|
||||
} else {
|
||||
EcMiss::NotFound
|
||||
}));
|
||||
};
|
||||
build_snapshot(ecv, offset, size, &intervals).map(Some)
|
||||
build_snapshot(ecv, offset, size, &intervals).map(Ok)
|
||||
}
|
||||
|
||||
/// Like `snapshot_under_lock`, but locates intervals from the RAW .ecx
|
||||
@@ -1790,6 +1823,21 @@ async fn drain_copy_stream(
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn gather_intervals_puts_a_reported_deletion_ahead_of_errors() {
|
||||
let failed = || Err(io::Error::other("shard unreachable"));
|
||||
assert!(
|
||||
gather_intervals(vec![failed(), Ok((Vec::new(), true))])
|
||||
.unwrap()
|
||||
.is_none()
|
||||
);
|
||||
assert!(gather_intervals(vec![failed(), Ok((vec![1], false))]).is_err());
|
||||
assert_eq!(
|
||||
gather_intervals(vec![Ok((vec![1], false)), Ok((vec![2], false))]).unwrap(),
|
||||
Some(vec![vec![1], vec![2]])
|
||||
);
|
||||
}
|
||||
|
||||
fn locations(count: usize) -> HashMap<ShardId, Vec<String>> {
|
||||
(0..count)
|
||||
.map(|sid| (sid as ShardId, vec!["127.0.0.1:8080".to_string()]))
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
//! Instead of each upload handler directly calling `write_needle`, writes are
|
||||
//! submitted to a queue. A background worker drains the queue in batches (up to
|
||||
//! 128 entries), groups them by volume ID, and processes them together under a
|
||||
//! single store lock. Requests that asked for `fsync` are flushed by
|
||||
//! `write_needle` itself, one flush per durable write.
|
||||
//! single store lock. Durable writes to a volume share their .dat and .idx
|
||||
//! flushes (see `Volume::write_needles_grouped`).
|
||||
|
||||
use std::sync::Arc;
|
||||
|
||||
@@ -159,8 +159,12 @@ fn process_batch(state: Arc<VolumeServerState>, batch: Vec<WriteRequest>) {
|
||||
let mut store = state.store.write().unwrap();
|
||||
|
||||
for (vid, entries) in groups {
|
||||
for (mut needle, fsync, response_tx) in entries {
|
||||
let result = store.write_volume_needle(vid, &mut needle, fsync);
|
||||
let (mut writes, senders): (Vec<_>, Vec<_>) = entries
|
||||
.into_iter()
|
||||
.map(|(needle, fsync, response_tx)| ((needle, fsync), response_tx))
|
||||
.unzip();
|
||||
let results = store.write_volume_needles(vid, &mut writes);
|
||||
for (response_tx, result) in senders.into_iter().zip(results) {
|
||||
// Send result back; ignore error if receiver dropped.
|
||||
let _ = response_tx.send(result);
|
||||
}
|
||||
@@ -312,6 +316,63 @@ mod tests {
|
||||
}
|
||||
}
|
||||
|
||||
/// The queue hands a volume's batch to the grouped path, so ten durable
|
||||
/// writes cost one .dat sync and one .idx sync, not ten of each.
|
||||
#[test]
|
||||
fn test_process_batch_group_commits_fsync_writes() {
|
||||
use crate::config::MinFreeSpace;
|
||||
use crate::storage::types::{DiskType, NeedleId};
|
||||
use crate::storage::volume::VolumeSpec;
|
||||
|
||||
let tmp = tempfile::TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let state = make_test_state();
|
||||
{
|
||||
let mut store = state.store.write().unwrap();
|
||||
store
|
||||
.add_location(
|
||||
dir,
|
||||
dir,
|
||||
10,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
store
|
||||
.add_volume(VolumeId(1), DiskType::HardDrive, &VolumeSpec::default())
|
||||
.unwrap();
|
||||
}
|
||||
|
||||
let mut receivers = Vec::new();
|
||||
let batch = (1..=10u64)
|
||||
.map(|id| {
|
||||
let (response_tx, response_rx) = oneshot::channel();
|
||||
receivers.push(response_rx);
|
||||
WriteRequest {
|
||||
volume_id: VolumeId(1),
|
||||
needle: Needle {
|
||||
id: NeedleId(id),
|
||||
cookie: 0x1111.into(),
|
||||
data: vec![id as u8; 8],
|
||||
data_size: 8,
|
||||
..Needle::default()
|
||||
},
|
||||
fsync: true,
|
||||
response_tx,
|
||||
}
|
||||
})
|
||||
.collect();
|
||||
process_batch(state.clone(), batch);
|
||||
|
||||
for mut rx in receivers {
|
||||
assert!(matches!(rx.try_recv().unwrap(), Ok((_, _, false))));
|
||||
}
|
||||
let store = state.store.read().unwrap();
|
||||
let (_, vol) = store.find_volume(VolumeId(1)).unwrap();
|
||||
assert_eq!(vol.sync_counts_for_test(), (1, 1));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn test_write_queue_dropped_sender() {
|
||||
// When the queue is dropped, subsequent submits should fail gracefully.
|
||||
|
||||
@@ -479,6 +479,13 @@ impl DiskLocation {
|
||||
if self.idx_directory != self.directory {
|
||||
remove_bitrot_sidecars(&idx_base)?;
|
||||
}
|
||||
|
||||
// Staged 2PC generations (<base>.ecNN.v<N>, versioned .ecx/.ecj/.vif)
|
||||
// belong to this volume's EC state too; leaving them orphans the files.
|
||||
crate::storage::erasure_coding::ec_shard::remove_ec_generation_files(&base, 0)?;
|
||||
if self.idx_directory != self.directory {
|
||||
crate::storage::erasure_coding::ec_shard::remove_ec_generation_files(&idx_base, 0)?;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -601,6 +608,12 @@ impl DiskLocation {
|
||||
only_garbage: bool,
|
||||
keep_remote_data: bool,
|
||||
) -> Result<(), VolumeError> {
|
||||
// Refuse before removing: a refused destroy must leave it mounted.
|
||||
if let Some(v) = self.volumes.get(&vid)
|
||||
&& v.is_compacting()
|
||||
{
|
||||
return Err(v.compacting_error());
|
||||
}
|
||||
if let Some(mut v) = self.volumes.remove(&vid) {
|
||||
crate::metrics::VOLUME_GAUGE
|
||||
.with_label_values(&[&v.collection, "volume"])
|
||||
|
||||
@@ -3,10 +3,12 @@
|
||||
//! Rebuilds the original .dat + .idx files from data shards (.ec00-.ec09)
|
||||
//! and the sorted index (.ecx) + deletion journal (.ecj).
|
||||
|
||||
use std::collections::HashSet;
|
||||
use std::fs::File;
|
||||
use std::io::{self, Read, Write};
|
||||
|
||||
use crate::storage::erasure_coding::ec_shard::*;
|
||||
use crate::storage::erasure_coding::ec_volume::read_ecj_ids;
|
||||
use crate::storage::idx;
|
||||
use crate::storage::needle::needle::get_actual_size;
|
||||
use crate::storage::super_block::SUPER_BLOCK_SIZE;
|
||||
@@ -20,18 +22,21 @@ use crate::storage::volume::{fsync_dir, volume_file_name};
|
||||
/// `dir` is used both for reading `.ec00` and `.ecx`. For split-disk
|
||||
/// reconciled volumes call [`find_dat_file_size_with_dirs`] instead.
|
||||
pub fn find_dat_file_size(dir: &str, collection: &str, volume_id: VolumeId) -> io::Result<i64> {
|
||||
find_dat_file_size_with_dirs(dir, dir, collection, volume_id)
|
||||
let deleted = read_ecj_deletions(&[dir], collection, volume_id)?;
|
||||
find_dat_file_size_with_dirs(dir, dir, collection, volume_id, &deleted)
|
||||
}
|
||||
|
||||
/// Like [`find_dat_file_size`] but lets the caller pass separate dirs
|
||||
/// for `.ec00` (the data shard) and `.ecx` (the sealed index). This
|
||||
/// is the form needed when shards are split across data dirs and the
|
||||
/// `.ecx` lives on a sibling disk's idx dir (#9252).
|
||||
/// `.ecx` lives on a sibling disk's idx dir (#9252). Needles in `deleted`
|
||||
/// count as deleted.
|
||||
pub fn find_dat_file_size_with_dirs(
|
||||
ec00_dir: &str,
|
||||
ecx_dir: &str,
|
||||
collection: &str,
|
||||
volume_id: VolumeId,
|
||||
deleted: &HashSet<NeedleId>,
|
||||
) -> io::Result<i64> {
|
||||
let ec00_base = volume_file_name(ec00_dir, collection, volume_id);
|
||||
let ecx_base = volume_file_name(ecx_dir, collection, volume_id);
|
||||
@@ -53,9 +58,9 @@ pub fn find_dat_file_size_with_dirs(
|
||||
|
||||
for i in 0..entry_count {
|
||||
let start = i * NEEDLE_MAP_ENTRY_SIZE;
|
||||
let (_, offset, size) =
|
||||
let (key, offset, size) =
|
||||
idx_entry_from_bytes(&ecx_data[start..start + NEEDLE_MAP_ENTRY_SIZE]);
|
||||
if size.is_deleted() {
|
||||
if size.is_deleted() || deleted.contains(&key) {
|
||||
continue;
|
||||
}
|
||||
let entry_stop = offset.to_actual_offset() + get_actual_size(size, version);
|
||||
@@ -67,6 +72,48 @@ pub fn find_dat_file_size_with_dirs(
|
||||
Ok(dat_size)
|
||||
}
|
||||
|
||||
/// Whether the `.ecx` in `ecx_dir` indexes a needle deleted neither there nor
|
||||
/// in `deleted`.
|
||||
pub fn has_live_needles(
|
||||
ecx_dir: &str,
|
||||
collection: &str,
|
||||
volume_id: VolumeId,
|
||||
deleted: &HashSet<NeedleId>,
|
||||
) -> io::Result<bool> {
|
||||
let ecx_base = volume_file_name(ecx_dir, collection, volume_id);
|
||||
let ecx_data = std::fs::read(format!("{}.ecx", ecx_base))?;
|
||||
let (entries, _) = ecx_data.as_chunks::<NEEDLE_MAP_ENTRY_SIZE>();
|
||||
Ok(entries.iter().any(|entry| {
|
||||
let (key, _, size) = idx_entry_from_bytes(entry);
|
||||
!size.is_deleted() && !deleted.contains(&key)
|
||||
}))
|
||||
}
|
||||
|
||||
/// Distinct needle ids journaled in the `.ecj` of any of `dirs`. Go folds the
|
||||
/// journal into the `.ecx` (RebuildEcxFile) before a decode; reading it leaves
|
||||
/// the sealed index untouched. Only NotFound means "no journal".
|
||||
pub fn read_ecj_deletions(
|
||||
dirs: &[&str],
|
||||
collection: &str,
|
||||
volume_id: VolumeId,
|
||||
) -> io::Result<HashSet<NeedleId>> {
|
||||
let mut ids = HashSet::new();
|
||||
for (i, dir) in dirs.iter().enumerate() {
|
||||
if dirs[..i].contains(dir) {
|
||||
continue;
|
||||
}
|
||||
let path = format!("{}.ecj", volume_file_name(dir, collection, volume_id));
|
||||
let file = match File::open(&path) {
|
||||
Ok(file) => file,
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => continue,
|
||||
Err(e) => return Err(e),
|
||||
};
|
||||
let len = file.metadata()?.len();
|
||||
read_ecj_ids(&file, len, &mut ids)?;
|
||||
}
|
||||
Ok(ids)
|
||||
}
|
||||
|
||||
/// What it takes to rebuild a volume's .dat from its EC data shards.
|
||||
///
|
||||
/// Mirrors Go's `WriteDatFile(baseFileName, datFileSize,
|
||||
@@ -267,51 +314,61 @@ pub fn write_dat_file_from_shards(spec: &DatRebuild<'_>) -> io::Result<()> {
|
||||
|
||||
/// Write .idx file from .ecx index + .ecj deletion journal.
|
||||
///
|
||||
/// Copies sorted .ecx entries to .idx, then appends tombstones for
|
||||
/// deleted needles from .ecj.
|
||||
/// See [`write_idx_file_from_ec_index_with_dirs`]; everything lives in `dir`.
|
||||
pub fn write_idx_file_from_ec_index(
|
||||
dir: &str,
|
||||
collection: &str,
|
||||
volume_id: VolumeId,
|
||||
) -> io::Result<()> {
|
||||
let base = volume_file_name(dir, collection, volume_id);
|
||||
let ecx_path = format!("{}.ecx", base);
|
||||
let ecj_path = format!("{}.ecj", base);
|
||||
let idx_path = format!("{}.idx", base);
|
||||
let deleted = read_ecj_deletions(&[dir], collection, volume_id)?;
|
||||
let dat_file_size = find_dat_file_size_with_dirs(dir, dir, collection, volume_id, &deleted)?;
|
||||
write_idx_file_from_ec_index_with_dirs(dir, dir, collection, volume_id, &deleted, dat_file_size)
|
||||
}
|
||||
|
||||
/// Write the `.idx` for a `.dat` decoded to `dat_file_size` bytes, from the
|
||||
/// `.ecx` in `ecx_dir`, into `idx_dir`.
|
||||
///
|
||||
/// Copies the `.ecx` rows, then appends one tombstone per row whose needle is
|
||||
/// in `deleted`. A deleted needle at or past `dat_file_size` was cut from the
|
||||
/// `.dat`, so its row is dropped: a row pointing past the end of the `.dat`
|
||||
/// makes the volume load read-only.
|
||||
pub fn write_idx_file_from_ec_index_with_dirs(
|
||||
ecx_dir: &str,
|
||||
idx_dir: &str,
|
||||
collection: &str,
|
||||
volume_id: VolumeId,
|
||||
deleted: &HashSet<NeedleId>,
|
||||
dat_file_size: i64,
|
||||
) -> io::Result<()> {
|
||||
let ecx_path = format!("{}.ecx", volume_file_name(ecx_dir, collection, volume_id));
|
||||
let idx_path = format!("{}.idx", volume_file_name(idx_dir, collection, volume_id));
|
||||
// Write to a temp file and atomically rename into place, so a crash
|
||||
// mid-write never leaves a partial .idx at the final name beside the
|
||||
// source shards.
|
||||
let tmp_path = format!("{}.tmp", idx_path);
|
||||
|
||||
let write_result = (|| -> io::Result<()> {
|
||||
// Copy .ecx to the temp .idx
|
||||
std::fs::copy(&ecx_path, &tmp_path)?;
|
||||
|
||||
// Append deletions from .ecj as tombstones. Read the journal directly
|
||||
// and treat only NotFound as "no journal": Path::exists would also
|
||||
// swallow a permission/IO error and silently skip deletions, which
|
||||
// would resurrect deleted needles as live.
|
||||
let mut idx_file = std::fs::OpenOptions::new().append(true).open(&tmp_path)?;
|
||||
match std::fs::read(&ecj_path) {
|
||||
Ok(ecj_data) => {
|
||||
let count = ecj_data.len() / NEEDLE_ID_SIZE;
|
||||
for i in 0..count {
|
||||
let start = i * NEEDLE_ID_SIZE;
|
||||
let needle_id = NeedleId::from_bytes(&ecj_data[start..start + NEEDLE_ID_SIZE]);
|
||||
idx::write_index_entry(
|
||||
&mut idx_file,
|
||||
needle_id,
|
||||
Offset::default(),
|
||||
TOMBSTONE_FILE_SIZE,
|
||||
)?;
|
||||
}
|
||||
let mut ecx_file = File::open(&ecx_path)?;
|
||||
let mut idx_file = io::BufWriter::new(File::create(&tmp_path)?);
|
||||
let mut tombstoned = Vec::new();
|
||||
idx::walk_index_file(&mut ecx_file, 0, |key, offset, size| {
|
||||
let is_deleted = size.is_deleted() || deleted.contains(&key);
|
||||
if is_deleted && offset.to_actual_offset() >= dat_file_size {
|
||||
return Ok(());
|
||||
}
|
||||
Err(e) if e.kind() == io::ErrorKind::NotFound => {}
|
||||
Err(e) => return Err(e),
|
||||
idx::write_index_entry(&mut idx_file, key, offset, size)?;
|
||||
if !size.is_deleted() && deleted.contains(&key) {
|
||||
tombstoned.push(key);
|
||||
}
|
||||
Ok(())
|
||||
})?;
|
||||
for key in tombstoned {
|
||||
idx::write_index_entry(&mut idx_file, key, Offset::default(), TOMBSTONE_FILE_SIZE)?;
|
||||
}
|
||||
|
||||
// fsync, rename, then fsync the dir so the decoded .idx is durable and
|
||||
// atomically published before the caller deletes the source shards.
|
||||
let idx_file = idx_file.into_inner().map_err(|e| e.into_error())?;
|
||||
idx_file.sync_all()?;
|
||||
drop(idx_file);
|
||||
// Windows rename does not replace an existing file on every version;
|
||||
@@ -694,4 +751,43 @@ mod tests {
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
/// A journal many chunks long that repeats a few ids reads back as those
|
||||
/// ids, from each dir once, whatever its length.
|
||||
#[test]
|
||||
fn test_read_ecj_deletions_collects_distinct_ids_across_dirs() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let data = tmp.path().join("data");
|
||||
let idx = tmp.path().join("idx");
|
||||
let missing = tmp.path().join("missing");
|
||||
std::fs::create_dir_all(&data).unwrap();
|
||||
std::fs::create_dir_all(&idx).unwrap();
|
||||
let (data, idx, missing) = (
|
||||
data.to_str().unwrap(),
|
||||
idx.to_str().unwrap(),
|
||||
missing.to_str().unwrap(),
|
||||
);
|
||||
|
||||
let entry = |id: u64| {
|
||||
let mut buf = [0u8; NEEDLE_ID_SIZE];
|
||||
NeedleId(id).to_bytes(&mut buf);
|
||||
buf
|
||||
};
|
||||
// Past two load chunks of three repeating ids, then an id only in the
|
||||
// last chunk and a torn trailing record.
|
||||
let mut ecj = Vec::new();
|
||||
while ecj.len() <= 2 * (1 << 20) {
|
||||
for id in [1, 2, 3] {
|
||||
ecj.extend_from_slice(&entry(id));
|
||||
}
|
||||
}
|
||||
ecj.extend_from_slice(&entry(7));
|
||||
ecj.extend_from_slice(&entry(8)[..3]);
|
||||
std::fs::write(format!("{idx}/1.ecj"), &ecj).unwrap();
|
||||
std::fs::write(format!("{data}/1.ecj"), entry(9)).unwrap();
|
||||
|
||||
let ids = read_ecj_deletions(&[data, idx, idx, missing], "", VolumeId(1)).unwrap();
|
||||
let expected: HashSet<NeedleId> = [1, 2, 3, 7, 9].into_iter().map(NeedleId).collect();
|
||||
assert_eq!(ids, expected);
|
||||
}
|
||||
}
|
||||
@@ -813,7 +813,7 @@ impl EncodeRun<'_> {
|
||||
// explicitly.
|
||||
for (i, buf) in self.buffers[..self.data_shards].iter_mut().enumerate() {
|
||||
let read_offset = offset + (i * block_size) as u64;
|
||||
let n = read_at_most(self.dat_file, buf, read_offset)?;
|
||||
let n = crate::storage::io::read_full_at(self.dat_file, buf, read_offset)?;
|
||||
buf[n..].fill(0);
|
||||
}
|
||||
|
||||
@@ -834,19 +834,6 @@ impl EncodeRun<'_> {
|
||||
}
|
||||
}
|
||||
|
||||
/// Read into `buf` at `offset` until it is full or EOF; returns bytes read.
|
||||
fn read_at_most(dat_file: &File, buf: &mut [u8], offset: u64) -> io::Result<usize> {
|
||||
let mut n = 0;
|
||||
while n < buf.len() {
|
||||
let r = crate::storage::io::read_at(dat_file, &mut buf[n..], offset + n as u64)?;
|
||||
if r == 0 {
|
||||
break;
|
||||
}
|
||||
n += r;
|
||||
}
|
||||
Ok(n)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -87,14 +87,14 @@ impl EcVolumeShard {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Read data at a specific offset.
|
||||
/// Read data at a specific offset, filling `buf` unless the shard ends first.
|
||||
pub fn read_at(&self, buf: &mut [u8], offset: u64) -> io::Result<usize> {
|
||||
let file = self
|
||||
.ecd_file
|
||||
.as_ref()
|
||||
.ok_or_else(|| io::Error::other("shard file not open"))?;
|
||||
|
||||
crate::storage::io::read_at(file, buf, offset)
|
||||
crate::storage::io::read_full_at(file, buf, offset)
|
||||
}
|
||||
|
||||
/// Write data to the shard file (appends).
|
||||
@@ -195,6 +195,104 @@ impl ShardBits {
|
||||
}
|
||||
}
|
||||
|
||||
/// Parses the generation of a 2PC-staged `<base>.v<N>` file: `None` means the
|
||||
/// name is not a generation file of `base`.
|
||||
pub fn ec_file_generation(name: &str, base: &str) -> Option<u32> {
|
||||
let suffix = name.strip_prefix(&format!("{}.v", base))?;
|
||||
match suffix.parse::<u32>() {
|
||||
Ok(g) if g > 0 => Some(g),
|
||||
_ => None,
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes 2PC generation files staged under `base`:
|
||||
/// `<base>.ecNN.v<N>`, `<base>.ecx.v<N>`, `<base>.ecj.v<N>`, `<base>.ecsum.v<N>`
|
||||
/// and `<base>.vif.v<N>`. `generations_older_than == 0` removes every
|
||||
/// generation; otherwise only generations strictly below it. Returns the
|
||||
/// first real removal failure. Mirrors Go's `RemoveEcGenerationFiles`.
|
||||
pub fn remove_ec_generation_files(base: &str, generations_older_than: u32) -> io::Result<()> {
|
||||
let path = std::path::Path::new(base);
|
||||
let (Some(parent), Some(fname)) = (path.parent(), path.file_name()) else {
|
||||
return Ok(());
|
||||
};
|
||||
let ec_prefix = format!("{}.ec", fname.to_string_lossy());
|
||||
let vif_name = format!("{}.vif", fname.to_string_lossy());
|
||||
let mut first_err: Option<io::Error> = None;
|
||||
let mut record = |res: io::Result<()>| {
|
||||
if let Err(e) = res
|
||||
&& first_err.is_none()
|
||||
{
|
||||
first_err = Some(e);
|
||||
}
|
||||
};
|
||||
match fs::read_dir(parent) {
|
||||
Ok(entries) => {
|
||||
for entry in entries {
|
||||
let entry = match entry {
|
||||
Ok(entry) => entry,
|
||||
Err(e) => {
|
||||
// A skipped entry means an incomplete sweep; report it
|
||||
// instead of pretending the cleanup finished.
|
||||
record(Err(e));
|
||||
continue;
|
||||
}
|
||||
};
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
let Some((artifact, _)) = name.rsplit_once(".v") else {
|
||||
continue;
|
||||
};
|
||||
if artifact != vif_name && !artifact.starts_with(&ec_prefix) {
|
||||
continue;
|
||||
}
|
||||
let Some(generation) = ec_file_generation(&name, artifact) else {
|
||||
continue;
|
||||
};
|
||||
if generations_older_than > 0 && generation >= generations_older_than {
|
||||
continue;
|
||||
}
|
||||
record(match fs::remove_file(entry.path()) {
|
||||
Err(e) if e.kind() != io::ErrorKind::NotFound => Err(e),
|
||||
_ => Ok(()),
|
||||
});
|
||||
}
|
||||
}
|
||||
Err(e) if e.kind() != io::ErrorKind::NotFound => record(Err(e)),
|
||||
Err(_) => {}
|
||||
}
|
||||
match first_err {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// Removes every staged generation `<shard_file>.v<N>` of one shard file.
|
||||
/// Returns true when at least one generation file was removed.
|
||||
pub fn remove_ec_shard_generations(shard_file: &str) -> io::Result<bool> {
|
||||
let path = std::path::Path::new(shard_file);
|
||||
let (Some(parent), Some(fname)) = (path.parent(), path.file_name()) else {
|
||||
return Ok(false);
|
||||
};
|
||||
let fname = fname.to_string_lossy().into_owned();
|
||||
let mut removed = false;
|
||||
match fs::read_dir(parent) {
|
||||
Ok(entries) => {
|
||||
for entry in entries {
|
||||
let entry = entry?;
|
||||
let name = entry.file_name().to_string_lossy().into_owned();
|
||||
if ec_file_generation(&name, &fname).is_some() {
|
||||
match fs::remove_file(entry.path()) {
|
||||
Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
|
||||
_ => removed = true,
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
Err(e) if e.kind() != io::ErrorKind::NotFound => return Err(e),
|
||||
Err(_) => {}
|
||||
}
|
||||
Ok(removed)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
@@ -48,6 +48,29 @@ pub(crate) struct ShardLocationCache {
|
||||
/// A multiple of `NEEDLE_ID_SIZE`; 1 MiB is 131072 entries per syscall.
|
||||
const ECJ_LOAD_CHUNK_BYTES: usize = 1 << 20;
|
||||
|
||||
/// Adds every whole needle id in the first `len` bytes of `ecj_file` to `ids`,
|
||||
/// reading `ECJ_LOAD_CHUNK_BYTES` at a time; a trailing partial record is
|
||||
/// ignored.
|
||||
pub(crate) fn read_ecj_ids(
|
||||
ecj_file: &File,
|
||||
len: u64,
|
||||
ids: &mut HashSet<NeedleId>,
|
||||
) -> io::Result<()> {
|
||||
let mut buf = vec![0u8; std::cmp::min(ECJ_LOAD_CHUNK_BYTES as u64, len) as usize];
|
||||
let mut off: u64 = 0;
|
||||
while off + NEEDLE_ID_SIZE as u64 <= len {
|
||||
let mut want = std::cmp::min(ECJ_LOAD_CHUNK_BYTES as u64, len - off) as usize;
|
||||
want -= want % NEEDLE_ID_SIZE;
|
||||
// Positional read: the loader's handle is shared with journal appends.
|
||||
read_exact_at(ecj_file, &mut buf[..want], off)?;
|
||||
for entry in buf[..want].as_chunks::<NEEDLE_ID_SIZE>().0 {
|
||||
ids.insert(NeedleId::from_bytes(entry));
|
||||
}
|
||||
off += want as u64;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// An erasure-coded volume managing its local shards and index.
|
||||
pub struct EcVolume {
|
||||
pub volume_id: VolumeId,
|
||||
@@ -810,38 +833,7 @@ impl EcVolume {
|
||||
// held the `deleted_needles` write lock for the whole scan, which on a
|
||||
// bloated journal is the entire (unbounded) startup.
|
||||
let mut loaded: HashSet<NeedleId> = HashSet::new();
|
||||
let mut buf = vec![0u8; ECJ_LOAD_CHUNK_BYTES];
|
||||
let end = self.ecj_file_size as u64;
|
||||
let mut off: u64 = 0;
|
||||
while off + NEEDLE_ID_SIZE as u64 <= end {
|
||||
// Whole entries only; a trailing partial record is ignored, as the
|
||||
// per-entry loop did by construction.
|
||||
let mut want = std::cmp::min(ECJ_LOAD_CHUNK_BYTES as u64, end - off) as usize;
|
||||
want -= want % NEEDLE_ID_SIZE;
|
||||
if want == 0 {
|
||||
break;
|
||||
}
|
||||
#[cfg(unix)]
|
||||
{
|
||||
use std::os::unix::fs::FileExt;
|
||||
ecj_file.read_exact_at(&mut buf[..want], off)?;
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
// Positional read so concurrent readers of the shared .ecj
|
||||
// handle can't interleave seek/read. Mirrors the
|
||||
// read_exact_at helper at the bottom of this file.
|
||||
read_exact_at(ecj_file, &mut buf[..want], off)?;
|
||||
}
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
{
|
||||
compile_error!("Platform not supported: only unix and windows are supported");
|
||||
}
|
||||
for entry in buf[..want].chunks_exact(NEEDLE_ID_SIZE) {
|
||||
loaded.insert(NeedleId::from_bytes(entry));
|
||||
}
|
||||
off += want as u64;
|
||||
}
|
||||
read_ecj_ids(ecj_file, self.ecj_file_size as u64, &mut loaded)?;
|
||||
|
||||
let mut set = self
|
||||
.deleted_needles
|
||||
@@ -4668,7 +4660,7 @@ impl EcLocalShard {
|
||||
.file
|
||||
.as_ref()
|
||||
.map_err(|e| io::Error::new(e.kind(), e.to_string()))?;
|
||||
crate::storage::io::read_at(file, buf, offset)
|
||||
crate::storage::io::read_full_at(file, buf, offset)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -36,23 +36,11 @@ pub(crate) fn read_exact_at(file: &File, buf: &mut [u8], offset: u64) -> io::Res
|
||||
}
|
||||
#[cfg(windows)]
|
||||
{
|
||||
use std::os::windows::fs::FileExt;
|
||||
let mut filled = 0;
|
||||
let mut at = offset;
|
||||
while filled < buf.len() {
|
||||
let n = match file.seek_read(&mut buf[filled..], at) {
|
||||
Ok(n) => n,
|
||||
Err(err) if err.kind() == io::ErrorKind::Interrupted => continue,
|
||||
Err(err) => return Err(err),
|
||||
};
|
||||
if n == 0 {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::UnexpectedEof,
|
||||
"unexpected EOF in seek_read",
|
||||
));
|
||||
}
|
||||
filled += n;
|
||||
at += n as u64;
|
||||
if read_full_at(file, buf, offset)? < buf.len() {
|
||||
return Err(io::Error::new(
|
||||
io::ErrorKind::UnexpectedEof,
|
||||
"unexpected EOF in seek_read",
|
||||
));
|
||||
}
|
||||
}
|
||||
#[cfg(not(any(unix, windows)))]
|
||||
@@ -84,9 +72,34 @@ pub(crate) fn read_at(file: &File, buf: &mut [u8], offset: u64) -> io::Result<us
|
||||
}
|
||||
}
|
||||
|
||||
/// Reads into `buf` at `offset` until it is full or the file ends, retrying
|
||||
/// interrupted reads; returns how many bytes were read.
|
||||
///
|
||||
/// Unlike [`read_at`], a count below `buf.len()` always means end of file.
|
||||
pub(crate) fn read_full_at(file: &File, buf: &mut [u8], offset: u64) -> io::Result<usize> {
|
||||
fill_at(|b, at| read_at(file, b, at), buf, offset)
|
||||
}
|
||||
|
||||
fn fill_at(
|
||||
mut read: impl FnMut(&mut [u8], u64) -> io::Result<usize>,
|
||||
buf: &mut [u8],
|
||||
offset: u64,
|
||||
) -> io::Result<usize> {
|
||||
let mut filled = 0;
|
||||
while filled < buf.len() {
|
||||
match read(&mut buf[filled..], offset + filled as u64) {
|
||||
Ok(0) => break,
|
||||
Ok(n) => filled += n,
|
||||
Err(err) if err.kind() == io::ErrorKind::Interrupted => {}
|
||||
Err(err) => return Err(err),
|
||||
}
|
||||
}
|
||||
Ok(filled)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::{read_at, read_exact_at};
|
||||
use super::{fill_at, read_at, read_exact_at, read_full_at};
|
||||
use std::io::{ErrorKind, Write};
|
||||
|
||||
fn temp_file(bytes: &[u8]) -> tempfile::NamedTempFile {
|
||||
@@ -139,4 +152,57 @@ mod tests {
|
||||
let n = read_at(f.as_file(), &mut buf, 10).expect("read");
|
||||
assert_eq!(n, 0);
|
||||
}
|
||||
|
||||
/// A source that returns at most `chunk` bytes per call and fails with
|
||||
/// `Interrupted` on its first call, like a network mount under a signal.
|
||||
fn chunked(src: &[u8], chunk: usize) -> impl FnMut(&mut [u8], u64) -> std::io::Result<usize> {
|
||||
let mut interrupted = false;
|
||||
move |buf, at| {
|
||||
if !interrupted {
|
||||
interrupted = true;
|
||||
return Err(ErrorKind::Interrupted.into());
|
||||
}
|
||||
let at = (at as usize).min(src.len());
|
||||
let n = buf.len().min(chunk).min(src.len() - at);
|
||||
buf[..n].copy_from_slice(&src[at..at + n]);
|
||||
Ok(n)
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_at_fills_across_short_and_interrupted_reads() {
|
||||
let src: Vec<u8> = (0..=255).collect();
|
||||
let mut buf = [0u8; 100];
|
||||
let n = fill_at(chunked(&src, 7), &mut buf, 50).expect("read");
|
||||
assert_eq!(n, buf.len());
|
||||
assert_eq!(&buf[..], &src[50..150]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_at_stops_at_end_of_source() {
|
||||
let src: Vec<u8> = (0..=255).collect();
|
||||
let mut buf = [0u8; 100];
|
||||
let n = fill_at(chunked(&src, 7), &mut buf, 200).expect("read");
|
||||
assert_eq!(n, 56);
|
||||
assert_eq!(&buf[..n], &src[200..]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn fill_at_propagates_other_errors() {
|
||||
let mut buf = [0u8; 8];
|
||||
let err = fill_at(|_, _| Err(ErrorKind::PermissionDenied.into()), &mut buf, 0)
|
||||
.expect_err("error");
|
||||
assert_eq!(err.kind(), ErrorKind::PermissionDenied);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn read_full_at_returns_the_short_count_only_at_eof() {
|
||||
let f = temp_file(b"0123456789");
|
||||
let mut buf = [0u8; 8];
|
||||
assert_eq!(read_full_at(f.as_file(), &mut buf, 0).expect("read"), 8);
|
||||
assert_eq!(&buf, b"01234567");
|
||||
assert_eq!(read_full_at(f.as_file(), &mut buf, 6).expect("read"), 4);
|
||||
assert_eq!(&buf[..4], b"6789");
|
||||
assert_eq!(read_full_at(f.as_file(), &mut buf, 10).expect("read"), 0);
|
||||
}
|
||||
}
|
||||
@@ -3,7 +3,7 @@
|
||||
|
||||
use std::io;
|
||||
use std::sync::Mutex;
|
||||
use std::sync::atomic::{AtomicBool, AtomicI32, Ordering};
|
||||
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
|
||||
|
||||
/// Consecutive storage-media errors allowed before the volume is quarantined.
|
||||
pub(crate) const IO_ERROR_TOLERANCE: i32 = 3;
|
||||
@@ -34,10 +34,30 @@ pub(crate) fn is_storage_io_error(e: &io::Error) -> bool {
|
||||
#[derive(Default)]
|
||||
pub(crate) struct IoErrorTracker {
|
||||
last: Mutex<Option<String>>,
|
||||
count: AtomicI32,
|
||||
/// The consecutive error count in the low 32 bits and, in the high 32,
|
||||
/// how many times it has been cleared. They share one word so that
|
||||
/// `record_success_at` updates both in one step: reads record their
|
||||
/// outcomes here without the volume's write lock.
|
||||
streak: AtomicU64,
|
||||
quarantined: AtomicBool,
|
||||
}
|
||||
|
||||
const STREAK_COUNT_BITS: u64 = 0xffff_ffff;
|
||||
|
||||
fn streak_count(streak: u64) -> i32 {
|
||||
(streak & STREAK_COUNT_BITS) as i32
|
||||
}
|
||||
|
||||
/// `streak` with its count cleared and one more clear on record.
|
||||
fn streak_cleared(streak: u64) -> u64 {
|
||||
(streak >> 32).wrapping_add(1) << 32
|
||||
}
|
||||
|
||||
/// A point in the error streak, taken where a write landed whose success
|
||||
/// is only recorded later. See `IoErrorTracker::record_success_at`.
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct StreakMark(u64);
|
||||
|
||||
impl IoErrorTracker {
|
||||
/// `Some(e)` records a failure, `None` a success. Only storage-media
|
||||
/// failures count; every other outcome clears the count and last error.
|
||||
@@ -45,14 +65,22 @@ impl IoErrorTracker {
|
||||
if let Some(e) = err
|
||||
&& is_storage_io_error(e)
|
||||
{
|
||||
self.count.fetch_add(1, Ordering::Relaxed);
|
||||
self.streak.fetch_add(1, Ordering::Relaxed);
|
||||
if let Ok(mut guard) = self.last.lock() {
|
||||
*guard = Some(e.to_string());
|
||||
}
|
||||
crate::metrics::STORAGE_IO_ERROR_COUNTER.inc();
|
||||
return;
|
||||
}
|
||||
self.count.store(0, Ordering::Relaxed);
|
||||
self.clear_count();
|
||||
self.clear_last();
|
||||
}
|
||||
|
||||
fn clear_count(&self) {
|
||||
self.update_streak(|streak| Some(streak_cleared(streak)));
|
||||
}
|
||||
|
||||
fn clear_last(&self) {
|
||||
if let Ok(mut guard) = self.last.lock()
|
||||
&& guard.is_some()
|
||||
{
|
||||
@@ -60,17 +88,58 @@ impl IoErrorTracker {
|
||||
}
|
||||
}
|
||||
|
||||
/// Apply `f` to the streak atomically; `None` leaves it as it is.
|
||||
/// Returns the streak `f` produced, if any.
|
||||
fn update_streak(&self, mut f: impl FnMut(u64) -> Option<u64>) -> Option<u64> {
|
||||
let mut updated = None;
|
||||
let _ = self
|
||||
.streak
|
||||
.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |streak| {
|
||||
updated = f(streak);
|
||||
updated
|
||||
});
|
||||
updated
|
||||
}
|
||||
|
||||
pub(crate) fn mark(&self) -> StreakMark {
|
||||
StreakMark(self.streak.load(Ordering::Relaxed))
|
||||
}
|
||||
|
||||
/// Record a success as if it had come at `mark`: the errors counted
|
||||
/// before the mark are cleared and the ones counted since still stand,
|
||||
/// as they would had each outcome been recorded in order. A streak
|
||||
/// cleared since the mark is left as it is.
|
||||
pub(crate) fn record_success_at(&self, mark: StreakMark) {
|
||||
let before = streak_count(mark.0);
|
||||
let updated = self.update_streak(|streak| {
|
||||
if streak >> 32 != mark.0 >> 32 {
|
||||
return None;
|
||||
}
|
||||
if streak_count(streak) <= before {
|
||||
return Some(streak_cleared(streak));
|
||||
}
|
||||
Some(streak - before as u64)
|
||||
});
|
||||
// The last error stays when one counted since the mark is left.
|
||||
if updated.is_some_and(|streak| streak_count(streak) == 0) {
|
||||
self.clear_last();
|
||||
}
|
||||
}
|
||||
|
||||
/// The last recorded error, the consecutive count, and the quarantine flag.
|
||||
pub(crate) fn get_io_error_state(&self) -> (Option<String>, i32, bool) {
|
||||
let err = self.last.lock().ok().and_then(|g| g.clone());
|
||||
let count = self.count.load(Ordering::Relaxed);
|
||||
let count = self.count();
|
||||
let quarantined = self.quarantined.load(Ordering::Relaxed);
|
||||
(err, count, quarantined)
|
||||
}
|
||||
|
||||
fn count(&self) -> i32 {
|
||||
streak_count(self.streak.load(Ordering::Relaxed))
|
||||
}
|
||||
|
||||
pub(crate) fn should_quarantine(&self) -> bool {
|
||||
self.quarantined.load(Ordering::Relaxed)
|
||||
|| self.count.load(Ordering::Relaxed) >= IO_ERROR_TOLERANCE
|
||||
self.quarantined.load(Ordering::Relaxed) || self.count() >= IO_ERROR_TOLERANCE
|
||||
}
|
||||
|
||||
pub(crate) fn mark_io_quarantined(&self) {
|
||||
@@ -78,7 +147,7 @@ impl IoErrorTracker {
|
||||
}
|
||||
|
||||
pub(crate) fn reset_io_error_state(&self) {
|
||||
self.count.store(0, Ordering::Relaxed);
|
||||
self.clear_count();
|
||||
self.quarantined.store(false, Ordering::Relaxed);
|
||||
if let Ok(mut guard) = self.last.lock() {
|
||||
*guard = None;
|
||||
@@ -91,9 +160,11 @@ impl IoErrorTracker {
|
||||
*guard = err.map(|value| value.to_string());
|
||||
}
|
||||
if err.is_some() {
|
||||
self.count.store(IO_ERROR_TOLERANCE, Ordering::Relaxed);
|
||||
self.update_streak(|streak| {
|
||||
Some((streak & !STREAK_COUNT_BITS) | IO_ERROR_TOLERANCE as u64)
|
||||
});
|
||||
} else {
|
||||
self.count.store(0, Ordering::Relaxed);
|
||||
self.clear_count();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -171,6 +242,87 @@ mod tests {
|
||||
assert!(tracker.should_quarantine());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn success_at_a_mark_keeps_only_the_errors_after_it() {
|
||||
let tracker = IoErrorTracker::default();
|
||||
tracker.check_read_write_error(Some(&media_error()));
|
||||
tracker.check_read_write_error(Some(&media_error()));
|
||||
let mark = tracker.mark();
|
||||
tracker.check_read_write_error(Some(&media_error()));
|
||||
tracker.record_success_at(mark);
|
||||
|
||||
assert_eq!(
|
||||
tracker.get_io_error_state(),
|
||||
(Some(media_error().to_string()), 1, false)
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn success_at_a_mark_with_nothing_after_it_clears_the_streak() {
|
||||
let tracker = IoErrorTracker::default();
|
||||
tracker.check_read_write_error(Some(&media_error()));
|
||||
let mark = tracker.mark();
|
||||
tracker.record_success_at(mark);
|
||||
|
||||
assert_eq!(tracker.get_io_error_state(), (None, 0, false));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn success_at_a_mark_leaves_a_streak_cleared_since() {
|
||||
let tracker = IoErrorTracker::default();
|
||||
tracker.check_read_write_error(Some(&media_error()));
|
||||
tracker.check_read_write_error(Some(&media_error()));
|
||||
let mark = tracker.mark();
|
||||
tracker.check_read_write_error(None);
|
||||
tracker.check_read_write_error(Some(&media_error()));
|
||||
tracker.record_success_at(mark);
|
||||
|
||||
assert_eq!(
|
||||
tracker.get_io_error_state(),
|
||||
(Some(media_error().to_string()), 1, false)
|
||||
);
|
||||
}
|
||||
|
||||
/// Reads update the tracker without the volume's write lock, so a
|
||||
/// success replayed at a mark must not lose the errors they record
|
||||
/// while it runs.
|
||||
#[test]
|
||||
fn success_at_a_mark_keeps_concurrent_errors() {
|
||||
use std::sync::{Arc, Barrier};
|
||||
const READERS: i32 = 4;
|
||||
const ERRORS: i32 = 200;
|
||||
|
||||
for _ in 0..500 {
|
||||
let tracker = Arc::new(IoErrorTracker::default());
|
||||
tracker.check_read_write_error(Some(&media_error()));
|
||||
tracker.check_read_write_error(Some(&media_error()));
|
||||
let mark = tracker.mark();
|
||||
let start = Arc::new(Barrier::new(READERS as usize + 1));
|
||||
let readers: Vec<_> = (0..READERS)
|
||||
.map(|_| {
|
||||
let (tracker, start) = (tracker.clone(), start.clone());
|
||||
std::thread::spawn(move || {
|
||||
start.wait();
|
||||
for _ in 0..ERRORS {
|
||||
tracker.check_read_write_error(Some(&media_error()));
|
||||
}
|
||||
})
|
||||
})
|
||||
.collect();
|
||||
start.wait();
|
||||
while tracker.get_io_error_state().1 < 2 + READERS * ERRORS / 2 {
|
||||
std::hint::spin_loop();
|
||||
}
|
||||
tracker.record_success_at(mark);
|
||||
for reader in readers {
|
||||
reader.join().unwrap();
|
||||
}
|
||||
// The two errors before the mark are cleared; every error the
|
||||
// readers recorded after it stands.
|
||||
assert_eq!(tracker.get_io_error_state().1, READERS * ERRORS);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn reset_io_error_state_lifts_the_quarantine() {
|
||||
let tracker = IoErrorTracker::default();
|
||||
|
||||
@@ -247,6 +247,8 @@ impl CompactNeedleMap {
|
||||
pub fn load_from_idx<R: Read + Seek>(reader: &mut R, version: Version) -> io::Result<Self> {
|
||||
let mut nm = CompactNeedleMap::new();
|
||||
idx::walk_index_file(reader, 0, |key, offset, size| {
|
||||
// A read-only load attaches no writer, so this is its only size.
|
||||
nm.idx_file_offset += NEEDLE_MAP_ENTRY_SIZE as u64;
|
||||
nm.metric.maybe_set_max_needle_end(offset, size, version);
|
||||
if offset.is_zero() || size.is_deleted() {
|
||||
nm.delete_from_map(key);
|
||||
@@ -1386,6 +1388,18 @@ impl NeedleMap {
|
||||
}
|
||||
}
|
||||
|
||||
/// Skew the live file count away from what the `.idx` holds, so tests
|
||||
/// can build a volume whose reported count disagrees with a reload.
|
||||
#[cfg(test)]
|
||||
pub(crate) fn add_file_count_for_test(&self, delta: i64) {
|
||||
let metric = match self {
|
||||
NeedleMap::InMemory(nm) => &nm.metric,
|
||||
NeedleMap::Redb(nm) => &nm.metric,
|
||||
NeedleMap::SortedFile(_) => panic!("sorted-file needle maps are read-only"),
|
||||
};
|
||||
metric.file_count.fetch_add(delta, Ordering::Relaxed);
|
||||
}
|
||||
|
||||
/// Largest (offset + actual size) seen during the load walk; 0 if the
|
||||
/// map is empty. Used at volume load to detect .idx entries that
|
||||
/// reference past the end of .dat (issue #8928) without a second scan.
|
||||
|
||||
@@ -14,11 +14,11 @@ use crate::pb::master_pb;
|
||||
use crate::storage::disk_location::DiskLocation;
|
||||
use crate::storage::erasure_coding::ec_shard::{EcVolumeShard, MAX_SHARD_COUNT, ShardId};
|
||||
use crate::storage::erasure_coding::ec_volume::{EcVolume, is_usable_ecx_file};
|
||||
use crate::storage::needle::needle::Needle;
|
||||
use crate::storage::needle::needle::{Needle, get_actual_size};
|
||||
use crate::storage::needle_map::NeedleMapKind;
|
||||
use crate::storage::super_block::ReplicaPlacement;
|
||||
use crate::storage::super_block::{ReplicaPlacement, SUPER_BLOCK_SIZE};
|
||||
use crate::storage::types::*;
|
||||
use crate::storage::volume::{VifVolumeInfo, VolumeError, VolumeSpec};
|
||||
use crate::storage::volume::{CompactionJob, VifVolumeInfo, Volume, VolumeError, VolumeSpec};
|
||||
|
||||
/// Top-level storage manager containing all disk locations and their volumes.
|
||||
pub struct Store {
|
||||
@@ -225,7 +225,13 @@ impl Store {
|
||||
/// Find a free location matching a predicate.
|
||||
/// Matches Go's Store.FindFreeLocation: picks the matching location with the
|
||||
/// most remaining volume capacity, while skipping low-disk locations.
|
||||
pub fn find_free_location_predicate<F>(&self, pred: F) -> Option<usize>
|
||||
/// `replace_vid` names a volume about to be replaced: the slot it holds on
|
||||
/// a location counts as free there.
|
||||
pub fn find_free_location_predicate<F>(
|
||||
&self,
|
||||
pred: F,
|
||||
replace_vid: Option<VolumeId>,
|
||||
) -> Option<usize>
|
||||
where
|
||||
F: Fn(&DiskLocation) -> bool,
|
||||
{
|
||||
@@ -241,8 +247,12 @@ impl Store {
|
||||
let effective_free = if max == 0 {
|
||||
i64::MAX
|
||||
} else {
|
||||
let free_count = (max - loc.volumes_len() as i64) * DATA_SHARDS_COUNT as i64
|
||||
- loc.ec_shard_count() as i64;
|
||||
let mut free_slots = max - loc.volumes_len() as i64;
|
||||
if replace_vid.is_some_and(|vid| loc.find_volume(vid).is_some()) {
|
||||
free_slots += 1;
|
||||
}
|
||||
let free_count =
|
||||
free_slots * DATA_SHARDS_COUNT as i64 - loc.ec_shard_count() as i64;
|
||||
free_count / DATA_SHARDS_COUNT as i64
|
||||
};
|
||||
if effective_free <= 0 {
|
||||
@@ -406,14 +416,20 @@ impl Store {
|
||||
Err(VolumeError::NotFound)
|
||||
}
|
||||
|
||||
/// Unload (unmount) a volume without deleting its files.
|
||||
pub fn unmount_volume(&mut self, vid: VolumeId) -> bool {
|
||||
/// Unload (unmount) a volume without deleting its files. Refused while
|
||||
/// compacting, since a remount could start a second copy into .cpd.
|
||||
pub fn unmount_volume(&mut self, vid: VolumeId) -> Result<bool, VolumeError> {
|
||||
if let Some((_, v)) = self.find_volume(vid)
|
||||
&& v.is_compacting()
|
||||
{
|
||||
return Err(v.compacting_error());
|
||||
}
|
||||
for loc in &mut self.locations {
|
||||
if loc.unload_volume(vid).is_some() {
|
||||
return true;
|
||||
return Ok(true);
|
||||
}
|
||||
}
|
||||
false
|
||||
Ok(false)
|
||||
}
|
||||
|
||||
/// Reports whether any local volume or EC shard is currently quarantined
|
||||
@@ -699,15 +715,15 @@ impl Store {
|
||||
vol.read_needle_opt(n, read_deleted)
|
||||
}
|
||||
|
||||
/// Read needle metadata and return streaming info for large file reads.
|
||||
pub fn read_volume_needle_stream_info(
|
||||
/// Resolve a needle read under this guard, to run after it is released.
|
||||
pub(crate) fn needle_read_plan(
|
||||
&self,
|
||||
vid: VolumeId,
|
||||
n: &mut Needle,
|
||||
id: NeedleId,
|
||||
read_deleted: bool,
|
||||
) -> Result<crate::storage::volume::NeedleStreamInfo, VolumeError> {
|
||||
) -> Result<crate::storage::volume::NeedleReadPlan, VolumeError> {
|
||||
let (_, vol) = self.find_volume(vid).ok_or(VolumeError::NotFound)?;
|
||||
vol.read_needle_stream_info(n, read_deleted)
|
||||
vol.needle_read_plan(id, read_deleted)
|
||||
}
|
||||
|
||||
/// Re-lookup a needle's data-file offset after compaction may have moved it.
|
||||
@@ -729,6 +745,30 @@ impl Store {
|
||||
n: &mut Needle,
|
||||
fsync: bool,
|
||||
) -> Result<(u64, Size, bool), VolumeError> {
|
||||
self.writable_volume_mut(vid)?.write_needle(n, true, fsync)
|
||||
}
|
||||
|
||||
/// Write a batch of needles to one volume, sharing the syncs of its
|
||||
/// durable writes. See `Volume::write_needles_grouped`.
|
||||
pub fn write_volume_needles(
|
||||
&mut self,
|
||||
vid: VolumeId,
|
||||
writes: &mut [(Needle, bool)],
|
||||
) -> Vec<Result<(u64, Size, bool), VolumeError>> {
|
||||
match self.writable_volume_mut(vid) {
|
||||
Ok(vol) => vol.write_needles_grouped(writes),
|
||||
// The lookup fails only with NotFound or the disk-space ReadOnly.
|
||||
Err(e) => writes
|
||||
.iter()
|
||||
.map(|_| match e {
|
||||
VolumeError::ReadOnly(vid) => Err(VolumeError::ReadOnly(vid)),
|
||||
_ => Err(VolumeError::NotFound),
|
||||
})
|
||||
.collect(),
|
||||
}
|
||||
}
|
||||
|
||||
fn writable_volume_mut(&mut self, vid: VolumeId) -> Result<&mut Volume, VolumeError> {
|
||||
// Check disk space on the location containing this volume.
|
||||
// We do this before the mutable borrow to avoid borrow conflicts.
|
||||
let loc_idx = self
|
||||
@@ -739,11 +779,11 @@ impl Store {
|
||||
.is_disk_space_low
|
||||
.load(Ordering::Relaxed)
|
||||
{
|
||||
return Err(VolumeError::ReadOnly);
|
||||
return Err(VolumeError::ReadOnly(vid));
|
||||
}
|
||||
|
||||
let (_, vol) = self.find_volume_mut(vid).ok_or(VolumeError::NotFound)?;
|
||||
vol.write_needle(n, true, fsync)
|
||||
Ok(vol)
|
||||
}
|
||||
|
||||
/// Delete a needle from a volume.
|
||||
@@ -755,7 +795,7 @@ impl Store {
|
||||
// Match Go's DeleteVolumeNeedle: check noWriteOrDelete before proceeding.
|
||||
let (_, vol) = self.find_volume(vid).ok_or(VolumeError::NotFound)?;
|
||||
if vol.is_no_write_or_delete() {
|
||||
return Err(VolumeError::ReadOnly);
|
||||
return Err(VolumeError::ReadOnly(vid));
|
||||
}
|
||||
|
||||
let (_, vol) = self.find_volume_mut(vid).ok_or(VolumeError::NotFound)?;
|
||||
@@ -1200,49 +1240,35 @@ impl Store {
|
||||
found_vol.map(|v| (v, dirs))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
pub fn delete_expired_ec_volumes(
|
||||
&mut self,
|
||||
) -> (
|
||||
Vec<master_pb::VolumeEcShardInformationMessage>,
|
||||
Vec<master_pb::VolumeEcShardInformationMessage>,
|
||||
) {
|
||||
let mut ec_shards = Vec::new();
|
||||
let mut deleted = Vec::new();
|
||||
let (mut ec_shards, expired) = self.find_expired_ec_volumes();
|
||||
let (deleted, still_held) = self.remove_expired_ec_volumes(expired);
|
||||
ec_shards.extend(still_held);
|
||||
(ec_shards, deleted)
|
||||
}
|
||||
|
||||
for (disk_id, loc) in self.locations.iter_mut().enumerate() {
|
||||
let mut expired_vids = Vec::new();
|
||||
let mut io_quarantined_vids = Vec::new();
|
||||
/// The read half of `delete_expired_ec_volumes`: the shards to report, and
|
||||
/// the expired EC volumes, by disk index, for `remove_expired_ec_volumes`.
|
||||
pub fn find_expired_ec_volumes(
|
||||
&self,
|
||||
) -> (
|
||||
Vec<master_pb::VolumeEcShardInformationMessage>,
|
||||
Vec<(usize, VolumeId)>,
|
||||
) {
|
||||
let mut ec_shards = Vec::new();
|
||||
let mut expired = Vec::new();
|
||||
|
||||
for (disk_id, loc) in self.locations.iter().enumerate() {
|
||||
for (vid, ec_vol) in loc.ec_volumes() {
|
||||
if ec_vol.is_time_to_destroy() {
|
||||
expired_vids.push(*vid);
|
||||
expired.push((disk_id, *vid));
|
||||
} else if ec_vol.should_quarantine() {
|
||||
io_quarantined_vids.push(*vid);
|
||||
} else {
|
||||
ec_shards
|
||||
.extend(ec_vol.to_volume_ec_shard_information_messages(disk_id as u32));
|
||||
}
|
||||
}
|
||||
|
||||
for vid in expired_vids {
|
||||
let messages = loc
|
||||
.find_ec_volume(vid)
|
||||
.map(|ec_vol| ec_vol.to_volume_ec_shard_information_messages(disk_id as u32))
|
||||
.unwrap_or_default();
|
||||
if let Some(mut ec_vol) = loc.remove_ec_volume(vid) {
|
||||
for _ in 0..ec_vol.shard_count() {
|
||||
crate::metrics::VOLUME_GAUGE
|
||||
.with_label_values(&[&ec_vol.collection, "ec_shards"])
|
||||
.dec();
|
||||
}
|
||||
ec_vol.destroy();
|
||||
deleted.extend(messages);
|
||||
} else {
|
||||
ec_shards.extend(messages);
|
||||
}
|
||||
}
|
||||
|
||||
for vid in io_quarantined_vids {
|
||||
if let Some(ec_vol) = loc.find_ec_volume(vid) {
|
||||
let (_, io_count, quarantined) = ec_vol.get_io_error_state();
|
||||
if !quarantined {
|
||||
ec_vol.mark_io_quarantined();
|
||||
@@ -1252,14 +1278,55 @@ impl Store {
|
||||
"ec volume quarantined after consecutive IO errors"
|
||||
);
|
||||
}
|
||||
} else {
|
||||
ec_shards
|
||||
.extend(ec_vol.to_volume_ec_shard_information_messages(disk_id as u32));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
(ec_shards, deleted)
|
||||
(ec_shards, expired)
|
||||
}
|
||||
|
||||
/// The write half of `delete_expired_ec_volumes`: destroys each volume that
|
||||
/// is still there and still expired, returning the shards deleted and the
|
||||
/// shards of any that no longer qualify.
|
||||
pub fn remove_expired_ec_volumes(
|
||||
&mut self,
|
||||
expired: Vec<(usize, VolumeId)>,
|
||||
) -> (
|
||||
Vec<master_pb::VolumeEcShardInformationMessage>,
|
||||
Vec<master_pb::VolumeEcShardInformationMessage>,
|
||||
) {
|
||||
let mut deleted = Vec::new();
|
||||
let mut still_held = Vec::new();
|
||||
for (disk_id, vid) in expired {
|
||||
let Some(loc) = self.locations.get_mut(disk_id) else {
|
||||
continue;
|
||||
};
|
||||
let Some(ec_vol) = loc.find_ec_volume(vid) else {
|
||||
continue;
|
||||
};
|
||||
let messages = ec_vol.to_volume_ec_shard_information_messages(disk_id as u32);
|
||||
if !ec_vol.is_time_to_destroy() {
|
||||
still_held.extend(messages);
|
||||
continue;
|
||||
}
|
||||
if let Some(mut ec_vol) = loc.remove_ec_volume(vid) {
|
||||
for _ in 0..ec_vol.shard_count() {
|
||||
crate::metrics::VOLUME_GAUGE
|
||||
.with_label_values(&[&ec_vol.collection, "ec_shards"])
|
||||
.dec();
|
||||
}
|
||||
ec_vol.destroy();
|
||||
deleted.extend(messages);
|
||||
}
|
||||
}
|
||||
(deleted, still_held)
|
||||
}
|
||||
|
||||
/// Remove an EC volume from whichever location has it.
|
||||
#[cfg(test)]
|
||||
pub fn remove_ec_volume(&mut self, vid: VolumeId) -> Option<EcVolume> {
|
||||
for loc in &mut self.locations {
|
||||
if let Some(ecv) = loc.remove_ec_volume(vid) {
|
||||
@@ -1293,16 +1360,42 @@ impl Store {
|
||||
None
|
||||
}
|
||||
|
||||
/// Delete EC shard files from disk.
|
||||
pub fn delete_ec_shards(&mut self, vid: VolumeId, collection: &str, shard_ids: &[ShardId]) {
|
||||
/// Delete EC shard files from disk. Staged-generation removal failures are
|
||||
/// retained and returned after every location has been processed, so a
|
||||
/// failed sweep never masquerades as a successful delete.
|
||||
pub fn delete_ec_shards(
|
||||
&mut self,
|
||||
vid: VolumeId,
|
||||
collection: &str,
|
||||
shard_ids: &[ShardId],
|
||||
) -> std::io::Result<()> {
|
||||
// Delete shard files from disk, tracking which locations actually held one.
|
||||
let mut deleted_at = vec![false; self.locations.len()];
|
||||
let mut first_err: Option<std::io::Error> = None;
|
||||
for (i, loc) in self.locations.iter().enumerate() {
|
||||
for &shard_id in shard_ids {
|
||||
let shard = EcVolumeShard::new(&loc.directory, collection, vid, shard_id);
|
||||
if std::fs::remove_file(shard.file_name()).is_ok() {
|
||||
deleted_at[i] = true;
|
||||
}
|
||||
// The shard and every 2PC generation of it (<name>.v<N>) are
|
||||
// removed: the shard must not live on this disk at all.
|
||||
match crate::storage::erasure_coding::ec_shard::remove_ec_shard_generations(
|
||||
&shard.file_name(),
|
||||
) {
|
||||
Ok(true) => deleted_at[i] = true,
|
||||
Ok(false) => {}
|
||||
Err(e) => {
|
||||
tracing::warn!(
|
||||
"failed to remove staged generations of {}: {}",
|
||||
shard.file_name(),
|
||||
e
|
||||
);
|
||||
if first_err.is_none() {
|
||||
first_err = Some(e);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1374,6 +1467,11 @@ impl Store {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
match first_err {
|
||||
Some(e) => Err(e),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// True if `loc` still has any on-disk EC shard for this volume. An
|
||||
@@ -1447,20 +1545,41 @@ impl Store {
|
||||
&mut self,
|
||||
vid: VolumeId,
|
||||
preallocate: u64,
|
||||
max_bytes_per_second: i64,
|
||||
_max_bytes_per_second: i64,
|
||||
progress_fn: F,
|
||||
) -> Result<(), VolumeError>
|
||||
where
|
||||
F: Fn(i64) -> bool,
|
||||
{
|
||||
match self.begin_compact_volume(vid, preallocate)? {
|
||||
Some(job) => job.run(progress_fn),
|
||||
None => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
/// The part of `compact_volume` that needs the store: check free space and
|
||||
/// start the compaction. The returned job runs without the store lock.
|
||||
pub(crate) fn begin_compact_volume(
|
||||
&mut self,
|
||||
vid: VolumeId,
|
||||
preallocate: u64,
|
||||
) -> Result<Option<CompactionJob>, VolumeError> {
|
||||
// Required space matches Go's CompactVolume check: the larger of the
|
||||
// requested preallocation and the estimated volume size.
|
||||
// requested preallocation and the estimated compacted size — the live
|
||||
// needles, not the .dat the garbage already occupies, so a full disk
|
||||
// can still be reclaimed.
|
||||
let (loc_idx, space_needed) = {
|
||||
let (loc_idx, v) = self
|
||||
.find_volume(vid)
|
||||
.ok_or(VolumeError::VolumeNotFound(vid))?;
|
||||
let estimated = v.dat_file_size().unwrap_or(0) + v.idx_file_size();
|
||||
(loc_idx, std::cmp::max(preallocate, estimated))
|
||||
let live_count = (v.file_count() - v.deleted_count()).max(0) as u64;
|
||||
let live_bytes = v.content_size().saturating_sub(v.deleted_size());
|
||||
let per_needle = (get_actual_size(Size(0), v.version())
|
||||
+ NEEDLE_PADDING_SIZE as i64
|
||||
+ NEEDLE_MAP_ENTRY_SIZE as i64) as u64;
|
||||
let estimated = SUPER_BLOCK_SIZE as u64 + live_count * per_needle + live_bytes;
|
||||
let space_needed = std::cmp::max(preallocate, estimated);
|
||||
(loc_idx, space_needed + space_needed / 10)
|
||||
};
|
||||
|
||||
let dir = self.locations[loc_idx].directory.clone();
|
||||
@@ -1476,7 +1595,7 @@ impl Store {
|
||||
let (_, v) = self
|
||||
.find_volume_mut(vid)
|
||||
.ok_or(VolumeError::VolumeNotFound(vid))?;
|
||||
v.compact_by_index(preallocate, max_bytes_per_second, progress_fn)
|
||||
v.begin_compact_by_index()
|
||||
}
|
||||
|
||||
/// Commit a completed compaction: swap files and reload.
|
||||
@@ -1776,7 +1895,7 @@ mod tests {
|
||||
store
|
||||
.write_volume_needle(VolumeId(7), &mut n, false)
|
||||
.unwrap();
|
||||
assert!(store.unmount_volume(VolumeId(7)));
|
||||
assert!(store.unmount_volume(VolumeId(7)).unwrap());
|
||||
|
||||
store.mount_volume_by_id(VolumeId(7), Some("coll")).unwrap();
|
||||
assert!(store.find_volume(VolumeId(7)).is_some());
|
||||
@@ -1818,7 +1937,7 @@ mod tests {
|
||||
store
|
||||
.write_volume_needle(VolumeId(9), &mut n, false)
|
||||
.unwrap();
|
||||
assert!(store.unmount_volume(VolumeId(9)));
|
||||
assert!(store.unmount_volume(VolumeId(9)).unwrap());
|
||||
|
||||
// The hint is accepted and mounts the volume.
|
||||
store
|
||||
@@ -1863,7 +1982,7 @@ mod tests {
|
||||
store
|
||||
.write_volume_needle(VolumeId(11), &mut n, false)
|
||||
.unwrap();
|
||||
assert!(store.unmount_volume(VolumeId(11)));
|
||||
assert!(store.unmount_volume(VolumeId(11)).unwrap());
|
||||
|
||||
// Simulate an interrupted copy: drop a .note marker.
|
||||
let base = volume_file_name(dir, "coll", VolumeId(11));
|
||||
@@ -1920,7 +2039,7 @@ mod tests {
|
||||
store
|
||||
.write_volume_needle(VolumeId(13), &mut n, false)
|
||||
.unwrap();
|
||||
assert!(store.unmount_volume(VolumeId(13)));
|
||||
assert!(store.unmount_volume(VolumeId(13)).unwrap());
|
||||
|
||||
// No hint: the fallback scan finds the sidecar on disk 0 first (skip,
|
||||
// no .dat), then the real .dat on disk 1 (mount).
|
||||
@@ -1975,7 +2094,7 @@ mod tests {
|
||||
store
|
||||
.write_volume_needle(VolumeId(15), &mut n, false)
|
||||
.unwrap();
|
||||
assert!(store.unmount_volume(VolumeId(15)));
|
||||
assert!(store.unmount_volume(VolumeId(15)).unwrap());
|
||||
// Clear the low-space flag so mount_volume_by_id considers disk 0.
|
||||
store.locations[0]
|
||||
.is_disk_space_low
|
||||
@@ -2352,7 +2471,7 @@ mod tests {
|
||||
.unwrap();
|
||||
|
||||
let selected =
|
||||
store.find_free_location_predicate(|loc| loc.disk_type == DiskType::HardDrive);
|
||||
store.find_free_location_predicate(|loc| loc.disk_type == DiskType::HardDrive, None);
|
||||
assert_eq!(selected, Some(1));
|
||||
|
||||
store.locations[1]
|
||||
@@ -2360,7 +2479,7 @@ mod tests {
|
||||
.store(true, Ordering::Relaxed);
|
||||
|
||||
let selected =
|
||||
store.find_free_location_predicate(|loc| loc.disk_type == DiskType::HardDrive);
|
||||
store.find_free_location_predicate(|loc| loc.disk_type == DiskType::HardDrive, None);
|
||||
assert_eq!(selected, Some(0));
|
||||
}
|
||||
|
||||
@@ -2483,6 +2602,162 @@ mod tests {
|
||||
assert_eq!(v.dat_file_size().unwrap(), volume_size);
|
||||
}
|
||||
|
||||
fn write_test_needle(store: &mut Store, vid: VolumeId, id: u64, data: &[u8]) {
|
||||
let mut n = Needle {
|
||||
id: NeedleId(id),
|
||||
cookie: Cookie(id as u32),
|
||||
data_size: data.len() as u32,
|
||||
data: data.to_vec(),
|
||||
..Needle::default()
|
||||
};
|
||||
store.write_volume_needle(vid, &mut n, true).unwrap();
|
||||
}
|
||||
|
||||
fn read_test_needle(store: &Store, vid: VolumeId, id: u64) -> Result<Vec<u8>, VolumeError> {
|
||||
let mut n = Needle {
|
||||
id: NeedleId(id),
|
||||
cookie: Cookie(id as u32),
|
||||
..Needle::default()
|
||||
};
|
||||
store.read_volume_needle(vid, &mut n)?;
|
||||
Ok(n.data)
|
||||
}
|
||||
|
||||
/// While a compaction copy runs off the store lock, nothing may pull the
|
||||
/// volume's files out from under it or start a second copy into .cpd.
|
||||
#[test]
|
||||
fn test_compaction_in_flight_guards_the_volume() {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let other = TempDir::new().unwrap();
|
||||
let mut store = make_test_store(&[dir]);
|
||||
let vid = VolumeId(1);
|
||||
store
|
||||
.add_volume(vid, DiskType::HardDrive, &VolumeSpec::default())
|
||||
.unwrap();
|
||||
for i in 1..=3u64 {
|
||||
write_test_needle(&mut store, vid, i, format!("data-{i}").as_bytes());
|
||||
}
|
||||
let revision = {
|
||||
let (_, v) = store.find_volume(vid).unwrap();
|
||||
v.super_block.compaction_revision
|
||||
};
|
||||
|
||||
let job = store
|
||||
.begin_compact_volume(vid, 0)
|
||||
.unwrap()
|
||||
.expect("the first compaction claims the volume");
|
||||
|
||||
assert!(store.begin_compact_volume(vid, 0).unwrap().is_none());
|
||||
assert!(store.unmount_volume(vid).is_err());
|
||||
assert!(store.delete_volume(vid, false, false, false).is_err());
|
||||
store.delete_collection("").unwrap();
|
||||
assert!(store.cleanup_compact_volume(vid).is_err());
|
||||
let (_, v) = store.find_volume_mut(vid).unwrap();
|
||||
assert!(v.relocate_index_to(other.path().to_str().unwrap()).is_err());
|
||||
// Go parity: a commit that finds the volume compacting is a no-op.
|
||||
store.commit_compact_volume(vid).unwrap();
|
||||
|
||||
let (_, v) = store.find_volume(vid).expect("still mounted");
|
||||
assert!(v.is_compacting());
|
||||
assert_eq!(v.super_block.compaction_revision, revision);
|
||||
|
||||
job.run(|_| true).unwrap();
|
||||
assert!(!store.find_volume(vid).unwrap().1.is_compacting());
|
||||
store.commit_compact_volume(vid).unwrap();
|
||||
let (_, v) = store.find_volume(vid).unwrap();
|
||||
assert_eq!(v.super_block.compaction_revision, revision + 1);
|
||||
assert!(store.unmount_volume(vid).unwrap());
|
||||
}
|
||||
|
||||
/// Writes, overwrites and deletes that land while the copy is parked
|
||||
/// off the store lock must all survive the commit via makeup_diff.
|
||||
fn check_writes_during_compaction_survive_commit(kind: NeedleMapKind) {
|
||||
let tmp = TempDir::new().unwrap();
|
||||
let dir = tmp.path().to_str().unwrap();
|
||||
let mut store = Store::new(kind);
|
||||
store
|
||||
.add_location(
|
||||
dir,
|
||||
dir,
|
||||
10,
|
||||
DiskType::HardDrive,
|
||||
MinFreeSpace::Percent(1.0),
|
||||
Vec::new(),
|
||||
)
|
||||
.unwrap();
|
||||
let vid = VolumeId(1);
|
||||
store
|
||||
.add_volume(vid, DiskType::HardDrive, &VolumeSpec::default())
|
||||
.unwrap();
|
||||
let (_, v) = store.find_volume(vid).unwrap();
|
||||
assert_eq!(
|
||||
v.live_meta_idx_size_for_test().is_some(),
|
||||
kind == NeedleMapKind::Redb
|
||||
);
|
||||
for i in 1..=6u64 {
|
||||
write_test_needle(&mut store, vid, i, format!("data-{i}").as_bytes());
|
||||
}
|
||||
let mut del = Needle {
|
||||
id: NeedleId(2),
|
||||
cookie: Cookie(2),
|
||||
..Needle::default()
|
||||
};
|
||||
store.delete_volume_needle(vid, &mut del).unwrap();
|
||||
let revision = {
|
||||
let (_, v) = store.find_volume(vid).unwrap();
|
||||
v.super_block.compaction_revision
|
||||
};
|
||||
|
||||
let job = store.begin_compact_volume(vid, 0).unwrap().unwrap();
|
||||
let (entered_tx, entered_rx) = std::sync::mpsc::channel();
|
||||
let (release_tx, release_rx) = std::sync::mpsc::channel::<()>();
|
||||
let copy = std::thread::spawn(move || {
|
||||
job.run(move |_| {
|
||||
let _ = entered_tx.send(());
|
||||
let _ = release_rx.recv();
|
||||
true
|
||||
})
|
||||
});
|
||||
entered_rx.recv().unwrap();
|
||||
|
||||
write_test_needle(&mut store, vid, 99, b"late-write");
|
||||
write_test_needle(&mut store, vid, 3, b"overwritten");
|
||||
let mut del = Needle {
|
||||
id: NeedleId(4),
|
||||
cookie: Cookie(4),
|
||||
..Needle::default()
|
||||
};
|
||||
store.delete_volume_needle(vid, &mut del).unwrap();
|
||||
|
||||
drop(release_tx);
|
||||
copy.join().unwrap().unwrap();
|
||||
store.commit_compact_volume(vid).unwrap();
|
||||
|
||||
let (_, v) = store.find_volume(vid).unwrap();
|
||||
assert_eq!(v.super_block.compaction_revision, revision + 1);
|
||||
assert_eq!(read_test_needle(&store, vid, 99).unwrap(), b"late-write");
|
||||
assert_eq!(read_test_needle(&store, vid, 3).unwrap(), b"overwritten");
|
||||
assert!(read_test_needle(&store, vid, 4).is_err());
|
||||
assert!(read_test_needle(&store, vid, 2).is_err());
|
||||
for i in [1u64, 5, 6] {
|
||||
assert_eq!(
|
||||
read_test_needle(&store, vid, i).unwrap(),
|
||||
format!("data-{i}").as_bytes()
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_writes_during_compaction_survive_commit_in_memory() {
|
||||
check_writes_during_compaction_survive_commit(NeedleMapKind::InMemory);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn test_writes_during_compaction_survive_commit_redb() {
|
||||
check_writes_during_compaction_survive_commit(NeedleMapKind::Redb);
|
||||
}
|
||||
|
||||
/// Build a Store with N HDD disk locations under a single TempDir.
|
||||
/// Returns the store and the TempDir guard so callers keep the dirs
|
||||
/// alive for the test's lifetime.
|
||||
@@ -2553,13 +2828,13 @@ mod tests {
|
||||
std::fs::write(format!("{}.ecsum", base1), b"x").unwrap();
|
||||
|
||||
// Disk 1 still has .ec01 afterwards: both sidecars survive.
|
||||
store.delete_ec_shards(vid, collection, &[0]);
|
||||
store.delete_ec_shards(vid, collection, &[0]).unwrap();
|
||||
assert!(std::path::Path::new(&format!("{}.ecsum", base0)).exists());
|
||||
assert!(std::path::Path::new(&format!("{}.ecsum", base1)).exists());
|
||||
|
||||
// Disk 1's last shard goes: its sidecar is orphaned and removed, but
|
||||
// disk 0 was never touched by either delete and keeps its sidecar.
|
||||
store.delete_ec_shards(vid, collection, &[1]);
|
||||
store.delete_ec_shards(vid, collection, &[1]).unwrap();
|
||||
assert!(!std::path::Path::new(&format!("{}.ec01", base1)).exists());
|
||||
assert!(
|
||||
!std::path::Path::new(&format!("{}.ecsum", base1)).exists(),
|
||||
@@ -2604,13 +2879,13 @@ mod tests {
|
||||
std::fs::write(format!("{}.ec01", base1), b"x").unwrap();
|
||||
std::fs::write(format!("{}.ecsum", idx_base), b"x").unwrap();
|
||||
|
||||
store.delete_ec_shards(vid, collection, &[0]);
|
||||
store.delete_ec_shards(vid, collection, &[0]).unwrap();
|
||||
assert!(
|
||||
std::path::Path::new(&format!("{}.ecsum", idx_base)).exists(),
|
||||
"shared idx sidecar must survive while a sibling disk still has shards"
|
||||
);
|
||||
|
||||
store.delete_ec_shards(vid, collection, &[1]);
|
||||
store.delete_ec_shards(vid, collection, &[1]).unwrap();
|
||||
assert!(
|
||||
!std::path::Path::new(&format!("{}.ecsum", idx_base)).exists(),
|
||||
"shared idx sidecar should go with the last location's last shard"
|
||||
@@ -2633,7 +2908,7 @@ mod tests {
|
||||
std::fs::write(format!("{}.vif", base1), b"x").unwrap();
|
||||
std::fs::write(format!("{}.idx", base1), b"x").unwrap();
|
||||
|
||||
store.delete_ec_shards(vid, collection, &[0, 1]);
|
||||
store.delete_ec_shards(vid, collection, &[0, 1]).unwrap();
|
||||
|
||||
assert!(
|
||||
!std::path::Path::new(&format!("{}.vif", base0)).exists(),
|
||||
@@ -2645,6 +2920,34 @@ mod tests {
|
||||
);
|
||||
}
|
||||
|
||||
/// Deleting a shard removes its staged 2PC generations (<name>.v<N>) too:
|
||||
/// a shard evicted off a disk leaves nothing (Go
|
||||
/// deleteEcShardIdsForEachLocation).
|
||||
#[test]
|
||||
fn test_delete_ec_shards_removes_staged_generations() {
|
||||
let (mut store, _tmp) = make_ec_target_test_store(1);
|
||||
let collection = "c";
|
||||
let vid = VolumeId(7);
|
||||
let base = volume_file_name(&store.locations[0].directory, collection, vid);
|
||||
std::fs::write(format!("{}.ec00", base), b"x").unwrap();
|
||||
std::fs::write(format!("{}.ec05", base), b"x").unwrap();
|
||||
std::fs::write(format!("{}.ec05.v2", base), b"x").unwrap();
|
||||
std::fs::write(format!("{}.ecx", base), b"x").unwrap();
|
||||
|
||||
store.delete_ec_shards(vid, collection, &[5]).unwrap();
|
||||
|
||||
assert!(!std::path::Path::new(&format!("{}.ec05", base)).exists());
|
||||
assert!(
|
||||
!std::path::Path::new(&format!("{}.ec05.v2", base)).exists(),
|
||||
"staged generations of a deleted shard must go with it"
|
||||
);
|
||||
assert!(std::path::Path::new(&format!("{}.ec00", base)).exists());
|
||||
assert!(
|
||||
std::path::Path::new(&format!("{}.ecx", base)).exists(),
|
||||
"index must survive while shards remain"
|
||||
);
|
||||
}
|
||||
|
||||
/// An already-mounted EC volume on disk 1 must win over a stray
|
||||
/// `.ecx` on disk 2. Protects the post-startup steady state from
|
||||
/// being perturbed by leftover index files from a prior failed move.
|
||||
|
||||
@@ -1476,7 +1476,7 @@ mod tests {
|
||||
let vid = VolumeId(7004);
|
||||
let collection = "grafana-loki";
|
||||
|
||||
store.delete_ec_shards(vid, collection, &[1]);
|
||||
store.delete_ec_shards(vid, collection, &[1]).unwrap();
|
||||
|
||||
// Shard 1 file is gone on disk 1.
|
||||
let p1 = format!(
|
||||
|
||||
+1397
-567
File diff suppressed because it is too large.
Load diff
@@ -477,6 +477,74 @@ async fn delete_then_get_returns_404() {
|
||||
);
|
||||
}
|
||||
|
||||
// Go answers both with 500 and an error containing "volume N is read only"
|
||||
// (the write behind "failed to write to local disk: ").
|
||||
#[tokio::test]
|
||||
async fn write_and_delete_on_read_only_volume_say_is_read_only() {
|
||||
let (state, _tmp) = test_state();
|
||||
let uri = "/1,01637037d6";
|
||||
|
||||
let request = |method: &str, body: &[u8]| {
|
||||
Request::builder()
|
||||
.method(method)
|
||||
.uri(uri)
|
||||
.body(Body::from(body.to_vec()))
|
||||
.unwrap()
|
||||
};
|
||||
let error_of = |body: Vec<u8>| -> String {
|
||||
let json: serde_json::Value = serde_json::from_slice(&body).unwrap();
|
||||
json["error"].as_str().unwrap_or_default().to_string()
|
||||
};
|
||||
|
||||
let response = build_admin_router(state.clone())
|
||||
.oneshot(request("POST", b"written before read-only"))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::CREATED);
|
||||
|
||||
state
|
||||
.store
|
||||
.write()
|
||||
.unwrap()
|
||||
.find_volume_mut(VolumeId(1))
|
||||
.unwrap()
|
||||
.1
|
||||
.set_no_write_or_delete(true);
|
||||
|
||||
let response = build_admin_router(state.clone())
|
||||
.oneshot(request("POST", b"refused"))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
let error = error_of(body_bytes(response).await);
|
||||
assert!(error.contains("volume 1 is read only"), "{error}");
|
||||
|
||||
let response = build_admin_router(state.clone())
|
||||
.oneshot(request("DELETE", b""))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::INTERNAL_SERVER_ERROR);
|
||||
assert_eq!(
|
||||
error_of(body_bytes(response).await),
|
||||
"Deletion Failed: volume 1 is read only"
|
||||
);
|
||||
|
||||
// The needle is still there to delete once the volume is writable again.
|
||||
state
|
||||
.store
|
||||
.write()
|
||||
.unwrap()
|
||||
.find_volume_mut(VolumeId(1))
|
||||
.unwrap()
|
||||
.1
|
||||
.set_no_write_or_delete(false);
|
||||
let response = build_admin_router(state.clone())
|
||||
.oneshot(request("DELETE", b""))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(response.status(), StatusCode::ACCEPTED);
|
||||
}
|
||||
|
||||
// ============================================================================
|
||||
// 6. HEAD returns headers without body
|
||||
// ============================================================================
|
||||
|
||||
@@ -21,7 +21,7 @@
|
||||
<scala.binary.version>2.12</scala.binary.version>
|
||||
<junit.version>4.13.2</junit.version>
|
||||
<seaweedfs.hadoop3.client.version>4.00</seaweedfs.hadoop3.client.version>
|
||||
<jackson.version>2.22.1</jackson.version> <!-- Upgraded from 2.15.3 -->
|
||||
<jackson.version>2.22.3</jackson.version> <!-- Upgraded from 2.15.3 -->
|
||||
<!-- jackson-annotations dropped the patch digit in 2.20; matches jackson.version's major.minor -->
|
||||
<jackson.annotations.version>2.22</jackson.annotations.version>
|
||||
<netty.version>4.2.16.Final</netty.version> <!-- Upgraded to 4.1.125.Final for security fixes (CVE in netty-codec < 4.1.125.Final, netty-codec-http2 <= 4.1.123.Final) -->
|
||||
|
||||
@@ -0,0 +1,258 @@
|
||||
package iam
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"math/big"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/aws/credentials"
|
||||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
"github.com/aws/aws-sdk-go/service/iam"
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
webIdentityAudience = "web-identity-api-test"
|
||||
webIdentitySubject = "spiffe://example.org/ns/app/sa/app"
|
||||
)
|
||||
|
||||
// webIdentityIssuer is an OIDC issuer served by the test: discovery document
|
||||
// and JWKS for one RSA key, so the server under test fetches real keys.
|
||||
type webIdentityIssuer struct {
|
||||
server *httptest.Server
|
||||
key *rsa.PrivateKey
|
||||
}
|
||||
|
||||
func newWebIdentityIssuer(t *testing.T) *webIdentityIssuer {
|
||||
t.Helper()
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
require.NoError(t, err)
|
||||
issuer := &webIdentityIssuer{key: key}
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("/.well-known/openid-configuration", func(w http.ResponseWriter, _ *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{
|
||||
"issuer": issuer.server.URL,
|
||||
"jwks_uri": issuer.server.URL + "/keys",
|
||||
"id_token_signing_alg_values_supported": []string{"RS256"},
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("/keys", func(w http.ResponseWriter, _ *http.Request) {
|
||||
b64 := func(b []byte) string { return base64.RawURLEncoding.EncodeToString(b) }
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"keys": []any{map[string]any{
|
||||
"kty": "RSA", "kid": "k1", "use": "sig", "alg": "RS256",
|
||||
"n": b64(key.PublicKey.N.Bytes()), "e": b64(big.NewInt(int64(key.PublicKey.E)).Bytes()),
|
||||
}}})
|
||||
})
|
||||
issuer.server = httptest.NewServer(mux)
|
||||
t.Cleanup(issuer.server.Close)
|
||||
return issuer
|
||||
}
|
||||
|
||||
func (i *webIdentityIssuer) claims(sub string) jwt.MapClaims {
|
||||
now := time.Now()
|
||||
return jwt.MapClaims{"iss": i.server.URL, "sub": sub, "aud": webIdentityAudience,
|
||||
"iat": now.Unix(), "exp": now.Add(10 * time.Minute).Unix()}
|
||||
}
|
||||
|
||||
func (i *webIdentityIssuer) token(t *testing.T, sub string, key *rsa.PrivateKey) string {
|
||||
t.Helper()
|
||||
tok := jwt.NewWithClaims(jwt.SigningMethodRS256, i.claims(sub))
|
||||
tok.Header["kid"] = "k1"
|
||||
signed, err := tok.SignedString(key)
|
||||
require.NoError(t, err)
|
||||
return signed
|
||||
}
|
||||
|
||||
func (i *webIdentityIssuer) tokenForAudience(t *testing.T, sub, aud string) string {
|
||||
t.Helper()
|
||||
claims := i.claims(sub)
|
||||
claims["aud"] = aud
|
||||
tok := jwt.NewWithClaims(jwt.SigningMethodRS256, claims)
|
||||
tok.Header["kid"] = "k1"
|
||||
signed, err := tok.SignedString(i.key)
|
||||
require.NoError(t, err)
|
||||
return signed
|
||||
}
|
||||
|
||||
func (i *webIdentityIssuer) unsignedToken(t *testing.T, sub string) string {
|
||||
t.Helper()
|
||||
signed, err := jwt.NewWithClaims(jwt.SigningMethodNone, i.claims(sub)).SignedString(jwt.UnsafeAllowNoneSignatureType)
|
||||
require.NoError(t, err)
|
||||
return signed
|
||||
}
|
||||
|
||||
func trustPolicyFor(issuerURL, sub string) string {
|
||||
doc, _ := json.Marshal(map[string]any{"Version": "2012-10-17", "Statement": []any{map[string]any{
|
||||
"Effect": "Allow", "Principal": map[string]any{"Federated": issuerURL},
|
||||
"Action": []string{"sts:AssumeRoleWithWebIdentity"},
|
||||
"Condition": map[string]any{"StringEquals": map[string]any{"oidc:sub": sub}},
|
||||
}}})
|
||||
return string(doc)
|
||||
}
|
||||
|
||||
// assumeWithWebIdentity returns session credentials, or nil and the error body.
|
||||
func assumeWithWebIdentity(t *testing.T, roleArn, token string) (*credentials.Credentials, string) {
|
||||
t.Helper()
|
||||
resp, err := callSTSAPI(t, url.Values{
|
||||
"Action": {"AssumeRoleWithWebIdentity"}, "Version": {"2011-06-15"},
|
||||
"RoleArn": {roleArn}, "RoleSessionName": {"web-identity-api"}, "WebIdentityToken": {token},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
if resp.StatusCode != http.StatusOK {
|
||||
return nil, string(body)
|
||||
}
|
||||
var out AssumeRoleWithWebIdentityTestResponse
|
||||
require.NoError(t, xml.Unmarshal(body, &out), "body: %s", body)
|
||||
c := out.Result.Credentials
|
||||
return credentials.NewStaticCredentials(c.AccessKeyId, c.SecretAccessKey, c.SessionToken), ""
|
||||
}
|
||||
|
||||
func s3ClientWith(t *testing.T, creds *credentials.Credentials) *s3.S3 {
|
||||
t.Helper()
|
||||
sess, err := session.NewSession(&aws.Config{
|
||||
Region: aws.String(TestRegion), Endpoint: aws.String(TestS3Endpoint),
|
||||
Credentials: creds, S3ForcePathStyle: aws.Bool(true), DisableSSL: aws.Bool(true),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return s3.New(sess)
|
||||
}
|
||||
|
||||
// TestWebIdentityWithProviderAndRoleManagedThroughIAMAPI configures STS
|
||||
// federation entirely at runtime — an OIDC provider, a managed policy and a role
|
||||
// created through the IAM API, with no static configuration — and checks that
|
||||
// the role admits exactly the subject its trust policy names, with exactly the
|
||||
// permissions of its attached policy.
|
||||
func TestWebIdentityWithProviderAndRoleManagedThroughIAMAPI(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("Skipping integration test in short mode")
|
||||
}
|
||||
if !isSTSEndpointRunning(t) {
|
||||
t.Fatal("SeaweedFS STS endpoint is not running at", TestSTSEndpoint, "- please run 'make setup-all-tests' first")
|
||||
}
|
||||
|
||||
framework := NewS3IAMTestFramework(t)
|
||||
defer framework.Cleanup()
|
||||
admin, err := framework.CreateIAMClientWithJWT("admin-user", "TestAdminRole")
|
||||
require.NoError(t, err)
|
||||
adminS3, err := framework.CreateS3ClientWithJWT("admin-user", "TestAdminRole")
|
||||
require.NoError(t, err)
|
||||
|
||||
issuer := newWebIdentityIssuer(t)
|
||||
bucket := framework.GenerateUniqueBucketName("web-identity")
|
||||
require.NoError(t, framework.CreateBucketWithCleanup(adminS3, bucket))
|
||||
|
||||
provider, err := admin.CreateOpenIDConnectProvider(&iam.CreateOpenIDConnectProviderInput{
|
||||
Url: aws.String(issuer.server.URL),
|
||||
ClientIDList: []*string{aws.String(webIdentityAudience)},
|
||||
// Required by this SDK version; pinning only applies to a TLS issuer,
|
||||
// and the test issuer is plain HTTP.
|
||||
ThumbprintList: []*string{aws.String("0000000000000000000000000000000000000000")},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
defer admin.DeleteOpenIDConnectProvider(&iam.DeleteOpenIDConnectProviderInput{OpenIDConnectProviderArn: provider.OpenIDConnectProviderArn})
|
||||
|
||||
policyDoc, _ := json.Marshal(map[string]any{"Version": "2012-10-17", "Statement": []any{map[string]any{
|
||||
"Effect": "Allow", "Action": []string{"s3:*"},
|
||||
"Resource": []string{"arn:aws:s3:::" + bucket, "arn:aws:s3:::" + bucket + "/*"},
|
||||
}}})
|
||||
policy, err := admin.CreatePolicy(&iam.CreatePolicyInput{
|
||||
PolicyName: aws.String(bucket + "-rw"), PolicyDocument: aws.String(string(policyDoc)),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
defer admin.DeletePolicy(&iam.DeletePolicyInput{PolicyArn: policy.Policy.Arn})
|
||||
|
||||
// Role names are at most 64 characters; the bucket name is longer.
|
||||
roleName := "web-identity-" + strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||
role, err := admin.CreateRole(&iam.CreateRoleInput{
|
||||
RoleName: aws.String(roleName),
|
||||
AssumeRolePolicyDocument: aws.String(trustPolicyFor(issuer.server.URL, webIdentitySubject)),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
defer admin.DeleteRole(&iam.DeleteRoleInput{RoleName: aws.String(roleName)})
|
||||
_, err = admin.AttachRolePolicy(&iam.AttachRolePolicyInput{RoleName: aws.String(roleName), PolicyArn: policy.Policy.Arn})
|
||||
require.NoError(t, err)
|
||||
defer admin.DetachRolePolicy(&iam.DetachRolePolicyInput{RoleName: aws.String(roleName), PolicyArn: policy.Policy.Arn})
|
||||
roleArn := aws.StringValue(role.Role.Arn)
|
||||
|
||||
t.Run("the trusted subject gets credentials scoped to the attached policy", func(t *testing.T) {
|
||||
creds, failure := assumeWithWebIdentity(t, roleArn, issuer.token(t, webIdentitySubject, issuer.key))
|
||||
require.NotNil(t, creds, "AssumeRoleWithWebIdentity refused the trusted subject: %s", failure)
|
||||
client := s3ClientWith(t, creds)
|
||||
_, err := client.PutObject(&s3.PutObjectInput{Bucket: aws.String(bucket), Key: aws.String("federated.txt")})
|
||||
assert.NoError(t, err, "the session cannot write the bucket its policy grants")
|
||||
_, err = client.CreateBucket(&s3.CreateBucketInput{Bucket: aws.String(bucket + "-other")})
|
||||
assert.Error(t, err, "the session created a bucket its policy does not grant")
|
||||
})
|
||||
|
||||
refusals := map[string]string{
|
||||
"another subject": issuer.token(t, "spiffe://example.org/ns/other/sa/other", issuer.key),
|
||||
"a token signed by another key": func() string {
|
||||
other, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
require.NoError(t, err)
|
||||
return issuer.token(t, webIdentitySubject, other)
|
||||
}(),
|
||||
"an unsigned token": issuer.unsignedToken(t, webIdentitySubject),
|
||||
// The provider accepts only its registered client IDs as audiences.
|
||||
"a token issued for another audience": issuer.tokenForAudience(t, webIdentitySubject, "some-other-service"),
|
||||
}
|
||||
for name, token := range refusals {
|
||||
t.Run("refuses "+name, func(t *testing.T) {
|
||||
creds, _ := assumeWithWebIdentity(t, roleArn, token)
|
||||
assert.Nil(t, creds, "AssumeRoleWithWebIdentity issued credentials for %s", name)
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("an updated trust policy takes effect", func(t *testing.T) {
|
||||
moved := "spiffe://example.org/ns/app/sa/moved"
|
||||
_, err := admin.UpdateAssumeRolePolicy(&iam.UpdateAssumeRolePolicyInput{
|
||||
RoleName: aws.String(roleName), PolicyDocument: aws.String(trustPolicyFor(issuer.server.URL, moved)),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
creds, _ := assumeWithWebIdentity(t, roleArn, issuer.token(t, webIdentitySubject, issuer.key))
|
||||
assert.Nil(t, creds, "the subject removed from the trust policy still assumes the role")
|
||||
creds, failure := assumeWithWebIdentity(t, roleArn, issuer.token(t, moved, issuer.key))
|
||||
assert.NotNil(t, creds, "the subject added to the trust policy was refused: %s", failure)
|
||||
})
|
||||
|
||||
t.Run("a session does not survive its role being deleted and created again", func(t *testing.T) {
|
||||
trust := trustPolicyFor(issuer.server.URL, webIdentitySubject)
|
||||
_, err := admin.UpdateAssumeRolePolicy(&iam.UpdateAssumeRolePolicyInput{RoleName: aws.String(roleName), PolicyDocument: aws.String(trust)})
|
||||
require.NoError(t, err)
|
||||
before, failure := assumeWithWebIdentity(t, roleArn, issuer.token(t, webIdentitySubject, issuer.key))
|
||||
require.NotNil(t, before, "precondition: %s", failure)
|
||||
|
||||
_, err = admin.DetachRolePolicy(&iam.DetachRolePolicyInput{RoleName: aws.String(roleName), PolicyArn: policy.Policy.Arn})
|
||||
require.NoError(t, err)
|
||||
_, err = admin.DeleteRole(&iam.DeleteRoleInput{RoleName: aws.String(roleName)})
|
||||
require.NoError(t, err)
|
||||
recreated, err := admin.CreateRole(&iam.CreateRoleInput{RoleName: aws.String(roleName), AssumeRolePolicyDocument: aws.String(trust)})
|
||||
require.NoError(t, err)
|
||||
_, err = admin.AttachRolePolicy(&iam.AttachRolePolicyInput{RoleName: aws.String(roleName), PolicyArn: policy.Policy.Arn})
|
||||
require.NoError(t, err)
|
||||
assert.NotEqual(t, aws.StringValue(role.Role.RoleId), aws.StringValue(recreated.Role.RoleId), "the recreated role reuses the deleted role's ID")
|
||||
|
||||
_, err = s3ClientWith(t, before).PutObject(&s3.PutObjectInput{Bucket: aws.String(bucket), Key: aws.String("revived.txt")})
|
||||
assert.Error(t, err, "a session of the deleted role works again under the new role of the same name")
|
||||
after, failure := assumeWithWebIdentity(t, roleArn, issuer.token(t, webIdentitySubject, issuer.key))
|
||||
require.NotNil(t, after, "the new role refuses its trusted subject: %s", failure)
|
||||
_, err = s3ClientWith(t, after).PutObject(&s3.PutObjectInput{Bucket: aws.String(bucket), Key: aws.String("fresh.txt")})
|
||||
assert.NoError(t, err, "a session of the new role cannot use its policy")
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,231 @@
|
||||
package remote_cache
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go/aws"
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const (
|
||||
evictRemoteS3 = "http://localhost:28334"
|
||||
evictRemoteMaster = "30334"
|
||||
evictRemoteFiler = "28889"
|
||||
evictRemoteVolume = "30341"
|
||||
evictRemoteWebdav = "27334"
|
||||
evictRemoteMetrics = "30326"
|
||||
|
||||
evictPrimaryS3 = "http://localhost:28333"
|
||||
evictPrimaryMaster = "30333"
|
||||
evictPrimaryFiler = "28887"
|
||||
evictPrimaryVolume = "30340"
|
||||
evictPrimaryWebdav = "27333"
|
||||
evictPrimaryMetrics = "30327"
|
||||
|
||||
evictBucket = "evictsrc"
|
||||
evictMount = "evictmnt"
|
||||
)
|
||||
|
||||
var miniLogPaths []string
|
||||
|
||||
func startMini(t *testing.T, dir string, args ...string) {
|
||||
t.Helper()
|
||||
require.NoError(t, os.MkdirAll(dir, 0755))
|
||||
logPath := filepath.Join(dir, "weed.log")
|
||||
logFile, err := os.Create(logPath)
|
||||
require.NoError(t, err)
|
||||
miniLogPaths = append(miniLogPaths, logPath)
|
||||
cmd := exec.Command(weedBinary, append([]string{"mini",
|
||||
"-dir=" + dir,
|
||||
"-s3.config=s3_config.json",
|
||||
"-s3.allowDeleteBucketNotEmpty=true",
|
||||
"-ip=127.0.0.1", "-ip.bind=127.0.0.1",
|
||||
}, args...)...)
|
||||
cmd.Stdout = logFile
|
||||
cmd.Stderr = logFile
|
||||
require.NoError(t, cmd.Start())
|
||||
t.Cleanup(func() {
|
||||
cmd.Process.Kill()
|
||||
cmd.Wait()
|
||||
logFile.Close()
|
||||
})
|
||||
}
|
||||
|
||||
func waitForHTTP(t *testing.T, url string) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(90 * time.Second)
|
||||
for time.Now().Before(deadline) {
|
||||
if resp, err := http.Get(url); err == nil {
|
||||
resp.Body.Close()
|
||||
return
|
||||
}
|
||||
time.Sleep(time.Second)
|
||||
}
|
||||
for _, p := range miniLogPaths {
|
||||
if data, err := os.ReadFile(p); err == nil {
|
||||
lines := strings.Split(string(data), "\n")
|
||||
if len(lines) > 30 {
|
||||
lines = lines[len(lines)-30:]
|
||||
}
|
||||
t.Logf("last lines of %s:\n%s", p, strings.Join(lines, "\n"))
|
||||
}
|
||||
}
|
||||
t.Fatalf("timed out waiting for %s", url)
|
||||
}
|
||||
|
||||
func shellOn(t *testing.T, masterPort, command string) string {
|
||||
t.Helper()
|
||||
cmd := exec.Command(weedBinary, "shell", "-master=localhost:"+masterPort)
|
||||
cmd.Stdin = strings.NewReader(command + "\nexit\n")
|
||||
out, err := cmd.CombinedOutput()
|
||||
require.NoErrorf(t, err, "shell %q failed: %s", command, out)
|
||||
return stripLogs(string(out))
|
||||
}
|
||||
|
||||
func chunkCountOn(t *testing.T, masterPort, path string) string {
|
||||
meta := shellOn(t, masterPort, "fs.meta.cat "+path)
|
||||
idx := strings.LastIndex(meta, "chunks ")
|
||||
require.GreaterOrEqualf(t, idx, 0, "no chunk count in %s", meta)
|
||||
return strings.Fields(meta[idx+len("chunks "):])[0]
|
||||
}
|
||||
|
||||
func volumeStats(t *testing.T, volumePort string) (size, garbage uint64) {
|
||||
t.Helper()
|
||||
resp, err := http.Get("http://localhost:" + volumePort + "/status")
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
var status struct {
|
||||
Volumes []struct {
|
||||
Size uint64 `json:"Size"`
|
||||
DeletedByteCount uint64 `json:"DeletedByteCount"`
|
||||
} `json:"Volumes"`
|
||||
}
|
||||
require.NoError(t, json.NewDecoder(resp.Body).Decode(&status))
|
||||
for _, v := range status.Volumes {
|
||||
size += v.Size
|
||||
garbage += v.DeletedByteCount
|
||||
}
|
||||
return size, garbage
|
||||
}
|
||||
|
||||
func readViaFiler(t *testing.T, filerPort, path string) []byte {
|
||||
t.Helper()
|
||||
resp, err := http.Get("http://localhost:" + filerPort + path)
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
require.Equal(t, http.StatusOK, resp.StatusCode, "read %s", path)
|
||||
data, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
return data
|
||||
}
|
||||
|
||||
// TestRemoteCacheEvictUnderPressure fills a cache constrained to two small
|
||||
// volumes with remote-mounted objects until writes fail, then verifies the
|
||||
// filer evicts the oldest synced entry, vacuums the garbage, and a later read
|
||||
// caches again.
|
||||
func TestRemoteCacheEvictUnderPressure(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("spawns two weed mini clusters")
|
||||
}
|
||||
if _, err := os.Stat(weedBinary); err != nil {
|
||||
t.Skipf("weed binary not found at %s; run make build-weed", weedBinary)
|
||||
}
|
||||
if isServerRunning(evictRemoteS3) || isServerRunning(evictPrimaryS3) {
|
||||
t.Skip("eviction test ports are already in use")
|
||||
}
|
||||
|
||||
tmp := t.TempDir()
|
||||
startMini(t, filepath.Join(tmp, "remote"),
|
||||
"-s3.port=28334", "-master.port="+evictRemoteMaster,
|
||||
"-filer.port="+evictRemoteFiler, "-volume.port="+evictRemoteVolume,
|
||||
"-webdav.port="+evictRemoteWebdav, "-metricsPort="+evictRemoteMetrics)
|
||||
waitForHTTP(t, evictRemoteS3)
|
||||
startMini(t, filepath.Join(tmp, "primary"),
|
||||
"-s3.port=28333", "-master.port="+evictPrimaryMaster,
|
||||
"-filer.port="+evictPrimaryFiler, "-volume.port="+evictPrimaryVolume,
|
||||
"-webdav.port="+evictPrimaryWebdav, "-metricsPort="+evictPrimaryMetrics,
|
||||
"-volume.allowUntrustedRemoteEndpoints", "-filer.allowUntrustedRemoteEndpoints",
|
||||
"-s3.allowUntrustedRemoteEndpoints",
|
||||
"-master.volumeSizeLimitMB=32", "-volume.max=2",
|
||||
"-filer.remoteCacheEvictThreshold=0.99")
|
||||
waitForHTTP(t, evictPrimaryS3)
|
||||
|
||||
remote := createS3Client(evictRemoteS3)
|
||||
_, err := remote.CreateBucket(&s3.CreateBucketInput{Bucket: aws.String(evictBucket)})
|
||||
require.NoError(t, err)
|
||||
for i := 0; i < 5; i++ {
|
||||
data := make([]byte, 16*1024*1024)
|
||||
for j := range data {
|
||||
data[j] = byte(i + j%251)
|
||||
}
|
||||
_, err = remote.PutObject(&s3.PutObjectInput{
|
||||
Bucket: aws.String(evictBucket),
|
||||
Key: aws.String(fmt.Sprintf("obj%d.bin", i)),
|
||||
Body: bytes.NewReader(data),
|
||||
})
|
||||
require.NoError(t, err)
|
||||
}
|
||||
|
||||
shellOn(t, evictPrimaryMaster, fmt.Sprintf(
|
||||
"remote.configure -name=evictremote -type=s3 -s3.access_key=%s -s3.secret_key=%s -s3.endpoint=%s -s3.region=us-east-1",
|
||||
accessKey, secretKey, evictRemoteS3))
|
||||
shellOn(t, evictPrimaryMaster, fmt.Sprintf(
|
||||
"remote.mount -dir=/buckets/%s -remote=evictremote/%s -nonempty", evictMount, evictBucket))
|
||||
shellOn(t, evictPrimaryMaster, fmt.Sprintf("remote.meta.sync -dir=/buckets/%s", evictMount))
|
||||
time.Sleep(2 * time.Second)
|
||||
|
||||
mount := "/buckets/" + evictMount
|
||||
|
||||
// obj0 caches alone so it is the oldest evictable entry.
|
||||
first := readViaFiler(t, evictPrimaryFiler, mount+"/obj0.bin")
|
||||
require.Len(t, first, 16*1024*1024)
|
||||
require.NotEqual(t, "0", chunkCountOn(t, evictPrimaryMaster, mount+"/obj0.bin"), "obj0 should be cached")
|
||||
|
||||
// 4 x 16MB against ~64MB of capacity: the fills overrun, hit the
|
||||
// capacity error path, and trigger eviction + vacuum.
|
||||
var wg sync.WaitGroup
|
||||
for i := 1; i <= 4; i++ {
|
||||
wg.Add(1)
|
||||
go func(i int) {
|
||||
defer wg.Done()
|
||||
data := readViaFiler(t, evictPrimaryFiler, fmt.Sprintf("%s/obj%d.bin", mount, i))
|
||||
assert.Len(t, data, 16*1024*1024)
|
||||
}(i)
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// Eviction must have dropped obj0's local chunks and vacuumed the
|
||||
// tombstoned bytes, leaving only live data within the two volumes.
|
||||
require.True(t, waitForCondition(t, func() bool {
|
||||
size, garbage := volumeStats(t, evictPrimaryVolume)
|
||||
return garbage == 0 && size <= 72*1024*1024
|
||||
}, 2*time.Minute, "volumes to be reclaimed by eviction+vacuum"),
|
||||
"evicted chunks were not reclaimed")
|
||||
|
||||
assert.Equal(t, "0", chunkCountOn(t, evictPrimaryMaster, mount+"/obj0.bin"),
|
||||
"oldest cached entry should be evicted back to remote-only")
|
||||
|
||||
// The cache self-heals: reading the evicted object re-caches it. Fills
|
||||
// still running from the concurrent wave may evict it again, so retry
|
||||
// the read until a commit sticks.
|
||||
var again []byte
|
||||
require.True(t, waitForCondition(t, func() bool {
|
||||
again = readViaFiler(t, evictPrimaryFiler, mount+"/obj0.bin")
|
||||
return chunkCountOn(t, evictPrimaryMaster, mount+"/obj0.bin") != "0"
|
||||
}, 2*time.Minute, "obj0 to re-cache"),
|
||||
"evicted object did not re-cache on read")
|
||||
assert.Equal(t, first, again)
|
||||
}
|
||||
@@ -89,6 +89,7 @@ type FilerOptions struct {
|
||||
s3ConfigFile *string // optional path to static S3 identity config
|
||||
|
||||
allowUntrustedRemoteEndpoints *bool
|
||||
remoteCacheEvictThreshold *float64
|
||||
// shutdownCtx, when non-nil, tells startFiler to gracefully shut down its
|
||||
// HTTP/gRPC servers once the ctx is cancelled. Used by integration tests
|
||||
// and by weed mini; nil for standalone weed filer.
|
||||
@@ -134,6 +135,7 @@ func init() {
|
||||
f.tusMaxSizeMB = cmdFiler.Flag.Int("tusMaxSizeMB", 5*1024, "maximum TUS upload size in MB")
|
||||
f.tusSessionExpiry = cmdFiler.Flag.Duration("tusSessionExpiry", 24*time.Hour, "incomplete TUS upload sessions are cleaned up after this duration, e.g. \"48h\", \"7h30m\"")
|
||||
f.allowUntrustedRemoteEndpoints = cmdFiler.Flag.Bool("allowUntrustedRemoteEndpoints", false, allowUntrustedRemoteEndpointsUsage)
|
||||
f.remoteCacheEvictThreshold = cmdFiler.Flag.Float64("remoteCacheEvictThreshold", 0.9, "evict remote-cached objects (oldest first) when any volume disk exceeds this usage fraction; 0 disables")
|
||||
|
||||
// start s3 on filer
|
||||
filerStartS3 = cmdFiler.Flag.Bool("s3", false, "whether to start S3 gateway")
|
||||
@@ -407,6 +409,7 @@ func (fo *FilerOptions) startFiler() {
|
||||
CredentialManager: credentialManager,
|
||||
|
||||
AllowUntrustedRemoteEndpoints: *fo.allowUntrustedRemoteEndpoints,
|
||||
RemoteCacheEvictThreshold: *fo.remoteCacheEvictThreshold,
|
||||
})
|
||||
if nfs_err != nil {
|
||||
glog.Fatalf("Filer startup error: %v", nfs_err)
|
||||
|
||||
+22
-19
@@ -46,18 +46,19 @@ const (
|
||||
)
|
||||
|
||||
type MasterOptions struct {
|
||||
port *int
|
||||
portGrpc *int
|
||||
ip *string
|
||||
ipBind *string
|
||||
metaFolder *string
|
||||
peers *string
|
||||
mastersDeprecated *string // deprecated, for backward compatibility in master.follower
|
||||
volumeSizeLimitMB *uint
|
||||
fileSizeLimitMB *int
|
||||
volumePreallocate *bool
|
||||
maxParallelVacuumPerServer *int
|
||||
vacuumIntervalSeconds *int
|
||||
port *int
|
||||
portGrpc *int
|
||||
ip *string
|
||||
ipBind *string
|
||||
metaFolder *string
|
||||
peers *string
|
||||
mastersDeprecated *string // deprecated, for backward compatibility in master.follower
|
||||
volumeSizeLimitMB *uint
|
||||
fileSizeLimitMB *int
|
||||
volumePreallocate *bool
|
||||
maxParallelVacuumPerServer *int
|
||||
vacuumIntervalSeconds *int
|
||||
vacuumDeleteEmptyAfterSeconds *int
|
||||
// pulseSeconds *int
|
||||
defaultReplication *string
|
||||
garbageThreshold *float64
|
||||
@@ -95,6 +96,7 @@ func init() {
|
||||
m.volumePreallocate = cmdMaster.Flag.Bool("volumePreallocate", false, "Preallocate disk space for volumes.")
|
||||
m.maxParallelVacuumPerServer = cmdMaster.Flag.Int("maxParallelVacuumPerServer", 1, "maximum number of volumes to vacuum in parallel per volume server")
|
||||
m.vacuumIntervalSeconds = cmdMaster.Flag.Int("vacuumIntervalSeconds", 840, "seconds between automatic vacuum sweeps")
|
||||
m.vacuumDeleteEmptyAfterSeconds = cmdMaster.Flag.Int("vacuumDeleteEmptyAfterSeconds", 0, "automatic sweep deletes volume copies that stay empty this many seconds; 0 disables")
|
||||
// m.pulseSeconds = cmdMaster.Flag.Int("pulseSeconds", 5, "number of seconds between heartbeats")
|
||||
m.defaultReplication = cmdMaster.Flag.String("defaultReplication", "", "Default replication type if not specified.")
|
||||
m.garbageThreshold = cmdMaster.Flag.Float64("garbageThreshold", 0.3, "threshold to vacuum and reclaim spaces")
|
||||
@@ -469,13 +471,14 @@ func peerIndex(self pb.ServerAddress, peers []pb.ServerAddress) int {
|
||||
func (m *MasterOptions) toMasterOption(whiteList []string) *weed_server.MasterOption {
|
||||
masterAddress := pb.NewServerAddress(*m.ip, *m.port, *m.portGrpc)
|
||||
return &weed_server.MasterOption{
|
||||
Master: masterAddress,
|
||||
MetaFolder: *m.metaFolder,
|
||||
VolumeSizeLimitMB: uint32(*m.volumeSizeLimitMB),
|
||||
FileSizeLimitMB: *m.fileSizeLimitMB,
|
||||
VolumePreallocate: *m.volumePreallocate,
|
||||
MaxParallelVacuumPerServer: *m.maxParallelVacuumPerServer,
|
||||
VacuumIntervalSeconds: *m.vacuumIntervalSeconds,
|
||||
Master: masterAddress,
|
||||
MetaFolder: *m.metaFolder,
|
||||
VolumeSizeLimitMB: uint32(*m.volumeSizeLimitMB),
|
||||
FileSizeLimitMB: *m.fileSizeLimitMB,
|
||||
VolumePreallocate: *m.volumePreallocate,
|
||||
MaxParallelVacuumPerServer: *m.maxParallelVacuumPerServer,
|
||||
VacuumIntervalSeconds: *m.vacuumIntervalSeconds,
|
||||
VacuumDeleteEmptyAfterSeconds: *m.vacuumDeleteEmptyAfterSeconds,
|
||||
// PulseSeconds: *m.pulseSeconds,
|
||||
DefaultReplicaPlacement: *m.defaultReplication,
|
||||
GarbageThreshold: *m.garbageThreshold,
|
||||
|
||||
@@ -48,6 +48,7 @@ func init() {
|
||||
mf.raftResumeState = aws.Bool(false)
|
||||
mf.maxParallelVacuumPerServer = aws.Int(1)
|
||||
mf.vacuumIntervalSeconds = aws.Int(840)
|
||||
mf.vacuumDeleteEmptyAfterSeconds = aws.Int(0)
|
||||
mf.telemetryUrl = aws.String("https://telemetry.seaweedfs.com/api/collect")
|
||||
mf.telemetryEnabled = aws.Bool(false)
|
||||
}
|
||||
|
||||
@@ -428,6 +428,7 @@ func initMiniMasterFlags() {
|
||||
miniMasterOptions.volumePreallocate = cmdMini.Flag.Bool("master.volumePreallocate", false, "Preallocate disk space for volumes.")
|
||||
miniMasterOptions.maxParallelVacuumPerServer = cmdMini.Flag.Int("master.maxParallelVacuumPerServer", 1, "maximum number of volumes to vacuum in parallel on one volume server")
|
||||
miniMasterOptions.vacuumIntervalSeconds = cmdMini.Flag.Int("master.vacuumIntervalSeconds", 840, "seconds between automatic vacuum sweeps")
|
||||
miniMasterOptions.vacuumDeleteEmptyAfterSeconds = cmdMini.Flag.Int("master.vacuumDeleteEmptyAfterSeconds", 0, "automatic sweep deletes volume copies that stay empty this many seconds; 0 disables")
|
||||
miniMasterOptions.defaultReplication = cmdMini.Flag.String("master.defaultReplication", "", "Default replication type if not specified.")
|
||||
miniMasterOptions.garbageThreshold = cmdMini.Flag.Float64("master.garbageThreshold", 0.3, "threshold to vacuum and reclaim spaces")
|
||||
miniMasterOptions.metricsAddress = cmdMini.Flag.String("master.metrics.address", "", "Prometheus gateway address")
|
||||
@@ -466,6 +467,7 @@ func initMiniFilerFlags() {
|
||||
miniFilerOptions.tusMaxSizeMB = cmdMini.Flag.Int("filer.tusMaxSizeMB", 5*1024, "maximum TUS upload size in MB")
|
||||
miniFilerOptions.tusSessionExpiry = cmdMini.Flag.Duration("filer.tusSessionExpiry", 24*time.Hour, "incomplete TUS upload sessions are cleaned up after this duration")
|
||||
miniFilerOptions.allowUntrustedRemoteEndpoints = cmdMini.Flag.Bool("filer.allowUntrustedRemoteEndpoints", false, allowUntrustedRemoteEndpointsUsage)
|
||||
miniFilerOptions.remoteCacheEvictThreshold = cmdMini.Flag.Float64("filer.remoteCacheEvictThreshold", 0.9, "evict remote-cached objects (oldest first) when any volume disk exceeds this usage fraction; 0 disables")
|
||||
}
|
||||
|
||||
// initMiniVolumeFlags initializes Volume server flag options
|
||||
|
||||
@@ -41,6 +41,7 @@ copy_2 = 6 # create 2 x 6 = 12 actual volumes
|
||||
copy_3 = 3 # create 3 x 3 = 9 actual volumes
|
||||
copy_other = 1 # create n x 1 = n actual volumes
|
||||
threshold = 0.9 # create threshold
|
||||
reservation_timeout = "5m"# capacity reservation timeout before unreleased reservations expire
|
||||
disable = false # disables volume growth if true
|
||||
|
||||
# configuration flags for replication
|
||||
|
||||
@@ -99,6 +99,7 @@ func init() {
|
||||
masterOptions.volumePreallocate = cmdServer.Flag.Bool("master.volumePreallocate", false, "Preallocate disk space for volumes.")
|
||||
masterOptions.maxParallelVacuumPerServer = cmdServer.Flag.Int("master.maxParallelVacuumPerServer", 1, "maximum number of volumes to vacuum in parallel on one volume server")
|
||||
masterOptions.vacuumIntervalSeconds = cmdServer.Flag.Int("master.vacuumIntervalSeconds", 840, "seconds between automatic vacuum sweeps")
|
||||
masterOptions.vacuumDeleteEmptyAfterSeconds = cmdServer.Flag.Int("master.vacuumDeleteEmptyAfterSeconds", 0, "automatic sweep deletes volume copies that stay empty this many seconds; 0 disables")
|
||||
masterOptions.defaultReplication = cmdServer.Flag.String("master.defaultReplication", "", "Default replication type if not specified.")
|
||||
masterOptions.garbageThreshold = cmdServer.Flag.Float64("master.garbageThreshold", 0.3, "threshold to vacuum and reclaim spaces")
|
||||
masterOptions.metricsAddress = cmdServer.Flag.String("master.metrics.address", "", "Prometheus gateway address")
|
||||
@@ -135,6 +136,7 @@ func init() {
|
||||
filerOptions.tusMaxSizeMB = cmdServer.Flag.Int("filer.tusMaxSizeMB", 5*1024, "maximum TUS upload size in MB")
|
||||
filerOptions.tusSessionExpiry = cmdServer.Flag.Duration("filer.tusSessionExpiry", 24*time.Hour, "incomplete TUS upload sessions are cleaned up after this duration, e.g. \"48h\", \"7h30m\"")
|
||||
filerOptions.allowUntrustedRemoteEndpoints = cmdServer.Flag.Bool("filer.allowUntrustedRemoteEndpoints", false, allowUntrustedRemoteEndpointsUsage)
|
||||
filerOptions.remoteCacheEvictThreshold = cmdServer.Flag.Float64("filer.remoteCacheEvictThreshold", 0.9, "evict remote-cached objects (oldest first) when any volume disk exceeds this usage fraction; 0 disables")
|
||||
|
||||
serverOptions.v.port = cmdServer.Flag.Int("volume.port", 8080, "volume server http listen port")
|
||||
serverOptions.v.portGrpc = cmdServer.Flag.Int("volume.port.grpc", 0, "volume server grpc listen port")
|
||||
|
||||
@@ -380,15 +380,6 @@ func fetchWholeChunk(ctx context.Context, bytesBuffer *bytes.Buffer, lookupFileI
|
||||
})
|
||||
}
|
||||
|
||||
func fetchChunkRange(ctx context.Context, buffer []byte, lookupFileIdFn wdclient.LookupFileIdFunctionType, fileId string, cipherKey []byte, isGzipped bool, offset int64, refreshUrls util_http.RefreshUrlsFunc) (int, error) {
|
||||
urlStrings, err := lookupFileIdFn(ctx, fileId)
|
||||
if err != nil {
|
||||
glog.ErrorfCtx(ctx, "operation LookupFileId %s failed, err: %v", fileId, err)
|
||||
return 0, err
|
||||
}
|
||||
return util_http.RetriedFetchChunkData(ctx, buffer, urlStrings, cipherKey, isGzipped, false, offset, fileId, refreshUrls)
|
||||
}
|
||||
|
||||
// retriedStreamFetchChunkData streams a chunk from the first location that
|
||||
// answers. refreshUrls may be nil; when a location failed and a later one
|
||||
// answered, it is called so the reads that follow start from a fresh list.
|
||||
|
||||
@@ -185,6 +185,15 @@ func (cv *ChunkView) IsFullChunk() bool {
|
||||
return cv.OffsetInChunk == 0 && cv.ViewSize == cv.ChunkSize
|
||||
}
|
||||
|
||||
// CanRangeFetch reports whether fetching just the view's byte range avoids
|
||||
// reading more than the view needs. Ciphered and compressed chunks are
|
||||
// stored and served whole — a range on either still costs a full read plus
|
||||
// decrypt or decompress on the volume server — so partial views of them
|
||||
// take the shared whole-chunk path instead.
|
||||
func (cv *ChunkView) CanRangeFetch() bool {
|
||||
return cv.CipherKey == nil && !cv.IsGzipped
|
||||
}
|
||||
|
||||
func ViewFromChunks(ctx context.Context, lookupFileIdFn wdclient.LookupFileIdFunctionType, chunks []*filer_pb.FileChunk, offset int64, size int64) (chunkViews *IntervalList[*ChunkView]) {
|
||||
|
||||
visibles, _ := NonOverlappingVisibleIntervals(ctx, lookupFileIdFn, chunks, offset, offset+size)
|
||||
|
||||
+16
-4
@@ -23,6 +23,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/remote_pb"
|
||||
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/protobuf/proto"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
@@ -327,7 +328,7 @@ func (f *Filer) CreateEntry(ctx context.Context, entry *Entry, existing *Entry,
|
||||
return fmt.Errorf("%s: %w", entry.FullPath, filer_pb.ErrEntryAlreadyExists)
|
||||
}
|
||||
glog.V(4).InfofCtx(ctx, "UpdateEntry %s: old entry: %v", entry.FullPath, oldEntry.Name())
|
||||
if err := f.UpdateEntry(ctx, oldEntry, entry); err != nil {
|
||||
if err := f.UpdateEntry(ctx, oldEntry, entry, isFromOtherCluster); err != nil {
|
||||
if errors.Is(err, filer_pb.ErrExistingIsDirectory) || errors.Is(err, filer_pb.ErrExistingIsFile) {
|
||||
glog.V(2).InfofCtx(ctx, "update entry %s: %v", entry.FullPath, err)
|
||||
} else {
|
||||
@@ -482,7 +483,7 @@ func (f *Filer) EnsureDirectoryEntry(ctx context.Context, dirPath util.FullPath,
|
||||
narrowed := existing.ShallowClone()
|
||||
narrowed.Mode = existing.Mode&^restorableModeBits | kept
|
||||
glog.V(1).InfofCtx(ctx, "restore directory %s: narrowing %v to %v", dirPath, existing.Mode, narrowed.Mode)
|
||||
if err := f.UpdateEntry(ctx, existing, narrowed); err != nil {
|
||||
if err := f.UpdateEntry(ctx, existing, narrowed, false); err != nil {
|
||||
return err
|
||||
}
|
||||
f.NotifyUpdateEvent(ctx, existing, narrowed, false, false, nil)
|
||||
@@ -515,7 +516,7 @@ func (f *Filer) EnsureDirectoryEntry(ctx context.Context, dirPath util.FullPath,
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *Filer) UpdateEntry(ctx context.Context, oldEntry, entry *Entry) (err error) {
|
||||
func (f *Filer) UpdateEntry(ctx context.Context, oldEntry, entry *Entry, isFromOtherCluster bool) (err error) {
|
||||
if oldEntry != nil {
|
||||
entry.Attr.Crtime = oldEntry.Attr.Crtime
|
||||
if oldEntry.Attr.Inode != 0 {
|
||||
@@ -535,6 +536,17 @@ func (f *Filer) UpdateEntry(ctx context.Context, oldEntry, entry *Entry) (err er
|
||||
glog.V(2).InfofCtx(ctx, "existing %s is a file", oldEntry.FullPath)
|
||||
return fmt.Errorf("%s: %w", oldEntry.FullPath, filer_pb.ErrExistingIsFile)
|
||||
}
|
||||
// A local write to a remote-backed entry leaves the copy on remote
|
||||
// stale until a sync re-uploads it. Content changes that arrive
|
||||
// without a fresh sync stamp are unsynced; clear the stamp so nothing
|
||||
// mistakes the still-local chunks for a re-fetchable cache copy.
|
||||
// Replicated updates carry the writer's authoritative stamp.
|
||||
if !isFromOtherCluster && oldEntry.Remote != nil && entry.Remote != nil &&
|
||||
oldEntry.Remote.LastLocalSyncTsNs == entry.Remote.LastLocalSyncTsNs &&
|
||||
!chunksEqual(oldEntry.Chunks, entry.Chunks) {
|
||||
entry.Remote = proto.Clone(entry.Remote).(*filer_pb.RemoteEntry)
|
||||
entry.Remote.LastLocalSyncTsNs = 0
|
||||
}
|
||||
}
|
||||
if entry.Attr.Atime.IsZero() {
|
||||
entry.Attr.Atime = entryInitialAtime(entry.Attr)
|
||||
@@ -606,7 +618,7 @@ func (f *Filer) doListDirectoryEntries(ctx context.Context, p util.FullPath, sta
|
||||
lastFileName, err = f.Store.ListDirectoryPrefixedEntries(ctx, p, startFileName, inclusive, limit, prefix, func(entry *Entry) (bool, error) {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
glog.Errorf("Context is done.")
|
||||
glog.V(1).InfofCtx(ctx, "listing %q canceled: %v", p, ctx.Err())
|
||||
return false, fmt.Errorf("context canceled: %w", ctx.Err())
|
||||
default:
|
||||
if entry.TtlSec > 0 && !entry.IsDirectory() {
|
||||
|
||||
@@ -306,24 +306,29 @@ func (f *Filer) loopProcessingDeletion() {
|
||||
glog.V(0).Infof("deletion processor shutting down")
|
||||
return
|
||||
case <-ticker.C:
|
||||
f.FileIdDeletionQueue.Consume(func(fileIds []string) {
|
||||
for i := 0; i < len(fileIds); i += DeletionBatchSize {
|
||||
end := i + DeletionBatchSize
|
||||
if end > len(fileIds) {
|
||||
end = len(fileIds)
|
||||
}
|
||||
toDeleteFileIds := fileIds[i:end]
|
||||
f.processDeletionBatch(toDeleteFileIds, lookupFunc)
|
||||
}
|
||||
})
|
||||
f.FlushFileIdDeletionQueue(context.Background(), lookupFunc)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func (f *Filer) FlushFileIdDeletionQueue(ctx context.Context, lookupFunc func([]string) (map[string]*operation.LookupResult, error)) (consumed []string) {
|
||||
f.FileIdDeletionQueue.Consume(func(fileIds []string) {
|
||||
consumed = fileIds
|
||||
for i := 0; i < len(fileIds); i += DeletionBatchSize {
|
||||
end := i + DeletionBatchSize
|
||||
if end > len(fileIds) {
|
||||
end = len(fileIds)
|
||||
}
|
||||
f.processDeletionBatch(ctx, fileIds[i:end], lookupFunc)
|
||||
}
|
||||
})
|
||||
return consumed
|
||||
}
|
||||
|
||||
// processDeletionBatch handles deletion of a batch of file IDs and processes results.
|
||||
// It classifies errors into retryable and permanent categories, adds retryable failures
|
||||
// to the retry queue, and logs appropriate messages.
|
||||
func (f *Filer) processDeletionBatch(toDeleteFileIds []string, lookupFunc func([]string) (map[string]*operation.LookupResult, error)) {
|
||||
func (f *Filer) processDeletionBatch(ctx context.Context, toDeleteFileIds []string, lookupFunc func([]string) (map[string]*operation.LookupResult, error)) {
|
||||
// Deduplicate file IDs to prevent incorrect retry count increments for the same file ID within a single batch.
|
||||
uniqueFileIdsSlice := make([]string, 0, len(toDeleteFileIds))
|
||||
processed := make(map[string]struct{}, len(toDeleteFileIds))
|
||||
@@ -339,7 +344,7 @@ func (f *Filer) processDeletionBatch(toDeleteFileIds []string, lookupFunc func([
|
||||
}
|
||||
|
||||
// Delete files and classify outcomes
|
||||
outcomes := deleteFilesAndClassify(f.GrpcDialOption, uniqueFileIdsSlice, lookupFunc)
|
||||
outcomes := deleteFilesAndClassify(ctx, f.GrpcDialOption, uniqueFileIdsSlice, lookupFunc)
|
||||
|
||||
// Process outcomes
|
||||
var successCount, notFoundCount, retryableErrorCount, permanentErrorCount int
|
||||
@@ -405,9 +410,9 @@ type deletionOutcome struct {
|
||||
}
|
||||
|
||||
// deleteFilesAndClassify performs deletion and classifies outcomes for a list of file IDs
|
||||
func deleteFilesAndClassify(grpcDialOption grpc.DialOption, fileIds []string, lookupFunc func([]string) (map[string]*operation.LookupResult, error)) map[string]deletionOutcome {
|
||||
func deleteFilesAndClassify(ctx context.Context, grpcDialOption grpc.DialOption, fileIds []string, lookupFunc func([]string) (map[string]*operation.LookupResult, error)) map[string]deletionOutcome {
|
||||
// Perform deletion
|
||||
results := operation.DeleteFileIdsWithLookupVolumeId(grpcDialOption, fileIds, lookupFunc)
|
||||
results := operation.DeleteFileIdsWithLookupVolumeId(ctx, grpcDialOption, fileIds, lookupFunc)
|
||||
|
||||
// Group results by file ID to handle multiple results for replicated volumes
|
||||
resultsByFileId := make(map[string][]*volume_server_pb.DeleteResult)
|
||||
@@ -545,7 +550,7 @@ func (f *Filer) processRetryBatch(readyItems []*DeletionRetryItem, lookupFunc fu
|
||||
}
|
||||
|
||||
// Delete files and classify outcomes
|
||||
outcomes := deleteFilesAndClassify(f.GrpcDialOption, fileIds, lookupFunc)
|
||||
outcomes := deleteFilesAndClassify(context.Background(), f.GrpcDialOption, fileIds, lookupFunc)
|
||||
|
||||
// Process outcomes - iterate over readyItems to ensure all items are accounted for
|
||||
var successCount, notFoundCount, retryCount, permanentErrorCount int
|
||||
|
||||
@@ -173,7 +173,7 @@ func TestUpdateEntryPreservesExistingInode(t *testing.T) {
|
||||
},
|
||||
}
|
||||
|
||||
err := f.UpdateEntry(context.Background(), original, updated)
|
||||
err := f.UpdateEntry(context.Background(), original, updated, false)
|
||||
require.Error(t, err)
|
||||
|
||||
updated = &Entry{
|
||||
@@ -182,7 +182,7 @@ func TestUpdateEntryPreservesExistingInode(t *testing.T) {
|
||||
Mode: 0o600,
|
||||
},
|
||||
}
|
||||
err = f.UpdateEntry(context.Background(), original, updated)
|
||||
err = f.UpdateEntry(context.Background(), original, updated, false)
|
||||
require.NoError(t, err)
|
||||
|
||||
stored, findErr := store.FindEntry(context.Background(), original.FullPath)
|
||||
@@ -208,7 +208,7 @@ func TestUpdateEntryBackfillsMissingLegacyInode(t *testing.T) {
|
||||
Mode: 0o640,
|
||||
},
|
||||
}
|
||||
err := f.UpdateEntry(context.Background(), original, updated)
|
||||
err := f.UpdateEntry(context.Background(), original, updated, false)
|
||||
require.NoError(t, err)
|
||||
|
||||
stored, findErr := store.FindEntry(context.Background(), original.FullPath)
|
||||
|
||||
@@ -104,3 +104,23 @@ func TestExpiredFileIsDeletedOnRead(t *testing.T) {
|
||||
require.ErrorIs(t, err, filer_pb.ErrNotFound,
|
||||
"native TTL lookup should remove the expired metadata row")
|
||||
}
|
||||
|
||||
func TestListDirectoryEntriesContextCanceled(t *testing.T) {
|
||||
f, store := newTestFilerWithStubStore()
|
||||
ctx := context.Background()
|
||||
|
||||
require.NoError(t, store.InsertEntry(ctx, &Entry{
|
||||
FullPath: util.FullPath("/dir/file1.txt"),
|
||||
Attr: Attr{Mode: 0o644},
|
||||
}))
|
||||
|
||||
canceledCtx, cancel := context.WithCancel(ctx)
|
||||
cancel()
|
||||
|
||||
_, _, err := f.doListDirectoryEntries(canceledCtx, util.FullPath("/dir"), "", false, 10, "", func(entry *Entry) (bool, error) {
|
||||
return true, nil
|
||||
})
|
||||
require.Error(t, err)
|
||||
assert.ErrorContains(t, err, "context canceled")
|
||||
}
|
||||
|
||||
@@ -0,0 +1,89 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"sort"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
)
|
||||
|
||||
func chunksEqual(a, b []*filer_pb.FileChunk) bool {
|
||||
if len(a) != len(b) {
|
||||
return false
|
||||
}
|
||||
for i := range a {
|
||||
if a[i].GetFileIdString() != b[i].GetFileIdString() ||
|
||||
a[i].Size != b[i].Size ||
|
||||
a[i].Offset != b[i].Offset ||
|
||||
a[i].ModifiedTsNs != b[i].ModifiedTsNs {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// IsEvictableRemoteEntry reports whether an entry's local chunks are backed by
|
||||
// a synchronized remote copy, mirroring the checks remote.uncache applies:
|
||||
// remote-backed, chunks present, and not ahead of the remote version.
|
||||
func IsEvictableRemoteEntry(entry *Entry) bool {
|
||||
if entry.IsDirectory() || entry.Remote == nil {
|
||||
return false
|
||||
}
|
||||
if entry.Remote.LastLocalSyncTsNs <= 0 || len(entry.GetChunks()) == 0 {
|
||||
return false
|
||||
}
|
||||
if entry.Remote.LastLocalSyncTsNs < entry.Mtime.UnixNano() {
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// ListEvictableRemoteEntries walks every mounted directory and returns
|
||||
// synchronized remote entries holding local chunks, oldest cached first.
|
||||
func (f *Filer) ListEvictableRemoteEntries(ctx context.Context, mounts []util.FullPath, minCacheAge time.Duration) (out []*Entry) {
|
||||
cutoffNs := time.Now().UnixNano() - minCacheAge.Nanoseconds()
|
||||
for _, dir := range mounts {
|
||||
if err := f.collectEvictableRemoteEntries(ctx, dir, cutoffNs, &out); err != nil {
|
||||
glog.WarningfCtx(ctx, "list evictable remote entries under %s: %v", dir, err)
|
||||
}
|
||||
}
|
||||
sort.Slice(out, func(i, j int) bool {
|
||||
return out[i].Remote.LastLocalSyncTsNs < out[j].Remote.LastLocalSyncTsNs
|
||||
})
|
||||
return out
|
||||
}
|
||||
|
||||
func (f *Filer) collectEvictableRemoteEntries(ctx context.Context, dir util.FullPath, cutoffNs int64, out *[]*Entry) error {
|
||||
startFileName := ""
|
||||
for {
|
||||
var subDirs []util.FullPath
|
||||
lastFileName, err := f.Store.ListDirectoryEntries(ctx, dir, startFileName, false, 1024, func(entry *Entry) (bool, error) {
|
||||
if err := ctx.Err(); err != nil {
|
||||
return false, err
|
||||
}
|
||||
if entry.IsDirectory() {
|
||||
subDirs = append(subDirs, entry.FullPath)
|
||||
return true, nil
|
||||
}
|
||||
if entry.Remote != nil && entry.Remote.LastLocalSyncTsNs > 0 && entry.Remote.LastLocalSyncTsNs <= cutoffNs && IsEvictableRemoteEntry(entry) {
|
||||
*out = append(*out, entry)
|
||||
}
|
||||
return true, nil
|
||||
})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
for _, subDir := range subDirs {
|
||||
if err := f.collectEvictableRemoteEntries(ctx, subDir, cutoffNs, out); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
if lastFileName == "" {
|
||||
return nil
|
||||
}
|
||||
startFileName = lastFileName
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"os"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func remoteCachedEntry(path string, syncTsNs int64, mtime time.Time, chunks int) *Entry {
|
||||
entry := &Entry{
|
||||
FullPath: util.FullPath(path),
|
||||
Attr: Attr{
|
||||
Mtime: mtime,
|
||||
Crtime: mtime,
|
||||
Mode: 0644,
|
||||
Uid: 1,
|
||||
Gid: 1,
|
||||
Mime: "application/octet-stream",
|
||||
Md5: nil,
|
||||
FileSize: 0,
|
||||
},
|
||||
Remote: &filer_pb.RemoteEntry{
|
||||
RemoteMtime: mtime.Unix(),
|
||||
LastLocalSyncTsNs: syncTsNs,
|
||||
RemoteETag: "etag",
|
||||
RemoteSize: 100,
|
||||
},
|
||||
}
|
||||
for i := 0; i < chunks; i++ {
|
||||
entry.Chunks = append(entry.Chunks, &filer_pb.FileChunk{FileId: "1,01637037d6", Size: 100})
|
||||
}
|
||||
return entry
|
||||
}
|
||||
|
||||
func TestIsEvictableRemoteEntry(t *testing.T) {
|
||||
now := time.Now()
|
||||
synced := now.Add(-time.Hour).UnixNano()
|
||||
mtime := now.Add(-time.Hour)
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
entry *Entry
|
||||
expected bool
|
||||
}{
|
||||
{"directory", &Entry{FullPath: "/d", Attr: Attr{Mode: os.ModeDir | 0755}}, false},
|
||||
{"local only, no remote", &Entry{FullPath: "/f", Attr: Attr{Mtime: mtime, Mode: 0644}}, false},
|
||||
{"remote only, never cached", remoteCachedEntry("/f", 0, mtime, 0), false},
|
||||
{"remote, chunks cleared", remoteCachedEntry("/f", synced, mtime, 0), false},
|
||||
{"dirty, newer than remote", remoteCachedEntry("/f", synced, now, 1), false},
|
||||
{"same-second write after sync", remoteCachedEntry("/f",
|
||||
now.Truncate(time.Second).Add(100*time.Millisecond).UnixNano(),
|
||||
now.Truncate(time.Second).Add(900*time.Millisecond), 1), false},
|
||||
{"same-second sync after write", remoteCachedEntry("/f",
|
||||
now.Truncate(time.Second).Add(900*time.Millisecond).UnixNano(),
|
||||
now.Truncate(time.Second).Add(100*time.Millisecond), 1), true},
|
||||
{"synced and cached", remoteCachedEntry("/f", synced, mtime, 1), true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
assert.Equal(t, tt.expected, IsEvictableRemoteEntry(tt.entry), tt.name)
|
||||
}
|
||||
}
|
||||
|
||||
func TestListEvictableRemoteEntries(t *testing.T) {
|
||||
now := time.Now()
|
||||
mtime := now.Add(-2 * time.Hour)
|
||||
oldSync := now.Add(-time.Hour).UnixNano()
|
||||
newSync := now.Add(-time.Second).UnixNano()
|
||||
|
||||
store := newStubFilerStore()
|
||||
f := newTestFiler(t, store, NewFilerRemoteStorage())
|
||||
mounts := []util.FullPath{"/buckets/mybucket"}
|
||||
|
||||
seed := func(e *Entry) {
|
||||
require.NoError(t, f.CreateEntry(context.Background(), e, nil, false, false, nil, false, 255))
|
||||
}
|
||||
seed(remoteCachedEntry("/buckets/mybucket/old.bin", oldSync, mtime, 1))
|
||||
seed(remoteCachedEntry("/buckets/mybucket/fresh.bin", newSync, mtime, 1))
|
||||
seed(remoteCachedEntry("/buckets/mybucket/remoteonly.bin", 0, mtime, 0))
|
||||
seed(remoteCachedEntry("/buckets/mybucket/dirty.bin", oldSync, now, 1))
|
||||
seed(&Entry{FullPath: "/buckets/mybucket/plain.bin", Attr: Attr{Mtime: mtime, Mode: 0644}})
|
||||
|
||||
store.entries["/buckets/mybucket/sub"] = &Entry{
|
||||
FullPath: "/buckets/mybucket/sub",
|
||||
Attr: Attr{Mode: os.ModeDir | 0755, Mtime: mtime},
|
||||
}
|
||||
seed(remoteCachedEntry("/buckets/mybucket/sub/nested.bin", oldSync-1000, mtime, 1))
|
||||
|
||||
got := f.ListEvictableRemoteEntries(context.Background(), mounts, 0)
|
||||
var paths []string
|
||||
for _, e := range got {
|
||||
paths = append(paths, string(e.FullPath))
|
||||
}
|
||||
assert.Equal(t, []string{
|
||||
"/buckets/mybucket/sub/nested.bin",
|
||||
"/buckets/mybucket/old.bin",
|
||||
"/buckets/mybucket/fresh.bin",
|
||||
}, paths, "oldest LastLocalSyncTsNs first; remote-only, dirty, local entries skipped")
|
||||
|
||||
got = f.ListEvictableRemoteEntries(context.Background(), mounts, 30*time.Second)
|
||||
paths = paths[:0]
|
||||
for _, e := range got {
|
||||
paths = append(paths, string(e.FullPath))
|
||||
}
|
||||
assert.Equal(t, []string{
|
||||
"/buckets/mybucket/sub/nested.bin",
|
||||
"/buckets/mybucket/old.bin",
|
||||
}, paths, "minCacheAge excludes freshly cached entries")
|
||||
}
|
||||
|
||||
func TestUpdateEntryInvalidatesStaleSyncStamp(t *testing.T) {
|
||||
now := time.Now()
|
||||
synced := now.Add(-time.Hour).UnixNano()
|
||||
mtime := now.Add(-time.Hour)
|
||||
path := "/buckets/mybucket/a.bin"
|
||||
|
||||
newFiler := func() *Filer {
|
||||
f := newTestFiler(t, newStubFilerStore(), NewFilerRemoteStorage())
|
||||
require.NoError(t, f.CreateEntry(context.Background(), remoteCachedEntry(path, synced, mtime, 1), nil, false, false, nil, false, 255))
|
||||
return f
|
||||
}
|
||||
syncStamp := func(f *Filer) int64 {
|
||||
entry, err := f.FindEntry(context.Background(), util.FullPath(path))
|
||||
require.NoError(t, err)
|
||||
return entry.Remote.LastLocalSyncTsNs
|
||||
}
|
||||
|
||||
t.Run("local chunk change clears stamp", func(t *testing.T) {
|
||||
f := newFiler()
|
||||
update := remoteCachedEntry(path, synced, mtime, 1)
|
||||
update.Chunks[0].FileId = "2,01637037d6"
|
||||
require.NoError(t, f.CreateEntry(context.Background(), update, nil, false, false, nil, false, 255))
|
||||
assert.Zero(t, syncStamp(f))
|
||||
})
|
||||
|
||||
t.Run("metadata-only update keeps stamp", func(t *testing.T) {
|
||||
f := newFiler()
|
||||
update := remoteCachedEntry(path, synced, mtime, 1)
|
||||
update.Attr.Mime = "text/plain"
|
||||
require.NoError(t, f.CreateEntry(context.Background(), update, nil, false, false, nil, false, 255))
|
||||
assert.Equal(t, synced, syncStamp(f))
|
||||
})
|
||||
|
||||
t.Run("fresh sync stamp survives chunk change", func(t *testing.T) {
|
||||
f := newFiler()
|
||||
update := remoteCachedEntry(path, now.UnixNano(), mtime, 1)
|
||||
update.Chunks[0].FileId = "2,01637037d6"
|
||||
require.NoError(t, f.CreateEntry(context.Background(), update, nil, false, false, nil, false, 255))
|
||||
assert.Equal(t, now.UnixNano(), syncStamp(f))
|
||||
})
|
||||
|
||||
t.Run("replicated update keeps authoritative stamp", func(t *testing.T) {
|
||||
f := newFiler()
|
||||
update := remoteCachedEntry(path, synced, mtime, 1)
|
||||
update.Chunks[0].FileId = "2,01637037d6"
|
||||
require.NoError(t, f.CreateEntry(context.Background(), update, nil, false, true, nil, false, 255))
|
||||
assert.Equal(t, synced, syncStamp(f))
|
||||
})
|
||||
}
|
||||
+41
-15
@@ -32,7 +32,9 @@ type ChunkReadAt struct {
|
||||
fileSize int64
|
||||
readerCache *ReaderCache
|
||||
readerPattern *ReaderPattern
|
||||
lastChunkMu sync.Mutex // guards lastChunkFid; mount issues concurrent ReadAt calls
|
||||
lastChunkFid string
|
||||
stream chunkStream // chunk this reader is positioned in, pinned in the shared readerCache
|
||||
prefetchCount int // Number of chunks to prefetch ahead during sequential reads
|
||||
ctx context.Context // Context used for cancellation during chunk read operations
|
||||
}
|
||||
@@ -167,10 +169,17 @@ func (c *ChunkReadAt) Size() int64 {
|
||||
}
|
||||
|
||||
func (c *ChunkReadAt) Close() error {
|
||||
c.ReleaseStream()
|
||||
c.readerCache.destroy()
|
||||
return nil
|
||||
}
|
||||
|
||||
// ReleaseStream drops this reader's hold on the chunk it is positioned in.
|
||||
// Unlike Close it leaves the (possibly shared) ReaderCache intact.
|
||||
func (c *ChunkReadAt) ReleaseStream() {
|
||||
c.readerCache.releaseStream(&c.stream)
|
||||
}
|
||||
|
||||
func (c *ChunkReadAt) ReadAt(p []byte, offset int64) (n int, err error) {
|
||||
|
||||
c.readerPattern.MonitorReadAt(offset, len(p))
|
||||
@@ -340,36 +349,53 @@ func (c *ChunkReadAt) doReadAt(ctx context.Context, p []byte, offset int64) (n i
|
||||
|
||||
func (c *ChunkReadAt) readChunkSliceAt(ctx context.Context, buffer []byte, chunkView *ChunkView, nextChunkViews *Interval[*ChunkView], offset uint64) (n int, err error) {
|
||||
|
||||
if c.readerPattern.IsRandomMode() {
|
||||
// A view clipped to part of its chunk (e.g. the edge of a ranged GET,
|
||||
// whose views ViewFromVisibleIntervals clips to the request) only ever
|
||||
// needs that part: fetch it as a range no matter the detected pattern.
|
||||
// Fetching the chunk whole would multiply volume-server reads. Ciphered
|
||||
// and compressed chunks are the exception: the volume server reads the
|
||||
// whole blob to serve a range, so they take the shared whole-chunk path
|
||||
// where one download serves every buffer — unless the whole chunk cannot
|
||||
// even fit the reader budget, in which case a range fetch is the only
|
||||
// way to serve the request.
|
||||
rangeFetch := chunkView.CanRangeFetch() || !c.readerCache.budget.canFit(int(chunkView.ChunkSize))
|
||||
if rangeFetch && (!chunkView.IsFullChunk() || c.readerPattern.IsRandomMode()) {
|
||||
c.readerCache.releaseStream(&c.stream)
|
||||
n, err := c.readerCache.chunkCache.ReadChunkAt(buffer, chunkView.FileId, offset)
|
||||
if n > 0 {
|
||||
return n, err
|
||||
}
|
||||
return fetchChunkRange(ctx, buffer, c.readerCache.lookupFileIdFn, chunkView.FileId, chunkView.CipherKey, chunkView.IsGzipped, int64(offset),
|
||||
refreshUrls(ctx, c.readerCache.cacheInvalidator, c.readerCache.lookupFileIdFn, chunkView.FileId))
|
||||
return c.readerCache.fetchChunkRange(ctx, buffer, chunkView, int64(offset))
|
||||
}
|
||||
|
||||
shouldCache := (uint64(chunkView.ViewOffset) + chunkView.ChunkSize) <= c.readerCache.chunkCache.GetMaxFilePartSizeInCache()
|
||||
n, err = c.readerCache.ReadChunkAt(ctx, buffer, chunkView.FileId, chunkView.CipherKey, chunkView.IsGzipped, int64(offset), int(chunkView.ChunkSize), shouldCache)
|
||||
if c.lastChunkFid != chunkView.FileId {
|
||||
if chunkView.OffsetInChunk == 0 { // start of a new chunk
|
||||
if c.lastChunkFid != "" {
|
||||
c.readerCache.UnCache(c.lastChunkFid)
|
||||
}
|
||||
if nextChunkViews != nil && c.prefetchCount > 0 {
|
||||
// Prefetch multiple chunks ahead for better sequential read throughput
|
||||
// This keeps the network pipeline full with parallel chunk fetches
|
||||
c.readerCache.MaybeCache(nextChunkViews, c.prefetchCount)
|
||||
}
|
||||
// The previous chunk is released through the stream pin rather than
|
||||
// UnCache: the buffer is shared, and other streams may still be reading it.
|
||||
n, err = c.readerCache.readChunkAt(ctx, &c.stream, buffer, chunkView.FileId, chunkView.CipherKey, chunkView.IsGzipped, int64(offset), int(chunkView.ChunkSize), shouldCache)
|
||||
c.lastChunkMu.Lock()
|
||||
enteredChunk := c.lastChunkFid != chunkView.FileId
|
||||
c.lastChunkFid = chunkView.FileId
|
||||
c.lastChunkMu.Unlock()
|
||||
if enteredChunk && chunkView.OffsetInChunk == 0 { // start of a new chunk
|
||||
if nextChunkViews != nil && c.prefetchCount > 0 {
|
||||
// Prefetch multiple chunks ahead for better sequential read throughput
|
||||
// This keeps the network pipeline full with parallel chunk fetches
|
||||
c.readerCache.MaybeCache(nextChunkViews, c.prefetchCount)
|
||||
}
|
||||
}
|
||||
c.lastChunkFid = chunkView.FileId
|
||||
return
|
||||
}
|
||||
|
||||
// readChunkSliceAtForParallel is a simplified version for parallel chunk fetching
|
||||
// It doesn't update lastChunkFid or trigger prefetch (handled by the caller)
|
||||
func (c *ChunkReadAt) readChunkSliceAtForParallel(ctx context.Context, buffer []byte, chunkView *ChunkView, offset uint64) (n int, err error) {
|
||||
if (chunkView.CanRangeFetch() || !c.readerCache.budget.canFit(int(chunkView.ChunkSize))) && !chunkView.IsFullChunk() {
|
||||
n, err = c.readerCache.chunkCache.ReadChunkAt(buffer, chunkView.FileId, offset)
|
||||
if n > 0 {
|
||||
return n, err
|
||||
}
|
||||
return c.readerCache.fetchChunkRange(ctx, buffer, chunkView, int64(offset))
|
||||
}
|
||||
shouldCache := (uint64(chunkView.ViewOffset) + chunkView.ChunkSize) <= c.readerCache.chunkCache.GetMaxFilePartSizeInCache()
|
||||
return c.readerCache.ReadChunkAt(ctx, buffer, chunkView.FileId, chunkView.CipherKey, chunkView.IsGzipped, int64(offset), int(chunkView.ChunkSize), shouldCache)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,477 @@
|
||||
package filer
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"io"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/chunk_cache"
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
)
|
||||
|
||||
// Two streams (e.g. two S3 GETs) reading the same object through one shared
|
||||
// ReaderCache, interleaved in small slices, must share each chunk download:
|
||||
// one stream finishing a chunk, or moving on to the next one, must not drop a
|
||||
// buffer the other stream is still reading.
|
||||
func TestChunkReadAtConcurrentStreamsShareChunks(t *testing.T) {
|
||||
const chunkSize = 64 << 10
|
||||
const chunkCount = 3
|
||||
const sliceSize = 16 << 10
|
||||
|
||||
var mu sync.Mutex
|
||||
fetches := map[string]int{}
|
||||
rc := NewReaderCache(64, (*chunk_cache.TieredChunkCache)(nil), func(context.Context, string) ([]string, error) {
|
||||
return []string{"unused"}, nil
|
||||
}, nil)
|
||||
defer rc.destroy()
|
||||
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, fileId string, _ util_http.RefreshUrlsFunc) (int, error) {
|
||||
mu.Lock()
|
||||
fetches[fileId]++
|
||||
mu.Unlock()
|
||||
for i := range buffer {
|
||||
buffer[i] = fileId[len(fileId)-1]
|
||||
}
|
||||
return len(buffer), nil
|
||||
}
|
||||
|
||||
newStream := func() *ChunkReadAt {
|
||||
views := NewIntervalList[*ChunkView]()
|
||||
for i := 0; i < chunkCount; i++ {
|
||||
views.AppendInterval(&Interval[*ChunkView]{
|
||||
StartOffset: int64(i * chunkSize),
|
||||
StopOffset: int64((i + 1) * chunkSize),
|
||||
Value: &ChunkView{
|
||||
FileId: fmt.Sprintf("chunk%d", i),
|
||||
ViewSize: chunkSize,
|
||||
ViewOffset: int64(i * chunkSize),
|
||||
ChunkSize: chunkSize,
|
||||
},
|
||||
})
|
||||
}
|
||||
return NewChunkReaderAtFromClient(context.Background(), rc, views, chunkSize*chunkCount, 0)
|
||||
}
|
||||
streams := []*ChunkReadAt{newStream(), newStream()}
|
||||
|
||||
// The streams alternate slice by slice, the second one lagging one slice
|
||||
// behind, so the leader always finishes a chunk while the follower is
|
||||
// still inside it.
|
||||
offsets := make([]int64, len(streams))
|
||||
offsets[1] = -sliceSize
|
||||
for offsets[1] < chunkSize*chunkCount {
|
||||
for i, stream := range streams {
|
||||
if offsets[i] < 0 || offsets[i] >= chunkSize*chunkCount {
|
||||
offsets[i] += sliceSize
|
||||
continue
|
||||
}
|
||||
buf := make([]byte, sliceSize)
|
||||
n, err := stream.ReadAt(buf, offsets[i])
|
||||
if (err != nil && err != io.EOF) || n != sliceSize {
|
||||
t.Fatalf("stream %d at %d: n=%d err=%v", i, offsets[i], n, err)
|
||||
}
|
||||
if want := byte('0' + offsets[i]/chunkSize); buf[0] != want || buf[n-1] != want {
|
||||
t.Fatalf("stream %d at %d: got %q, want %q", i, offsets[i], buf[0], want)
|
||||
}
|
||||
offsets[i] += sliceSize
|
||||
}
|
||||
}
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
for i := 0; i < chunkCount; i++ {
|
||||
fileId := fmt.Sprintf("chunk%d", i)
|
||||
if fetches[fileId] != 1 {
|
||||
t.Errorf("%s fetched %d times for two concurrent streams, want 1", fileId, fetches[fileId])
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newStreamTestReaderCache(chunkCache chunk_cache.ChunkCache) *ReaderCache {
|
||||
rc := NewReaderCache(64, chunkCache, func(context.Context, string) ([]string, error) {
|
||||
return []string{"unused"}, nil
|
||||
}, nil)
|
||||
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, _ string, _ util_http.RefreshUrlsFunc) (int, error) {
|
||||
return len(buffer), nil
|
||||
}
|
||||
return rc
|
||||
}
|
||||
|
||||
func isRetained(rc *ReaderCache, fileId string) bool {
|
||||
rc.Lock()
|
||||
defer rc.Unlock()
|
||||
_, found := rc.downloaders[fileId]
|
||||
return found
|
||||
}
|
||||
|
||||
// A stream moving on to a chunk served from the chunk cache must still
|
||||
// release the chunk it was positioned in before.
|
||||
func TestChunkStreamReleasesPreviousChunkOnCacheHit(t *testing.T) {
|
||||
cache := newMockChunkCacheForReaderCache()
|
||||
cache.SetChunk("chunk1", make([]byte, 4<<10))
|
||||
rc := newStreamTestReaderCache(cache)
|
||||
defer rc.destroy()
|
||||
|
||||
stream := &chunkStream{}
|
||||
if _, err := rc.readChunkAt(context.Background(), stream, make([]byte, 1<<10), "chunk0", nil, false, 0, 4<<10, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if n, err := rc.readChunkAt(context.Background(), stream, make([]byte, 1<<10), "chunk1", nil, false, 0, 4<<10, true); err != nil || n == 0 {
|
||||
t.Fatalf("cache hit read: n=%d err=%v", n, err)
|
||||
}
|
||||
if isRetained(rc, "chunk0") {
|
||||
t.Fatal("chunk0 still retained after the stream moved on to a cached chunk")
|
||||
}
|
||||
}
|
||||
|
||||
// A chunk the stream leaves while another read is in flight must be dropped
|
||||
// once that read ends, even if it did not read the chunk to the end.
|
||||
func TestChunkStreamDropsLeftChunkAfterInFlightRead(t *testing.T) {
|
||||
rc := newStreamTestReaderCache(newMockChunkCacheForReaderCache())
|
||||
defer rc.destroy()
|
||||
|
||||
stream := &chunkStream{}
|
||||
if _, err := rc.readChunkAt(context.Background(), stream, make([]byte, 1<<10), "chunk0", nil, false, 0, 4<<10, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// Another reader is in the middle of a partial read of chunk0.
|
||||
rc.Lock()
|
||||
other := rc.downloaders["chunk0"]
|
||||
other.wg.Add(1)
|
||||
atomic.AddInt32(&other.readers, 1)
|
||||
rc.Unlock()
|
||||
|
||||
if _, err := rc.readChunkAt(context.Background(), stream, make([]byte, 1<<10), "chunk1", nil, false, 0, 4<<10, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !isRetained(rc, "chunk0") {
|
||||
t.Fatal("chunk0 dropped while a read was still in flight")
|
||||
}
|
||||
|
||||
// The in-flight read ends without reaching the end of the chunk.
|
||||
other.wg.Done()
|
||||
atomic.AddInt32(&other.readers, -1)
|
||||
rc.removeConsumed(other)
|
||||
if isRetained(rc, "chunk0") {
|
||||
t.Fatal("chunk0 retained after the stream left it and the last read ended")
|
||||
}
|
||||
}
|
||||
|
||||
// Concurrent ReadAt calls on one ChunkReadAt (as mount does) share its stream
|
||||
// pin; they must neither race on it nor leak or double-release pins.
|
||||
func TestChunkStreamConcurrentReadsOnOneReader(t *testing.T) {
|
||||
const chunkSize = 16 << 10
|
||||
const chunkCount = 4
|
||||
const sliceSize = 4 << 10
|
||||
rc := newStreamTestReaderCache((*chunk_cache.TieredChunkCache)(nil))
|
||||
defer rc.destroy()
|
||||
|
||||
views := NewIntervalList[*ChunkView]()
|
||||
for i := 0; i < chunkCount; i++ {
|
||||
views.AppendInterval(&Interval[*ChunkView]{
|
||||
StartOffset: int64(i * chunkSize),
|
||||
StopOffset: int64((i + 1) * chunkSize),
|
||||
Value: &ChunkView{
|
||||
FileId: fmt.Sprintf("chunk%d", i),
|
||||
ViewSize: chunkSize,
|
||||
ViewOffset: int64(i * chunkSize),
|
||||
ChunkSize: chunkSize,
|
||||
},
|
||||
})
|
||||
}
|
||||
reader := NewChunkReaderAtFromClient(context.Background(), rc, views, chunkSize*chunkCount, 0)
|
||||
|
||||
var wg sync.WaitGroup
|
||||
for g := 0; g < 8; g++ {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
for offset := int64(0); offset < chunkSize*chunkCount; offset += sliceSize {
|
||||
if _, err := reader.ReadAt(make([]byte, sliceSize), offset); err != nil && err != io.EOF {
|
||||
t.Error(err)
|
||||
return
|
||||
}
|
||||
}
|
||||
}()
|
||||
}
|
||||
wg.Wait()
|
||||
|
||||
// Finishing the last chunk releases the stream's final pin.
|
||||
if _, err := reader.ReadAt(make([]byte, sliceSize), chunkSize*chunkCount-sliceSize); err != nil && err != io.EOF {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rc.Lock()
|
||||
defer rc.Unlock()
|
||||
for fileId, cacher := range rc.downloaders {
|
||||
t.Errorf("%s retained after all reads finished: pins=%d readers=%d", fileId, atomic.LoadInt32(&cacher.pins), atomic.LoadInt32(&cacher.readers))
|
||||
}
|
||||
}
|
||||
|
||||
type recordedFetch struct {
|
||||
fileId string
|
||||
isFullChunk bool
|
||||
offset int64
|
||||
size int
|
||||
}
|
||||
|
||||
// fetchRecorder stubs the volume fetch and records how each chunk was
|
||||
// requested: isFullChunk=false is a range fetch of just the view's slice,
|
||||
// isFullChunk=true is a whole-chunk download into the shared cache.
|
||||
func fetchRecorder(rc *ReaderCache) (fetches *[]recordedFetch) {
|
||||
var mu sync.Mutex
|
||||
recorded := &[]recordedFetch{}
|
||||
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, isFullChunk bool, offset int64, fileId string, _ util_http.RefreshUrlsFunc) (int, error) {
|
||||
mu.Lock()
|
||||
*recorded = append(*recorded, recordedFetch{fileId, isFullChunk, offset, len(buffer)})
|
||||
mu.Unlock()
|
||||
for i := range buffer {
|
||||
buffer[i] = fileId[len(fileId)-1]
|
||||
}
|
||||
return len(buffer), nil
|
||||
}
|
||||
return recorded
|
||||
}
|
||||
|
||||
// A reader whose views are clipped to a request window — how the S3 gateway
|
||||
// builds a ranged GET — must fetch only the covered part of each chunk:
|
||||
// clipped edge views take range fetches, a fully covered chunk keeps the
|
||||
// shared whole-chunk path. This is what keeps a ranged GET larger than a
|
||||
// buffer from multiplying volume-server reads (issue #11564), without giving
|
||||
// up whole-chunk caching where the whole chunk is actually wanted.
|
||||
func TestChunkReadAtClippedViewsFetchOnlyCoveredParts(t *testing.T) {
|
||||
const chunkSize = 64 << 10
|
||||
|
||||
rc := NewReaderCache(64, (*chunk_cache.TieredChunkCache)(nil), func(context.Context, string) ([]string, error) {
|
||||
return []string{"unused"}, nil
|
||||
}, nil)
|
||||
defer rc.destroy()
|
||||
fetches := fetchRecorder(rc)
|
||||
|
||||
// Window [56KiB, 152KiB): tail of chunk0, all of chunk1, head of
|
||||
// chunk2, head of ciphered chunk3, head of compressed chunk4 (file
|
||||
// chunks need not be aligned).
|
||||
views := NewIntervalList[*ChunkView]()
|
||||
views.AppendInterval(&Interval[*ChunkView]{
|
||||
StartOffset: chunkSize - 8<<10,
|
||||
StopOffset: chunkSize,
|
||||
Value: &ChunkView{FileId: "chunk0", OffsetInChunk: chunkSize - 8<<10, ViewSize: 8 << 10, ViewOffset: chunkSize - 8<<10, ChunkSize: chunkSize},
|
||||
})
|
||||
views.AppendInterval(&Interval[*ChunkView]{
|
||||
StartOffset: chunkSize,
|
||||
StopOffset: 2 * chunkSize,
|
||||
Value: &ChunkView{FileId: "chunk1", ViewSize: chunkSize, ViewOffset: chunkSize, ChunkSize: chunkSize},
|
||||
})
|
||||
views.AppendInterval(&Interval[*ChunkView]{
|
||||
StartOffset: 2 * chunkSize,
|
||||
StopOffset: 2*chunkSize + 8<<10,
|
||||
Value: &ChunkView{FileId: "chunk2", ViewSize: 8 << 10, ViewOffset: 2 * chunkSize, ChunkSize: chunkSize},
|
||||
})
|
||||
views.AppendInterval(&Interval[*ChunkView]{
|
||||
StartOffset: 2*chunkSize + 8<<10,
|
||||
StopOffset: 2*chunkSize + 16<<10,
|
||||
Value: &ChunkView{FileId: "chunk3", ViewSize: 8 << 10, ViewOffset: 2*chunkSize + 8<<10, ChunkSize: chunkSize, CipherKey: []byte("key")},
|
||||
})
|
||||
views.AppendInterval(&Interval[*ChunkView]{
|
||||
StartOffset: 2*chunkSize + 16<<10,
|
||||
StopOffset: 2*chunkSize + 24<<10,
|
||||
Value: &ChunkView{FileId: "chunk4", ViewSize: 8 << 10, ViewOffset: 2*chunkSize + 16<<10, ChunkSize: chunkSize, IsGzipped: true},
|
||||
})
|
||||
|
||||
reader := NewChunkReaderAtFromClient(context.Background(), rc, views, 4*chunkSize, 0)
|
||||
buf := make([]byte, chunkSize+32<<10)
|
||||
if n, err := reader.ReadAt(buf, chunkSize-8<<10); err != nil || n != len(buf) {
|
||||
t.Fatalf("window read: n=%d err=%v", n, err)
|
||||
}
|
||||
// buf holds [56KiB, 152KiB): chunk0's tail, chunk1, and the heads of
|
||||
// chunk2, chunk3 and chunk4.
|
||||
for i, b := range buf {
|
||||
want := byte('1')
|
||||
if i < 8<<10 {
|
||||
want = '0'
|
||||
} else if i >= 24<<10+chunkSize {
|
||||
want = '4'
|
||||
} else if i >= 16<<10+chunkSize {
|
||||
want = '3'
|
||||
} else if i >= 8<<10+chunkSize {
|
||||
want = '2'
|
||||
}
|
||||
if b != want {
|
||||
t.Fatalf("buf[%d]=%q, want %q", i, b, want)
|
||||
}
|
||||
}
|
||||
|
||||
want := []recordedFetch{
|
||||
{fileId: "chunk0", isFullChunk: false, offset: chunkSize - 8<<10, size: 8 << 10},
|
||||
{fileId: "chunk1", isFullChunk: true, offset: 0, size: chunkSize},
|
||||
{fileId: "chunk2", isFullChunk: false, offset: 0, size: 8 << 10},
|
||||
// partial views, but ciphered and compressed chunks download whole
|
||||
// either way and the shared path decrypts/decompresses once for
|
||||
// every buffer
|
||||
{fileId: "chunk3", isFullChunk: true, offset: 0, size: chunkSize},
|
||||
{fileId: "chunk4", isFullChunk: true, offset: 0, size: chunkSize},
|
||||
}
|
||||
got := map[string]recordedFetch{}
|
||||
for _, f := range *fetches {
|
||||
if _, dup := got[f.fileId]; dup {
|
||||
t.Fatalf("chunk %s fetched more than once: %+v", f.fileId, *fetches)
|
||||
}
|
||||
got[f.fileId] = f
|
||||
}
|
||||
for _, w := range want {
|
||||
if g, ok := got[w.fileId]; !ok {
|
||||
t.Fatalf("chunk %s never fetched: %+v", w.fileId, *fetches)
|
||||
} else if g != w {
|
||||
t.Fatalf("chunk %s fetched as %+v, want %+v", w.fileId, g, w)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The regression from issue #11564: a ranged GET sitting inside one big
|
||||
// chunk. Every buffer of the request must stay a range fetch — none may
|
||||
// escalate into a whole-chunk download once the reads look sequential.
|
||||
func TestChunkReadAtRangeInsideOneChunkStaysRangeFetch(t *testing.T) {
|
||||
const chunkSize = 1 << 20
|
||||
const sliceSize = 16 << 10
|
||||
|
||||
rc := NewReaderCache(64, (*chunk_cache.TieredChunkCache)(nil), func(context.Context, string) ([]string, error) {
|
||||
return []string{"unused"}, nil
|
||||
}, nil)
|
||||
defer rc.destroy()
|
||||
fetches := fetchRecorder(rc)
|
||||
|
||||
// Range [32KiB, 96KiB) inside one 1MiB chunk: a single clipped view.
|
||||
views := NewIntervalList[*ChunkView]()
|
||||
views.AppendInterval(&Interval[*ChunkView]{
|
||||
StartOffset: 32 << 10,
|
||||
StopOffset: 96 << 10,
|
||||
Value: &ChunkView{FileId: "chunk0", OffsetInChunk: 32 << 10, ViewSize: 64 << 10, ViewOffset: 32 << 10, ChunkSize: chunkSize},
|
||||
})
|
||||
|
||||
reader := NewChunkReaderAtFromClient(context.Background(), rc, views, chunkSize, 0)
|
||||
for offset := int64(32 << 10); offset < 96<<10; offset += sliceSize {
|
||||
buf := make([]byte, sliceSize)
|
||||
if n, err := reader.ReadAt(buf, offset); err != nil || n != sliceSize {
|
||||
t.Fatalf("read at %d: n=%d err=%v", offset, n, err)
|
||||
}
|
||||
}
|
||||
|
||||
if len(*fetches) != 4 {
|
||||
t.Fatalf("got %d fetches, want 4 range fetches: %+v", len(*fetches), *fetches)
|
||||
}
|
||||
for i, f := range *fetches {
|
||||
wantOffset := int64(32<<10) + int64(i)*sliceSize
|
||||
if f.isFullChunk || f.offset != wantOffset || f.size != sliceSize {
|
||||
t.Fatalf("fetch %d = %+v, want range fetch offset=%d size=%d", i, f, wantOffset, sliceSize)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// A compressed chunk larger than the reader cache budget can never be
|
||||
// downloaded whole — the budget rejects the buffer — so its partial view
|
||||
// must fall back to a range fetch even though each range costs a full
|
||||
// decompress server-side. The alternative is a failed GET.
|
||||
func TestChunkReadAtOversizedCompressedChunkFallsBackToRange(t *testing.T) {
|
||||
const chunkSize = 1 << 20
|
||||
|
||||
budget := NewReaderCacheBudget(64 << 10) // smaller than the chunk
|
||||
rc := NewReaderCache(64, (*chunk_cache.TieredChunkCache)(nil), func(context.Context, string) ([]string, error) {
|
||||
return []string{"unused"}, nil
|
||||
}, nil, budget)
|
||||
defer rc.destroy()
|
||||
fetches := fetchRecorder(rc)
|
||||
|
||||
views := NewIntervalList[*ChunkView]()
|
||||
views.AppendInterval(&Interval[*ChunkView]{
|
||||
StartOffset: 32 << 10,
|
||||
StopOffset: 64 << 10,
|
||||
Value: &ChunkView{FileId: "chunk0", OffsetInChunk: 32 << 10, ViewSize: 32 << 10, ViewOffset: 32 << 10, ChunkSize: chunkSize, IsGzipped: true},
|
||||
})
|
||||
|
||||
reader := NewChunkReaderAtFromClient(context.Background(), rc, views, chunkSize, 0)
|
||||
buf := make([]byte, 32<<10)
|
||||
if n, err := reader.ReadAt(buf, 32<<10); err != nil || n != len(buf) {
|
||||
t.Fatalf("read: n=%d err=%v", n, err)
|
||||
}
|
||||
|
||||
if len(*fetches) != 1 {
|
||||
t.Fatalf("got %d fetches, want 1 range fetch: %+v", len(*fetches), *fetches)
|
||||
}
|
||||
if f := (*fetches)[0]; f.isFullChunk || f.offset != 32<<10 || f.size != 32<<10 {
|
||||
t.Fatalf("fetch = %+v, want range fetch offset=%d size=%d", f, 32<<10, 32<<10)
|
||||
}
|
||||
}
|
||||
|
||||
// A chunk a stream is positioned in must outlast downloader-limit eviction:
|
||||
// otherwise a busy cache drops the buffer mid-stream and forces a refetch.
|
||||
func TestChunkReadAtPinnedChunkSurvivesEviction(t *testing.T) {
|
||||
const chunkSize = 64 << 10
|
||||
|
||||
var fetches int32
|
||||
rc := NewReaderCache(2, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) {
|
||||
return []string{"unused"}, nil
|
||||
}, nil)
|
||||
defer rc.destroy()
|
||||
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, fileId string, _ util_http.RefreshUrlsFunc) (int, error) {
|
||||
if fileId == "chunk0" {
|
||||
atomic.AddInt32(&fetches, 1)
|
||||
}
|
||||
return len(buffer), nil
|
||||
}
|
||||
|
||||
stream := &chunkStream{}
|
||||
buf := make([]byte, 16<<10)
|
||||
// One slice in: the stream is positioned in chunk0 but has not left it.
|
||||
if _, err := rc.readChunkAt(context.Background(), stream, buf, "chunk0", nil, false, 0, chunkSize, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Fill the downloader map past its limit with unpinned chunks.
|
||||
for _, fileId := range []string{"chunk1", "chunk2", "chunk3"} {
|
||||
if _, err := rc.ReadChunkAt(context.Background(), buf, fileId, nil, false, 0, chunkSize, true); err != nil {
|
||||
t.Fatalf("read %s: %v", fileId, err)
|
||||
}
|
||||
}
|
||||
|
||||
// The stream's next slice must come from the still-pinned buffer.
|
||||
if _, err := rc.readChunkAt(context.Background(), stream, buf, "chunk0", nil, false, 16<<10, chunkSize, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := atomic.LoadInt32(&fetches); got != 1 {
|
||||
t.Errorf("chunk0 fetched %d times, want 1", got)
|
||||
}
|
||||
}
|
||||
|
||||
// When every downloader is pinned the limit still applies: the oldest pinned
|
||||
// buffer is evicted so abandoned streams cannot grow memory past the limit.
|
||||
func TestChunkReadAtPinnedEvictionFallsBackWhenAllPinned(t *testing.T) {
|
||||
const chunkSize = 64 << 10
|
||||
rc := NewReaderCache(2, newMockChunkCacheForReaderCache(), func(context.Context, string) ([]string, error) {
|
||||
return []string{"unused"}, nil
|
||||
}, nil)
|
||||
defer rc.destroy()
|
||||
rc.fetchChunkDataFn = func(_ context.Context, buffer []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, _ string, _ util_http.RefreshUrlsFunc) (int, error) {
|
||||
return len(buffer), nil
|
||||
}
|
||||
|
||||
buf := make([]byte, 16<<10)
|
||||
streamA := &chunkStream{}
|
||||
streamB := &chunkStream{}
|
||||
if _, err := rc.readChunkAt(context.Background(), streamA, buf, "chunk0", nil, false, 0, chunkSize, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := rc.readChunkAt(context.Background(), streamB, buf, "chunk1", nil, false, 0, chunkSize, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Every downloader is now pinned; the next chunk must still get in.
|
||||
if _, err := rc.readChunkAt(context.Background(), &chunkStream{}, buf, "chunk2", nil, false, 0, chunkSize, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if isRetained(rc, "chunk0") {
|
||||
t.Fatal("oldest pinned downloader was not evicted past the limit")
|
||||
}
|
||||
if !isRetained(rc, "chunk2") {
|
||||
t.Fatal("new downloader missing after pinned fallback eviction")
|
||||
}
|
||||
}
|
||||
+150
-9
@@ -35,6 +35,8 @@ type SingleChunkCacher struct {
|
||||
completedTimeNew int64
|
||||
readers int32
|
||||
consumed int32
|
||||
pins int32 // streams currently positioned inside this chunk
|
||||
left int32 // set once the last pinning stream moved on
|
||||
sync.Mutex
|
||||
parent *ReaderCache
|
||||
chunkFileId string
|
||||
@@ -98,6 +100,14 @@ func (rc *ReaderCache) MaybeCache(chunkViews *Interval[*ChunkView], count int) {
|
||||
// abort when slots are filled
|
||||
return
|
||||
}
|
||||
if (chunkView.CanRangeFetch() || !rc.budget.canFit(int(chunkView.ChunkSize))) && !chunkView.IsFullChunk() {
|
||||
// the view is clipped to part of the chunk and will be
|
||||
// range-fetched, so prefetching it whole would download bytes
|
||||
// nobody needs; a ciphered or compressed partial view needs
|
||||
// the whole blob anyway and is worth prefetching, but not when
|
||||
// it cannot fit the budget at all
|
||||
continue
|
||||
}
|
||||
|
||||
// glog.V(4).Infof("prefetch %s offset %d", chunkView.FileId, chunkView.ViewOffset)
|
||||
// cache this chunk if not yet
|
||||
@@ -112,7 +122,33 @@ func (rc *ReaderCache) MaybeCache(chunkViews *Interval[*ChunkView], count int) {
|
||||
return
|
||||
}
|
||||
|
||||
// fetchChunkRange downloads only [offset, offset+len(buffer)) of a chunk,
|
||||
// for views clipped to part of their chunk and for random-mode reads. It
|
||||
// goes through fetchChunkDataFn so tests observe range fetches the same way
|
||||
// they observe whole-chunk downloads.
|
||||
func (rc *ReaderCache) fetchChunkRange(ctx context.Context, buffer []byte, chunkView *ChunkView, offset int64) (int, error) {
|
||||
urlStrings, err := rc.lookupFileIdFn(ctx, chunkView.FileId)
|
||||
if err != nil {
|
||||
glog.ErrorfCtx(ctx, "operation LookupFileId %s failed, err: %v", chunkView.FileId, err)
|
||||
return 0, err
|
||||
}
|
||||
return rc.fetchChunkDataFn(ctx, buffer, urlStrings, chunkView.CipherKey, chunkView.IsGzipped, false, offset, chunkView.FileId,
|
||||
refreshUrls(ctx, rc.cacheInvalidator, rc.lookupFileIdFn, chunkView.FileId))
|
||||
}
|
||||
|
||||
// chunkStream is one sequential reader's position in a shared ReaderCache.
|
||||
// The chunk it is reading stays pinned until the stream reads it to the end or
|
||||
// moves elsewhere, so another stream finishing or leaving the same chunk does
|
||||
// not drop the buffer from under it.
|
||||
type chunkStream struct {
|
||||
cacher *SingleChunkCacher
|
||||
}
|
||||
|
||||
func (rc *ReaderCache) ReadChunkAt(ctx context.Context, buffer []byte, fileId string, cipherKey []byte, isGzipped bool, offset int64, chunkSize int, shouldCache bool) (int, error) {
|
||||
return rc.readChunkAt(ctx, nil, buffer, fileId, cipherKey, isGzipped, offset, chunkSize, shouldCache)
|
||||
}
|
||||
|
||||
func (rc *ReaderCache) readChunkAt(ctx context.Context, stream *chunkStream, buffer []byte, fileId string, cipherKey []byte, isGzipped bool, offset int64, chunkSize int, shouldCache bool) (int, error) {
|
||||
retry:
|
||||
rc.Lock()
|
||||
|
||||
@@ -130,8 +166,11 @@ retry:
|
||||
// start wg.Wait() on a zero counter while this read is about to register.
|
||||
cacher.wg.Add(1)
|
||||
atomic.AddInt32(&cacher.readers, 1)
|
||||
previous := stream.pin(cacher)
|
||||
rc.Unlock()
|
||||
rc.unpin(previous)
|
||||
n, err := cacher.readChunkAt(ctx, buffer, offset)
|
||||
rc.releaseIfFinished(stream, cacher, offset, n, err, chunkSize)
|
||||
if n > 0 || err != nil {
|
||||
return n, err
|
||||
}
|
||||
@@ -144,19 +183,34 @@ retry:
|
||||
if shouldCache || rc.lookupFileIdFn == nil {
|
||||
n, err := rc.chunkCache.ReadChunkAt(buffer, fileId, uint64(offset))
|
||||
if n > 0 {
|
||||
// Served from the chunk cache: the stream has left its pinned chunk.
|
||||
previous := stream.unpinLocked()
|
||||
rc.Unlock()
|
||||
rc.unpin(previous)
|
||||
return n, err
|
||||
}
|
||||
}
|
||||
|
||||
// clean up old downloaders
|
||||
// clean up old downloaders; prefer one no stream is positioned in, but
|
||||
// fall back to a pinned one so abandoned pins cannot bypass the limit
|
||||
if len(rc.downloaders) >= rc.limit {
|
||||
oldestFid, oldestTime := "", time.Now().UnixNano()
|
||||
pinnedFid, pinnedTime := "", int64(0)
|
||||
for fid, downloader := range rc.downloaders {
|
||||
completedTime := atomic.LoadInt64(&downloader.completedTimeNew)
|
||||
if completedTime > 0 && completedTime < oldestTime {
|
||||
oldestFid, oldestTime = fid, completedTime
|
||||
if completedTime <= 0 {
|
||||
continue
|
||||
}
|
||||
if atomic.LoadInt32(&downloader.pins) == 0 {
|
||||
if completedTime < oldestTime {
|
||||
oldestFid, oldestTime = fid, completedTime
|
||||
}
|
||||
} else if pinnedFid == "" || completedTime < pinnedTime {
|
||||
pinnedFid, pinnedTime = fid, completedTime
|
||||
}
|
||||
}
|
||||
if oldestFid == "" {
|
||||
oldestFid = pinnedFid
|
||||
}
|
||||
if oldestFid != "" {
|
||||
oldDownloader := rc.downloaders[oldestFid]
|
||||
@@ -175,9 +229,77 @@ retry:
|
||||
rc.downloaders[fileId] = cacher
|
||||
cacher.wg.Add(1)
|
||||
atomic.AddInt32(&cacher.readers, 1)
|
||||
previous := stream.pin(cacher)
|
||||
rc.Unlock()
|
||||
rc.unpin(previous)
|
||||
|
||||
return cacher.readChunkAt(ctx, buffer, offset)
|
||||
n, err := cacher.readChunkAt(ctx, buffer, offset)
|
||||
rc.releaseIfFinished(stream, cacher, offset, n, err, chunkSize)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// pin makes cacher the stream's current chunk and returns the chunk it was
|
||||
// pinned to before, which the caller unpins once the ReaderCache lock is
|
||||
// released. The stream is only touched under the ReaderCache lock, since
|
||||
// concurrent ReadAt calls on one ChunkReadAt share it.
|
||||
func (stream *chunkStream) pin(cacher *SingleChunkCacher) (previous *SingleChunkCacher) {
|
||||
if stream == nil || stream.cacher == cacher {
|
||||
return nil
|
||||
}
|
||||
previous = stream.cacher
|
||||
stream.cacher = cacher
|
||||
atomic.AddInt32(&cacher.pins, 1)
|
||||
return previous
|
||||
}
|
||||
|
||||
// unpinLocked detaches the stream from its chunk and returns that chunk for
|
||||
// the caller to unpin once the ReaderCache lock is released.
|
||||
func (stream *chunkStream) unpinLocked() (previous *SingleChunkCacher) {
|
||||
if stream == nil {
|
||||
return nil
|
||||
}
|
||||
previous = stream.cacher
|
||||
stream.cacher = nil
|
||||
return previous
|
||||
}
|
||||
|
||||
// releaseIfFinished unpins the stream's chunk once the stream has read it to
|
||||
// the end, since the stream will not come back to it.
|
||||
func (rc *ReaderCache) releaseIfFinished(stream *chunkStream, cacher *SingleChunkCacher, offset int64, n int, err error, chunkSize int) {
|
||||
if stream == nil || err != nil || offset+int64(n) < int64(chunkSize) {
|
||||
return
|
||||
}
|
||||
var previous *SingleChunkCacher
|
||||
rc.Lock()
|
||||
if stream.cacher == cacher {
|
||||
previous = stream.unpinLocked()
|
||||
}
|
||||
rc.Unlock()
|
||||
rc.unpin(previous)
|
||||
}
|
||||
|
||||
// releaseStream unpins whatever chunk the stream is positioned in.
|
||||
func (rc *ReaderCache) releaseStream(stream *chunkStream) {
|
||||
if stream == nil {
|
||||
return
|
||||
}
|
||||
rc.Lock()
|
||||
previous := stream.unpinLocked()
|
||||
rc.Unlock()
|
||||
rc.unpin(previous)
|
||||
}
|
||||
|
||||
// unpin drops one stream's pin. Once no stream is positioned in the chunk it
|
||||
// is dropped like UnCache would, as soon as no read is in progress either:
|
||||
// here if none is, otherwise by the last read's removeConsumed.
|
||||
func (rc *ReaderCache) unpin(downloader *SingleChunkCacher) {
|
||||
if downloader == nil {
|
||||
return
|
||||
}
|
||||
if atomic.AddInt32(&downloader.pins, -1) == 0 {
|
||||
atomic.StoreInt32(&downloader.left, 1)
|
||||
}
|
||||
rc.removeConsumed(downloader)
|
||||
}
|
||||
|
||||
func (rc *ReaderCache) UnCache(fileId string) {
|
||||
@@ -202,15 +324,34 @@ func (rc *ReaderCache) remove(downloader *SingleChunkCacher) {
|
||||
}
|
||||
}
|
||||
|
||||
// removeConsumed drops a cacher once its buffer was fully read and no
|
||||
// readers remain attached. The checks run under the ReaderCache lock so a
|
||||
// reader attaching at the same time either wins (the cacher stays and that
|
||||
// reader's detach retries the removal) or misses the map and refetches.
|
||||
// removeUnpinned drops a cacher only while no stream is positioned in it.
|
||||
// Budget eviction picks its victim under the budget lock, so the pin check
|
||||
// and the map removal must happen together under the ReaderCache lock.
|
||||
func (rc *ReaderCache) removeUnpinned(downloader *SingleChunkCacher) (removed bool) {
|
||||
rc.Lock()
|
||||
removed = rc.downloaders[downloader.chunkFileId] == downloader &&
|
||||
atomic.LoadInt32(&downloader.pins) == 0
|
||||
if removed {
|
||||
delete(rc.downloaders, downloader.chunkFileId)
|
||||
}
|
||||
rc.Unlock()
|
||||
if removed {
|
||||
downloader.destroy()
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// removeConsumed drops a cacher once its buffer was fully read, or the
|
||||
// streams positioned in it have left, and no readers remain attached or
|
||||
// pinned. The checks run under the ReaderCache lock so a reader attaching
|
||||
// at the same time either wins (the cacher stays and that reader's detach
|
||||
// retries the removal) or misses the map and refetches.
|
||||
func (rc *ReaderCache) removeConsumed(downloader *SingleChunkCacher) {
|
||||
rc.Lock()
|
||||
removed := rc.downloaders[downloader.chunkFileId] == downloader &&
|
||||
atomic.LoadInt32(&downloader.readers) == 0 &&
|
||||
atomic.LoadInt32(&downloader.consumed) != 0
|
||||
atomic.LoadInt32(&downloader.pins) == 0 &&
|
||||
(atomic.LoadInt32(&downloader.consumed) != 0 || atomic.LoadInt32(&downloader.left) != 0)
|
||||
if removed {
|
||||
delete(rc.downloaders, downloader.chunkFileId)
|
||||
}
|
||||
|
||||
@@ -4,6 +4,7 @@ import (
|
||||
"container/list"
|
||||
"fmt"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/mem"
|
||||
)
|
||||
@@ -51,12 +52,39 @@ func (b *ReaderCacheBudget) reserve(s *SingleChunkCacher) error {
|
||||
b.Unlock()
|
||||
return nil
|
||||
}
|
||||
if entry := b.idle.Front(); entry != nil {
|
||||
victim := entry.Value.(*SingleChunkCacher)
|
||||
// Prefer evicting an idle chunk no stream is positioned in; fall back
|
||||
// to the oldest pinned one so abandoned pins cannot block the budget.
|
||||
var victim *SingleChunkCacher
|
||||
var entry *list.Element
|
||||
pinnedVictim := false
|
||||
for e := b.idle.Front(); e != nil; e = e.Next() {
|
||||
c := e.Value.(*SingleChunkCacher)
|
||||
if atomic.LoadInt32(&c.pins) == 0 {
|
||||
victim, entry = c, e
|
||||
pinnedVictim = false
|
||||
break
|
||||
}
|
||||
if victim == nil {
|
||||
victim, entry = c, e
|
||||
pinnedVictim = true
|
||||
}
|
||||
}
|
||||
if entry != nil {
|
||||
b.idle.Remove(entry)
|
||||
delete(b.idleEntries, victim)
|
||||
b.Unlock()
|
||||
victim.parent.remove(victim)
|
||||
if pinnedVictim {
|
||||
victim.parent.remove(victim)
|
||||
} else if !victim.parent.removeUnpinned(victim) {
|
||||
// The victim was pinned between selection and removal: keep it
|
||||
// evictable so a pin abandoned in that gap cannot wedge the
|
||||
// budget, then retry the selection.
|
||||
b.Lock()
|
||||
if _, ok := b.reservations[victim]; ok && b.idleEntries[victim] == nil {
|
||||
b.idleEntries[victim] = b.idle.PushBack(victim)
|
||||
}
|
||||
b.Unlock()
|
||||
}
|
||||
continue
|
||||
}
|
||||
changed := b.changed
|
||||
@@ -65,6 +93,13 @@ func (b *ReaderCacheBudget) reserve(s *SingleChunkCacher) error {
|
||||
}
|
||||
}
|
||||
|
||||
// canFit reports whether a whole-chunk buffer of this size can ever be
|
||||
// reserved. A chunk bigger than the budget cannot be read through the
|
||||
// whole-chunk path at all, so callers must fall back to range fetches.
|
||||
func (b *ReaderCacheBudget) canFit(size int) bool {
|
||||
return b == nil || int64(mem.AllocationSize(size)) <= b.limit
|
||||
}
|
||||
|
||||
func (b *ReaderCacheBudget) complete(s *SingleChunkCacher) {
|
||||
if b == nil {
|
||||
return
|
||||
|
||||
@@ -72,7 +72,7 @@ func TestReaderCacheBudgetInFlight(t *testing.T) {
|
||||
return len(buffer), nil
|
||||
}
|
||||
if prefetch {
|
||||
rc.MaybeCache(&Interval[*ChunkView]{Value: &ChunkView{FileId: "chunk", ChunkSize: 3 << 10}}, 1)
|
||||
rc.MaybeCache(&Interval[*ChunkView]{Value: &ChunkView{FileId: "chunk", ViewSize: 3 << 10, ChunkSize: 3 << 10}}, 1)
|
||||
} else {
|
||||
readers.Add(1)
|
||||
go func() {
|
||||
@@ -180,7 +180,7 @@ func TestReaderCacheFailedPrefetchReleasesBudget(t *testing.T) {
|
||||
rc.fetchChunkDataFn = func(_ context.Context, _ []byte, _ []string, _ []byte, _ bool, _ bool, _ int64, _ string, _ util_http.RefreshUrlsFunc) (int, error) {
|
||||
return 0, fmt.Errorf("fetch failed")
|
||||
}
|
||||
rc.MaybeCache(&Interval[*ChunkView]{Value: &ChunkView{FileId: "failed", ChunkSize: 1024}}, 1)
|
||||
rc.MaybeCache(&Interval[*ChunkView]{Value: &ChunkView{FileId: "failed", ViewSize: 1024, ChunkSize: 1024}}, 1)
|
||||
deadline := time.Now().Add(5 * time.Second)
|
||||
for {
|
||||
rc.Lock()
|
||||
@@ -278,7 +278,7 @@ func TestReaderCachePrefetchBufferDroppedAfterRead(t *testing.T) {
|
||||
buffer[0] = 42
|
||||
return len(buffer), nil
|
||||
}
|
||||
rc.MaybeCache(&Interval[*ChunkView]{Value: &ChunkView{FileId: "chunk", ChunkSize: 4 << 10}}, 1)
|
||||
rc.MaybeCache(&Interval[*ChunkView]{Value: &ChunkView{FileId: "chunk", ViewSize: 4 << 10, ChunkSize: 4 << 10}}, 1)
|
||||
|
||||
buf := make([]byte, 4<<10)
|
||||
n, err := rc.ReadChunkAt(context.Background(), buf, "chunk", nil, false, 0, 4<<10, false)
|
||||
|
||||
@@ -54,10 +54,13 @@ func (rp *ReaderPattern) MonitorReadAt(offset int64, size int) {
|
||||
if counter < ModeChangeLimit {
|
||||
atomic.AddInt64(&rp.isSequentialCounter, 1)
|
||||
}
|
||||
} else if counter <= 0 {
|
||||
// Entering random mode is a strong verdict: drop to the bottom of
|
||||
// the window so the contiguous tail of one ranged request cannot
|
||||
// flip it back on the next buffer read and pay a whole-chunk fetch.
|
||||
atomic.StoreInt64(&rp.isSequentialCounter, -ModeChangeLimit)
|
||||
} else {
|
||||
if counter > -ModeChangeLimit {
|
||||
atomic.AddInt64(&rp.isSequentialCounter, -1)
|
||||
}
|
||||
atomic.AddInt64(&rp.isSequentialCounter, -1)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -102,3 +102,23 @@ func TestReaderPatternRecoversFromRandom(t *testing.T) {
|
||||
t.Fatal("sustained near reads must recover sequential mode")
|
||||
}
|
||||
}
|
||||
|
||||
// A ranged request's first read lands far from the frontier, but its
|
||||
// remaining buffer reads are contiguous. The random verdict must stick for
|
||||
// them — otherwise the tail of every range >256KiB pays a whole-chunk fetch.
|
||||
func TestReaderPatternRangedReadStaysRandom(t *testing.T) {
|
||||
rp := NewReaderPattern()
|
||||
rp.MonitorReadAt(500*mb, 256*1024) // far first read -> -ModeChangeLimit
|
||||
for i := 1; i <= 2; i++ {
|
||||
rp.MonitorReadAt(500*mb+int64(i)*256*1024, 256*1024)
|
||||
if !rp.IsRandomMode() {
|
||||
t.Fatalf("contiguous read %d of a ranged request flipped back to sequential", i+1)
|
||||
}
|
||||
}
|
||||
for i := 3; i < 10; i++ {
|
||||
rp.MonitorReadAt(500*mb+int64(i)*256*1024, 256*1024)
|
||||
}
|
||||
if rp.IsRandomMode() {
|
||||
t.Fatal("sustained sequential reads should restore sequential mode")
|
||||
}
|
||||
}
|
||||
@@ -116,6 +116,14 @@ func (c *GenericCachedRoleStore) DeleteRole(ctx context.Context, filerAddress st
|
||||
return c.Delete(ctx, filerAddress, roleName)
|
||||
}
|
||||
|
||||
// UpdateRole implements RoleStore interface. The update reads the filer, not
|
||||
// the cache, and the cache is dropped afterwards whatever the outcome: a
|
||||
// refused write may mean the cached role is stale.
|
||||
func (c *GenericCachedRoleStore) UpdateRole(ctx context.Context, filerAddress string, roleName string, update RoleUpdate) error {
|
||||
defer c.ClearCache()
|
||||
return c.adapter.store.UpdateRole(ctx, filerAddress, roleName, update)
|
||||
}
|
||||
|
||||
// genericCopyRoleDefinition creates a deep copy of a RoleDefinition for the generic cache
|
||||
func genericCopyRoleDefinition(role *RoleDefinition) *RoleDefinition {
|
||||
if role == nil {
|
||||
@@ -123,9 +131,13 @@ func genericCopyRoleDefinition(role *RoleDefinition) *RoleDefinition {
|
||||
}
|
||||
|
||||
result := &RoleDefinition{
|
||||
RoleName: role.RoleName,
|
||||
RoleArn: role.RoleArn,
|
||||
Description: role.Description,
|
||||
RoleName: role.RoleName,
|
||||
RoleArn: role.RoleArn,
|
||||
Description: role.Description,
|
||||
MaxSessionDuration: role.MaxSessionDuration,
|
||||
Source: role.Source,
|
||||
CreatedAt: role.CreatedAt,
|
||||
RoleId: role.RoleId,
|
||||
}
|
||||
|
||||
// Deep copy trust policy if it exists
|
||||
|
||||
@@ -2,7 +2,10 @@ package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
@@ -27,11 +30,30 @@ const maxPoliciesForEvaluation = 1024
|
||||
|
||||
// IAMManager orchestrates all IAM components
|
||||
type IAMManager struct {
|
||||
stsService *sts.STSService
|
||||
policyEngine *policy.PolicyEngine
|
||||
roleStore RoleStore
|
||||
userStore UserStore
|
||||
oidcProviderStore OIDCProviderStore
|
||||
stsService *sts.STSService
|
||||
policyEngine *policy.PolicyEngine
|
||||
roleStore RoleStore
|
||||
userStore UserStore
|
||||
oidcProviderStore OIDCProviderStore
|
||||
// staticOIDCProviders are the OIDC providers of this server's IAM config
|
||||
// file, by ARN. With an in-memory store they are also written to the
|
||||
// store; a persistent store never holds them (see installOIDCProviderStore).
|
||||
staticOIDCProviders map[string]*OIDCProviderRecord
|
||||
// staticRoles are the roles of this server's IAM config file, by name, once
|
||||
// LoadStaticRoles has run (see installRoleStore).
|
||||
staticRoles map[string]*RoleDefinition
|
||||
// oidcRetryMu guards the background refresh retry and which store is
|
||||
// current: cancelOIDCLoad stops the retry, oidcRetryGen names the one
|
||||
// running (0 when none) so at most one runs, and oidcRetryAgain records a
|
||||
// refresh that failed while it ran, so the retry runs once more.
|
||||
oidcRetryMu sync.Mutex
|
||||
cancelOIDCLoad context.CancelFunc
|
||||
oidcRetryGen uint64
|
||||
oidcRetrySeq uint64
|
||||
oidcRetryAgain bool
|
||||
// oidcRefreshMu serializes refreshes from reading the store to handing
|
||||
// STS the result, so an older snapshot cannot replace a newer one.
|
||||
oidcRefreshMu sync.Mutex
|
||||
oidcAuditSink OIDCProviderAuditSink
|
||||
revocationStore SessionRevocationStore
|
||||
filerAddressProvider func() string // Function to get current filer address
|
||||
@@ -108,12 +130,13 @@ func (m *IAMManager) PurgeRevokedSessions(ctx context.Context) (int, error) {
|
||||
}
|
||||
|
||||
// SetOIDCProviderStore configures the IAM-managed OIDC provider store. When
|
||||
// nil, OIDC provider IAM actions return ServiceNotReady. The store is the
|
||||
// source of truth for AssumeRoleWithWebIdentity provider resolution once
|
||||
// Phase 2b lands; in Phase 2a it is read-only and populated from static
|
||||
// configuration at boot.
|
||||
// nil, OIDC provider IAM actions return ServiceNotReady.
|
||||
func (m *IAMManager) SetOIDCProviderStore(store OIDCProviderStore) {
|
||||
m.oidcProviderStore = store
|
||||
var stsConfig *sts.STSConfig
|
||||
if m.stsService != nil {
|
||||
stsConfig = m.stsService.Config
|
||||
}
|
||||
m.installOIDCProviderStore(store, stsConfig)
|
||||
}
|
||||
|
||||
// GetOIDCProviderStore returns the configured store (may be nil).
|
||||
@@ -121,13 +144,33 @@ func (m *IAMManager) GetOIDCProviderStore() OIDCProviderStore {
|
||||
return m.oidcProviderStore
|
||||
}
|
||||
|
||||
// GetRoleStore returns the configured role store.
|
||||
func (m *IAMManager) GetRoleStore() RoleStore {
|
||||
return m.roleStore
|
||||
}
|
||||
|
||||
// SetRoleStore replaces the role store. An S3 server builds the list of
|
||||
// directories it watches for peers' changes once, at startup, from the store
|
||||
// installed then (RoleStoreDirectory): a filer-backed store installed later
|
||||
// with a different basePath is not watched, so peers' changes to it reach this
|
||||
// server's cached roles only when the cache expires.
|
||||
func (m *IAMManager) SetRoleStore(store RoleStore) {
|
||||
m.installRoleStore(context.Background(), store)
|
||||
}
|
||||
|
||||
// GetOIDCProvider returns the record for the given ARN, or an error if the
|
||||
// store is not configured or the record is missing.
|
||||
func (m *IAMManager) GetOIDCProvider(ctx context.Context, arn string) (*OIDCProviderRecord, error) {
|
||||
if m.oidcProviderStore == nil {
|
||||
return nil, fmt.Errorf("OIDC provider store not configured")
|
||||
}
|
||||
return m.oidcProviderStore.GetProviderByARN(ctx, m.getFilerAddress(), arn)
|
||||
rec, err := m.oidcProviderStore.GetProviderByARN(ctx, m.getFilerAddress(), arn)
|
||||
if errors.Is(err, ErrOIDCProviderNotFound) {
|
||||
if static, ok := m.staticOIDCProviders[arn]; ok {
|
||||
return copyOIDCProviderRecord(static), nil
|
||||
}
|
||||
}
|
||||
return rec, err
|
||||
}
|
||||
|
||||
// ListOIDCProviders enumerates all configured OIDC providers.
|
||||
@@ -135,7 +178,33 @@ func (m *IAMManager) ListOIDCProviders(ctx context.Context) ([]*OIDCProviderReco
|
||||
if m.oidcProviderStore == nil {
|
||||
return nil, fmt.Errorf("OIDC provider store not configured")
|
||||
}
|
||||
return m.oidcProviderStore.ListProviders(ctx, m.getFilerAddress())
|
||||
records, err := m.oidcProviderStore.ListProviders(ctx, m.getFilerAddress())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// A persistent store does not hold the config file's providers.
|
||||
seen := make(map[string]bool, len(records))
|
||||
for _, rec := range records {
|
||||
seen[rec.ARN] = true
|
||||
}
|
||||
for arn, static := range m.staticOIDCProviders {
|
||||
if !seen[arn] {
|
||||
records = append(records, copyOIDCProviderRecord(static))
|
||||
}
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
|
||||
// mutableOIDCProvider loads a stored provider for a change. A provider only
|
||||
// the IAM config file defines is refused with ErrOIDCProviderStatic.
|
||||
func (m *IAMManager) mutableOIDCProvider(ctx context.Context, arn string) (*OIDCProviderRecord, error) {
|
||||
rec, err := m.oidcProviderStore.GetProviderByARN(ctx, m.getFilerAddress(), arn)
|
||||
if errors.Is(err, ErrOIDCProviderNotFound) {
|
||||
if _, ok := m.staticOIDCProviders[arn]; ok {
|
||||
return nil, fmt.Errorf("%w: %s", ErrOIDCProviderStatic, arn)
|
||||
}
|
||||
}
|
||||
return rec, err
|
||||
}
|
||||
|
||||
// CreateOIDCProvider persists a new IAM-managed OIDC provider record. Refuses
|
||||
@@ -150,6 +219,9 @@ func (m *IAMManager) CreateOIDCProvider(ctx context.Context, rec *OIDCProviderRe
|
||||
if err := validateOIDCProviderRecord(rec); err != nil {
|
||||
return err
|
||||
}
|
||||
if _, static := m.staticOIDCProviders[rec.ARN]; static {
|
||||
return fmt.Errorf("%w: %s", ErrOIDCProviderAlreadyExists, rec.ARN)
|
||||
}
|
||||
existing, err := m.oidcProviderStore.GetProviderByARN(ctx, m.getFilerAddress(), rec.ARN)
|
||||
if err == nil && existing != nil {
|
||||
return fmt.Errorf("%w: %s", ErrOIDCProviderAlreadyExists, rec.ARN)
|
||||
@@ -173,6 +245,9 @@ func (m *IAMManager) DeleteOIDCProvider(ctx context.Context, arn string) error {
|
||||
if m.oidcProviderStore == nil {
|
||||
return fmt.Errorf("OIDC provider store not configured")
|
||||
}
|
||||
if _, err := m.mutableOIDCProvider(ctx, arn); errors.Is(err, ErrOIDCProviderStatic) {
|
||||
return err
|
||||
}
|
||||
if err := m.oidcProviderStore.DeleteProvider(ctx, m.getFilerAddress(), arn); err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -190,7 +265,7 @@ func (m *IAMManager) AddClientIDToOIDCProvider(ctx context.Context, arn, clientI
|
||||
if clientID == "" {
|
||||
return fmt.Errorf("ClientID cannot be empty")
|
||||
}
|
||||
rec, err := m.oidcProviderStore.GetProviderByARN(ctx, m.getFilerAddress(), arn)
|
||||
rec, err := m.mutableOIDCProvider(ctx, arn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -218,7 +293,7 @@ func (m *IAMManager) RemoveClientIDFromOIDCProvider(ctx context.Context, arn, cl
|
||||
if m.oidcProviderStore == nil {
|
||||
return fmt.Errorf("OIDC provider store not configured")
|
||||
}
|
||||
rec, err := m.oidcProviderStore.GetProviderByARN(ctx, m.getFilerAddress(), arn)
|
||||
rec, err := m.mutableOIDCProvider(ctx, arn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -255,7 +330,7 @@ func (m *IAMManager) UpdateOIDCProviderThumbprints(ctx context.Context, arn stri
|
||||
return fmt.Errorf("invalid thumbprint %q: must be 40-character SHA-1 hex", tp)
|
||||
}
|
||||
}
|
||||
rec, err := m.oidcProviderStore.GetProviderByARN(ctx, m.getFilerAddress(), arn)
|
||||
rec, err := m.mutableOIDCProvider(ctx, arn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -274,7 +349,7 @@ func (m *IAMManager) TagOIDCProvider(ctx context.Context, arn string, tags map[s
|
||||
if m.oidcProviderStore == nil {
|
||||
return fmt.Errorf("OIDC provider store not configured")
|
||||
}
|
||||
rec, err := m.oidcProviderStore.GetProviderByARN(ctx, m.getFilerAddress(), arn)
|
||||
rec, err := m.mutableOIDCProvider(ctx, arn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -297,7 +372,7 @@ func (m *IAMManager) UntagOIDCProvider(ctx context.Context, arn string, keys []s
|
||||
if m.oidcProviderStore == nil {
|
||||
return fmt.Errorf("OIDC provider store not configured")
|
||||
}
|
||||
rec, err := m.oidcProviderStore.GetProviderByARN(ctx, m.getFilerAddress(), arn)
|
||||
rec, err := m.mutableOIDCProvider(ctx, arn)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -415,6 +490,88 @@ type RoleDefinition struct {
|
||||
// set it must satisfy AWS bounds: 3600 ≤ MaxSessionDuration ≤ 43200.
|
||||
// Honoured by AssumeRole, AssumeRoleWithWebIdentity, AssumeRoleWithCredentials.
|
||||
MaxSessionDuration int64 `json:"maxSessionDuration,omitempty"`
|
||||
|
||||
// Source records where the role came from. RoleSourceStaticConfig marks a
|
||||
// role loaded from the IAM config file; empty means it was created at
|
||||
// runtime. Only static-config roles are pruned when they leave the file.
|
||||
Source string `json:"source,omitempty"`
|
||||
|
||||
// CreatedAt is when the role was created through the IAM API. Zero for
|
||||
// roles loaded from the config file.
|
||||
CreatedAt time.Time `json:"createdAt,omitempty"`
|
||||
|
||||
// RoleId uniquely identifies this role, as AWS's RoleId does. A role
|
||||
// deleted and created again under the same name gets a new ID, and a
|
||||
// session is honoured only while the role it was issued for still has
|
||||
// the ID the session carries — so a session outlives neither the role's
|
||||
// deletion nor a later role that reuses its name.
|
||||
RoleId string `json:"roleId,omitempty"`
|
||||
}
|
||||
|
||||
// NewRoleID returns a fresh, random role ID in AWS's AROA form.
|
||||
func NewRoleID() string {
|
||||
const alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ234567"
|
||||
b := make([]byte, 17)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
panic(fmt.Sprintf("read random role id: %v", err))
|
||||
}
|
||||
for i := range b {
|
||||
b[i] = alphabet[int(b[i])%len(alphabet)]
|
||||
}
|
||||
return "AROA" + string(b)
|
||||
}
|
||||
|
||||
// StaticRoleID is the ID of a role defined in the IAM config file. Such a
|
||||
// role is created again at every start, so its ID is derived rather than
|
||||
// random, to keep sessions valid across restarts. It is derived from the name
|
||||
// and the trust policy together: a role removed from the file and replaced by
|
||||
// a different one under the same name trusts different principals, and must
|
||||
// not inherit the old role's sessions. Restoring the same role restores its ID.
|
||||
func StaticRoleID(role *RoleDefinition) string {
|
||||
h := sha256.New()
|
||||
h.Write([]byte("static-role:" + role.RoleName + "\x00"))
|
||||
if role.TrustPolicy != nil {
|
||||
trust, err := json.Marshal(role.TrustPolicy)
|
||||
if err != nil {
|
||||
// A trust policy that cannot be encoded cannot be matched on
|
||||
// either; give the role an ID no session can carry.
|
||||
return NewRoleID()
|
||||
}
|
||||
h.Write(trust)
|
||||
}
|
||||
return "AROA" + strings.ToUpper(hex.EncodeToString(h.Sum(nil)))[:17]
|
||||
}
|
||||
|
||||
// RoleSourceStaticConfig is the Source of a role loaded from the IAM config
|
||||
// file.
|
||||
const RoleSourceStaticConfig = "static-config"
|
||||
|
||||
// checkSessionRoleBinding refuses a session issued for a role that has since
|
||||
// been deleted, or replaced by a role reusing its name: the role's current ID
|
||||
// must be the one the session carries. It runs for every session carrying a
|
||||
// role ID, whatever policies the session embeds — the policies a session
|
||||
// embeds are the ones its role had, and outlive the role otherwise. A session
|
||||
// issued before role IDs were recorded carries none and is not bound. It
|
||||
// returns the role it checked, nil for an unbound session.
|
||||
func (m *IAMManager) checkSessionRoleBinding(ctx context.Context, sessionInfo *sts.SessionInfo) (*RoleDefinition, error) {
|
||||
if sessionInfo == nil || sessionInfo.RoleId == "" {
|
||||
return nil, nil
|
||||
}
|
||||
roleName := utils.ExtractRoleNameFromArn(sessionInfo.RoleArn)
|
||||
if roleName == "" {
|
||||
return nil, nil
|
||||
}
|
||||
role, err := m.roleStore.GetRole(ctx, m.getFilerAddress(), roleName)
|
||||
if errors.Is(err, ErrRoleNotFound) {
|
||||
return nil, fmt.Errorf("session was issued for role %s, which no longer exists", roleName)
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("resolve role %s for session: %w", roleName, err)
|
||||
}
|
||||
if role.RoleId != sessionInfo.RoleId {
|
||||
return nil, fmt.Errorf("session was issued for an earlier role named %s", roleName)
|
||||
}
|
||||
return role, nil
|
||||
}
|
||||
|
||||
// ActionRequest represents a request to perform an action
|
||||
@@ -557,55 +714,174 @@ func (m *IAMManager) initOIDCProviderStore(config *IAMConfig) error {
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
m.oidcProviderStore = store
|
||||
m.installOIDCProviderStore(store, config.STS)
|
||||
return nil
|
||||
}
|
||||
|
||||
if config.STS == nil {
|
||||
return nil
|
||||
// installOIDCProviderStore makes store the manager's OIDC provider store.
|
||||
//
|
||||
// The IAM config file's providers are reported by the IAM API alongside the
|
||||
// stored ones. An in-memory store holds them as records, as it always has. A
|
||||
// persistent store never does: it outlives this process and may be shared by
|
||||
// S3 servers with different config files, so a record written from one file
|
||||
// would outlive its removal from that file and be trusted by every server.
|
||||
// Those providers stay in memory (staticOIDCProviders) and STS keeps serving
|
||||
// them from its static configuration; the store holds only providers created
|
||||
// through the IAM API, and those are loaded into STS here.
|
||||
//
|
||||
// A provider stored under the same ARN as a config-file provider takes
|
||||
// precedence, in the IAM API as in STS, which already prefers IAM-managed
|
||||
// providers so that an API call can shadow a bootstrap entry. Deleting the
|
||||
// stored provider brings the config-file one back.
|
||||
func (m *IAMManager) installOIDCProviderStore(store OIDCProviderStore, stsConfig *sts.STSConfig) {
|
||||
// Cancel the old store's retry and switch stores in one step, so a failed
|
||||
// refresh of the old store cannot start a retry after the cancel.
|
||||
m.oidcRetryMu.Lock()
|
||||
m.stopOIDCRetryLocked()
|
||||
m.oidcProviderStore = store
|
||||
m.oidcRetryMu.Unlock()
|
||||
m.staticOIDCProviders = staticOIDCProviderRecords(stsConfig)
|
||||
if _, inMemory := store.(*MemoryOIDCProviderStore); inMemory {
|
||||
ctx := context.Background()
|
||||
now := time.Now().UTC()
|
||||
for _, rec := range m.staticOIDCProviders {
|
||||
mirrored := copyOIDCProviderRecord(rec)
|
||||
mirrored.CreatedAt, mirrored.UpdatedAt = now, now
|
||||
if err := store.StoreProvider(ctx, m.getFilerAddress(), mirrored); err != nil {
|
||||
glog.Warningf("mirror static OIDC provider %s into store: %v", rec.ARN, err)
|
||||
}
|
||||
}
|
||||
// The store now holds them and the API may change them, as before;
|
||||
// the overlay is only for stores that must not hold them.
|
||||
m.staticOIDCProviders = nil
|
||||
return
|
||||
}
|
||||
for _, pc := range config.STS.Providers {
|
||||
// The metadata subscription only reports changes made from now on, so
|
||||
// providers already in the store would stay unknown until one changes; a
|
||||
// failed load is retried (RefreshOIDCProvidersFromStore).
|
||||
if err := m.RefreshOIDCProvidersFromStore(context.Background()); err != nil {
|
||||
glog.Warningf("load OIDC providers from the store at startup: %v; retrying in the background", err)
|
||||
}
|
||||
}
|
||||
|
||||
// startOIDCRetry retries loading store in the background until it succeeds.
|
||||
// A store that is no longer current gets no retry: nothing would cancel it,
|
||||
// and its eventual success would replace the current store's providers. When
|
||||
// a retry is already running, it is asked to run once more instead, because
|
||||
// it may already have listed a snapshot older than this failure.
|
||||
func (m *IAMManager) startOIDCRetry(store OIDCProviderStore) {
|
||||
m.oidcRetryMu.Lock()
|
||||
defer m.oidcRetryMu.Unlock()
|
||||
if store != m.oidcProviderStore {
|
||||
return
|
||||
}
|
||||
if m.oidcRetryGen != 0 {
|
||||
m.oidcRetryAgain = true
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithCancel(context.Background())
|
||||
m.oidcRetrySeq++
|
||||
gen := m.oidcRetrySeq
|
||||
m.cancelOIDCLoad, m.oidcRetryGen = cancel, gen
|
||||
bounds := oidcHydrateRetry // read here, not in the goroutine: it outlives its caller
|
||||
go func() {
|
||||
defer cancel()
|
||||
for {
|
||||
m.retryOIDCProviderLoad(ctx, store, bounds)
|
||||
m.oidcRetryMu.Lock()
|
||||
if m.oidcRetryGen != gen {
|
||||
m.oidcRetryMu.Unlock()
|
||||
return // cancelled: another store was installed
|
||||
}
|
||||
if m.oidcRetryAgain && ctx.Err() == nil {
|
||||
m.oidcRetryAgain = false
|
||||
m.oidcRetryMu.Unlock()
|
||||
continue
|
||||
}
|
||||
m.cancelOIDCLoad, m.oidcRetryGen, m.oidcRetryAgain = nil, 0, false
|
||||
m.oidcRetryMu.Unlock()
|
||||
return
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// stopOIDCRetryLocked cancels a running retry, as installing another store
|
||||
// must. The caller holds oidcRetryMu.
|
||||
func (m *IAMManager) stopOIDCRetryLocked() {
|
||||
if m.cancelOIDCLoad != nil {
|
||||
m.cancelOIDCLoad()
|
||||
}
|
||||
m.cancelOIDCLoad, m.oidcRetryGen, m.oidcRetryAgain = nil, 0, false
|
||||
}
|
||||
|
||||
// currentOIDCProviderStore is the installed store, read under oidcRetryMu.
|
||||
func (m *IAMManager) currentOIDCProviderStore() OIDCProviderStore {
|
||||
m.oidcRetryMu.Lock()
|
||||
defer m.oidcRetryMu.Unlock()
|
||||
return m.oidcProviderStore
|
||||
}
|
||||
|
||||
// staticOIDCProviderRecords describes the enabled OIDC providers of the IAM
|
||||
// config file as provider records.
|
||||
func staticOIDCProviderRecords(stsConfig *sts.STSConfig) map[string]*OIDCProviderRecord {
|
||||
out := map[string]*OIDCProviderRecord{}
|
||||
if stsConfig == nil {
|
||||
return out
|
||||
}
|
||||
for _, pc := range stsConfig.Providers {
|
||||
if pc == nil || !pc.Enabled || pc.Type != sts.ProviderTypeOIDC {
|
||||
continue
|
||||
}
|
||||
issuer, _ := pc.Config["issuer"].(string)
|
||||
if issuer == "" {
|
||||
glog.Warningf("OIDC provider %s in static config has empty issuer; skipping mirror to store", pc.Name)
|
||||
glog.Warningf("OIDC provider %s in static config has empty issuer; skipping", pc.Name)
|
||||
continue
|
||||
}
|
||||
accountID := ""
|
||||
if config.STS != nil {
|
||||
accountID = config.STS.AccountId
|
||||
}
|
||||
arn, err := DeriveOIDCProviderARN(accountID, issuer)
|
||||
arn, err := DeriveOIDCProviderARN(stsConfig.AccountId, issuer)
|
||||
if err != nil {
|
||||
glog.Warningf("derive ARN for static OIDC provider %s: %v", pc.Name, err)
|
||||
continue
|
||||
}
|
||||
clientIDs := extractClientIDs(pc.Config)
|
||||
ctx := context.Background()
|
||||
// Preserve CreatedAt across reboots when a persistent store already
|
||||
// has this provider — IAM's GetOpenIDConnectProvider response
|
||||
// shouldn't shift its CreateDate every time the server restarts.
|
||||
now := time.Now().UTC()
|
||||
createdAt := now
|
||||
if existing, err := store.GetProviderByARN(ctx, m.getFilerAddress(), arn); err == nil && existing != nil && !existing.CreatedAt.IsZero() {
|
||||
createdAt = existing.CreatedAt
|
||||
}
|
||||
rec := &OIDCProviderRecord{
|
||||
AccountID: accountID,
|
||||
out[arn] = &OIDCProviderRecord{
|
||||
AccountID: stsConfig.AccountId,
|
||||
ARN: arn,
|
||||
URL: issuer,
|
||||
ClientIDs: clientIDs,
|
||||
ClientIDs: extractClientIDs(pc.Config),
|
||||
Thumbprints: extractStringList(pc.Config, "thumbprints"),
|
||||
AllowedPrincipalTagKeys: extractStringList(pc.Config, "allowedPrincipalTagKeys"),
|
||||
PolicyClaim: extractString(pc.Config, "policyClaim"),
|
||||
CreatedAt: createdAt,
|
||||
UpdatedAt: now,
|
||||
// No CreatedAt: a config-file provider has no creation time the
|
||||
// server could report consistently across restarts.
|
||||
}
|
||||
if err := store.StoreProvider(ctx, m.getFilerAddress(), rec); err != nil {
|
||||
glog.Warningf("mirror static OIDC provider %s into store: %v", pc.Name, err)
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// oidcHydrateRetry bounds the backoff between startup load attempts.
|
||||
var oidcHydrateRetry = struct{ initial, max time.Duration }{initial: time.Second, max: 30 * time.Second}
|
||||
|
||||
// retryOIDCProviderLoad retries loading store, the store it was started for,
|
||||
// until it succeeds or ctx is cancelled because another store was installed.
|
||||
// It calls refreshOIDCProvidersFrom, not RefreshOIDCProvidersFromStore, so it
|
||||
// never schedules a retry of its own.
|
||||
func (m *IAMManager) retryOIDCProviderLoad(ctx context.Context, store OIDCProviderStore, bounds struct{ initial, max time.Duration }) {
|
||||
delay := bounds.initial
|
||||
for {
|
||||
select {
|
||||
case <-ctx.Done():
|
||||
return
|
||||
case <-time.After(delay):
|
||||
}
|
||||
err := m.refreshOIDCProvidersFrom(ctx, store)
|
||||
if err == nil {
|
||||
glog.V(0).Infof("loaded OIDC providers from the store after retrying")
|
||||
return
|
||||
}
|
||||
glog.V(1).Infof("load OIDC providers from the store: %v; retrying in %v", err, delay)
|
||||
if delay *= 2; delay > bounds.max {
|
||||
delay = bounds.max
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// refreshOIDCProvidersBestEffort calls RefreshOIDCProvidersFromStore and
|
||||
@@ -626,14 +902,46 @@ func (m *IAMManager) refreshOIDCProvidersBestEffort(ctx context.Context, op, arn
|
||||
// the store is empty (clears the IAM-managed map). Records with empty URLs
|
||||
// or invalid configuration are logged and skipped so a single bad entry
|
||||
// does not stop the rest from refreshing.
|
||||
//
|
||||
// A refresh that fails keeps retrying in the background until the store
|
||||
// answers. Every caller needs that: a metadata-subscription event reports each
|
||||
// change ONCE, so a refresh that found the filer unreachable on it would leave
|
||||
// a peer's new provider untrusted, or a deleted one trusted, until an unrelated
|
||||
// later change; the refresh after a local IAM API mutation and the startup load
|
||||
// have the same shape. At most one retry runs.
|
||||
func (m *IAMManager) RefreshOIDCProvidersFromStore(ctx context.Context) error {
|
||||
if m.oidcProviderStore == nil || m.stsService == nil {
|
||||
store := m.currentOIDCProviderStore()
|
||||
err := m.refreshOIDCProvidersFrom(ctx, store)
|
||||
if err != nil && store != nil {
|
||||
m.startOIDCRetry(store)
|
||||
}
|
||||
return err
|
||||
}
|
||||
|
||||
// refreshOIDCProvidersFrom is RefreshOIDCProvidersFromStore for a given store.
|
||||
func (m *IAMManager) refreshOIDCProvidersFrom(ctx context.Context, store OIDCProviderStore) error {
|
||||
if store == nil || m.stsService == nil {
|
||||
return nil
|
||||
}
|
||||
records, err := m.oidcProviderStore.ListProviders(ctx, m.getFilerAddress())
|
||||
// Refreshes run concurrently: after an IAM API change, on a peer's change
|
||||
// and in the startup retry. Unserialized, a refresh that read the store
|
||||
// before a DeleteOIDCProvider could finish after that call's own refresh
|
||||
// and keep the deleted provider trusted.
|
||||
m.oidcRefreshMu.Lock()
|
||||
defer m.oidcRefreshMu.Unlock()
|
||||
records, err := store.ListProviders(ctx, m.getFilerAddress())
|
||||
if err != nil {
|
||||
return fmt.Errorf("list OIDC providers: %w", err)
|
||||
}
|
||||
// A snapshot of a store that has since been replaced must not replace the
|
||||
// current store's providers: a retry is cancelled when another store is
|
||||
// installed, and a refresh may have listed the old store just before.
|
||||
if err := ctx.Err(); err != nil {
|
||||
return err
|
||||
}
|
||||
if store != m.currentOIDCProviderStore() {
|
||||
return fmt.Errorf("list OIDC providers: the store was replaced during the refresh")
|
||||
}
|
||||
byIssuer := make(map[string][]sts.ScopedOIDCProvider, len(records))
|
||||
for _, rec := range records {
|
||||
if rec == nil || rec.URL == "" {
|
||||
@@ -664,9 +972,11 @@ func buildOIDCProviderFromRecord(rec *OIDCProviderRecord) (*oidc.OIDCProvider, e
|
||||
return nil, fmt.Errorf("record cannot be nil")
|
||||
}
|
||||
cfg := &oidc.OIDCConfig{
|
||||
Issuer: rec.URL,
|
||||
ClientIDs: append([]string(nil), rec.ClientIDs...),
|
||||
Thumbprints: append([]string(nil), rec.Thumbprints...),
|
||||
Issuer: rec.URL,
|
||||
ClientIDs: append([]string(nil), rec.ClientIDs...),
|
||||
Thumbprints: append([]string(nil), rec.Thumbprints...),
|
||||
AllowedPrincipalTagKeys: append([]string(nil), rec.AllowedPrincipalTagKeys...),
|
||||
PolicyClaim: rec.PolicyClaim,
|
||||
}
|
||||
provider := oidc.NewOIDCProvider(rec.ARN)
|
||||
if err := provider.Initialize(cfg); err != nil {
|
||||
@@ -800,14 +1110,51 @@ func (m *IAMManager) CreateRole(ctx context.Context, filerAddress string, roleNa
|
||||
if !m.initialized {
|
||||
return fmt.Errorf("IAM manager not initialized")
|
||||
}
|
||||
if err := PrepareRoleDefinition(roleName, roleDef); err != nil {
|
||||
return err
|
||||
}
|
||||
if roleDef.RoleId == "" {
|
||||
roleDef.RoleId = NewRoleID()
|
||||
}
|
||||
|
||||
// Store role definition
|
||||
return m.roleStore.StoreRole(ctx, "", roleName, roleDef)
|
||||
}
|
||||
|
||||
// UpdateRole changes a role atomically in the role store (see
|
||||
// RoleStore.UpdateRole). update receives the role's current definition, nil
|
||||
// when it does not exist, and its result is validated like CreateRole's; a
|
||||
// nil result deletes the role.
|
||||
// The IAM API's role actions use it, so a change made on one S3 server is
|
||||
// neither lost to a concurrent change on another nor written over a delete.
|
||||
func (m *IAMManager) UpdateRole(ctx context.Context, roleName string, update RoleUpdate) error {
|
||||
if !m.initialized {
|
||||
return fmt.Errorf("IAM manager not initialized")
|
||||
}
|
||||
return m.roleStore.UpdateRole(ctx, "", roleName, func(current *RoleDefinition) (*RoleDefinition, error) {
|
||||
next, err := update(current)
|
||||
if err != nil || next == nil {
|
||||
return next, err
|
||||
}
|
||||
if err := PrepareRoleDefinition(roleName, next); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return next, nil
|
||||
})
|
||||
}
|
||||
|
||||
// PrepareRoleDefinition applies CreateRole's defaults and validation to a role
|
||||
// about to be stored or loaded.
|
||||
func PrepareRoleDefinition(roleName string, roleDef *RoleDefinition) error {
|
||||
if roleName == "" {
|
||||
return fmt.Errorf("role name cannot be empty")
|
||||
}
|
||||
|
||||
if roleDef == nil {
|
||||
return fmt.Errorf("role definition cannot be nil")
|
||||
}
|
||||
if roleDef.RoleName == "" {
|
||||
roleDef.RoleName = roleName
|
||||
}
|
||||
|
||||
// Set role ARN if not provided
|
||||
if roleDef.RoleArn == "" {
|
||||
@@ -827,12 +1174,122 @@ func (m *IAMManager) CreateRole(ctx context.Context, filerAddress string, roleNa
|
||||
return fmt.Errorf("MaxSessionDuration must be between 3600 and 43200 seconds, got %d", roleDef.MaxSessionDuration)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Store role definition
|
||||
return m.roleStore.StoreRole(ctx, "", roleName, roleDef)
|
||||
// LoadStaticRoles installs the roles of the IAM config file.
|
||||
//
|
||||
// An in-memory store holds them as records, as it always has. A persistent
|
||||
// store never does: it outlives this process and may be shared by S3 servers
|
||||
// with different config files, so a record written from one file would
|
||||
// outlive its removal from that file and be honoured by every server. Those
|
||||
// roles are served from memory instead, ahead of the store, and cannot be
|
||||
// changed or deleted through the store (ErrRoleStatic). A role stored under
|
||||
// the same name takes precedence. They report no creation time.
|
||||
func (m *IAMManager) LoadStaticRoles(ctx context.Context, roles []*RoleDefinition) {
|
||||
defs := make(map[string]*RoleDefinition, len(roles))
|
||||
for _, role := range roles {
|
||||
if role == nil {
|
||||
continue
|
||||
}
|
||||
role.Source = RoleSourceStaticConfig
|
||||
if role.RoleId == "" {
|
||||
role.RoleId = StaticRoleID(role)
|
||||
}
|
||||
if err := PrepareRoleDefinition(role.RoleName, role); err != nil {
|
||||
glog.Warningf("Failed to load role %s: %v", role.RoleName, err)
|
||||
continue
|
||||
}
|
||||
defs[role.RoleName] = role
|
||||
}
|
||||
m.staticRoles = defs
|
||||
m.installRoleStore(ctx, m.roleStore)
|
||||
}
|
||||
|
||||
// installRoleStore makes store the role store, with the config-file roles
|
||||
// installed in it as LoadStaticRoles describes, so a store set after startup
|
||||
// behaves like the one set at startup.
|
||||
func (m *IAMManager) installRoleStore(ctx context.Context, store RoleStore) {
|
||||
if overlay, ok := store.(*staticRoleOverlay); ok {
|
||||
store = overlay.inner
|
||||
}
|
||||
if store == nil || m.staticRoles == nil {
|
||||
m.roleStore = store
|
||||
return
|
||||
}
|
||||
if _, inMemory := store.(*MemoryRoleStore); inMemory {
|
||||
for name, role := range m.staticRoles {
|
||||
if err := store.StoreRole(ctx, "", name, role); err != nil {
|
||||
glog.Warningf("Failed to create role %s: %v", name, err)
|
||||
}
|
||||
}
|
||||
m.roleStore = store
|
||||
return
|
||||
}
|
||||
m.roleStore = &staticRoleOverlay{static: m.staticRoles, inner: store}
|
||||
}
|
||||
|
||||
// GetRole retrieves a role definition by name.
|
||||
// ListRoles returns every stored role definition.
|
||||
func (m *IAMManager) ListRoles(ctx context.Context) ([]*RoleDefinition, error) {
|
||||
if !m.initialized {
|
||||
return nil, fmt.Errorf("IAM manager not initialized")
|
||||
}
|
||||
names, err := m.roleStore.ListRoles(ctx, m.getFilerAddress())
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list roles: %w", err)
|
||||
}
|
||||
roles := make([]*RoleDefinition, 0, len(names))
|
||||
for _, name := range names {
|
||||
role, err := m.roleStore.GetRole(ctx, m.getFilerAddress(), name)
|
||||
if errors.Is(err, ErrRoleNotFound) {
|
||||
continue // deleted between list and read
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get role %s: %w", name, err)
|
||||
}
|
||||
roles = append(roles, role)
|
||||
}
|
||||
return roles, nil
|
||||
}
|
||||
|
||||
// DeleteRole removes a role definition.
|
||||
func (m *IAMManager) DeleteRole(ctx context.Context, roleName string) error {
|
||||
if !m.initialized {
|
||||
return fmt.Errorf("IAM manager not initialized")
|
||||
}
|
||||
if roleName == "" {
|
||||
return fmt.Errorf("role name cannot be empty")
|
||||
}
|
||||
return m.roleStore.DeleteRole(ctx, m.getFilerAddress(), roleName)
|
||||
}
|
||||
|
||||
// InvalidateRoleCache drops any cached role definitions, so a change written
|
||||
// to the store by a peer is seen on the next lookup rather than after the
|
||||
// cache TTL.
|
||||
func (m *IAMManager) InvalidateRoleCache() {
|
||||
if cached, ok := m.roleStore.(interface{ ClearCache() }); ok {
|
||||
cached.ClearCache()
|
||||
}
|
||||
}
|
||||
|
||||
// RoleStoreDirectory is the filer directory the role store keeps roles in,
|
||||
// its configured basePath; empty when the store is not filer-backed. S3
|
||||
// servers watch it to drop cached roles when a peer changes one.
|
||||
func (m *IAMManager) RoleStoreDirectory() string {
|
||||
store := m.roleStore
|
||||
if overlay, ok := store.(*staticRoleOverlay); ok {
|
||||
store = overlay.inner
|
||||
}
|
||||
if cached, ok := store.(*GenericCachedRoleStore); ok {
|
||||
store = cached.adapter.store
|
||||
}
|
||||
if filerStore, ok := store.(*FilerRoleStore); ok {
|
||||
return filerStore.basePath
|
||||
}
|
||||
return ""
|
||||
}
|
||||
|
||||
func (m *IAMManager) GetRole(ctx context.Context, roleName string) (*RoleDefinition, error) {
|
||||
if !m.initialized {
|
||||
return nil, fmt.Errorf("IAM manager not initialized")
|
||||
@@ -942,7 +1399,8 @@ func (m *IAMManager) AssumeRoleWithWebIdentity(ctx context.Context, request *sts
|
||||
// Apply role-level MaxSessionDuration cap. The STS service still applies
|
||||
// the global MaxSessionLength and the source-token-expiry cap on top of
|
||||
// this; per-role takes precedence whenever it is the tightest bound.
|
||||
request.DurationSeconds = capDurationByRole(request.DurationSeconds, roleDef.MaxSessionDuration)
|
||||
request.DurationSeconds = capDurationByRole(request.DurationSeconds, roleDef.MaxSessionDuration, m.defaultTokenDurationSeconds(), m.maxSessionLengthSeconds())
|
||||
request.RoleId = roleDef.RoleId
|
||||
|
||||
// Use STS service to assume the role
|
||||
return m.stsService.AssumeRoleWithWebIdentity(ctx, request)
|
||||
@@ -1005,22 +1463,54 @@ func extractIssuerFromJWT(token string) (string, error) {
|
||||
return iss, nil
|
||||
}
|
||||
|
||||
// capDurationByRole returns the requested duration clamped to the role's
|
||||
// MaxSessionDuration. A nil requested duration is left nil so the STS
|
||||
// service's calculateSessionDuration applies the global default (typically
|
||||
// 1 hour) — substituting the role's max here would silently mint a 12h
|
||||
// session for any caller who omitted DurationSeconds, which AWS does not
|
||||
// do. The role-max upper bound still applies in the downstream cap chain
|
||||
// once the request has a concrete duration.
|
||||
func capDurationByRole(requested *int64, roleMax int64) *int64 {
|
||||
if roleMax <= 0 || requested == nil {
|
||||
return requested
|
||||
// capDurationByRole returns the session duration clamped to the role's
|
||||
// MaxSessionDuration. An omitted DurationSeconds resolves to the configured
|
||||
// default first, so the role bound caps defaults and explicit values alike.
|
||||
// A nil request is only materialized when something tightened the default
|
||||
// and the explicit value still passes the service's own input validation —
|
||||
// everything else is left nil so the service resolves the default and its
|
||||
// MaxSessionLength cap itself.
|
||||
func capDurationByRole(requested *int64, roleMax, defaultSec, serviceMaxSec int64) *int64 {
|
||||
if requested != nil {
|
||||
d := *requested
|
||||
if roleMax > 0 && d > roleMax {
|
||||
d = roleMax
|
||||
}
|
||||
return &d
|
||||
}
|
||||
if *requested > roleMax {
|
||||
v := roleMax
|
||||
return &v
|
||||
d := defaultSec
|
||||
if roleMax > 0 && d > roleMax {
|
||||
d = roleMax
|
||||
}
|
||||
return requested
|
||||
if d > serviceMaxSec {
|
||||
d = serviceMaxSec
|
||||
}
|
||||
if d < 900 && roleMax > 0 {
|
||||
d = 900
|
||||
}
|
||||
if d >= defaultSec || d < 900 {
|
||||
return nil
|
||||
}
|
||||
return &d
|
||||
}
|
||||
|
||||
func (m *IAMManager) defaultTokenDurationSeconds() int64 {
|
||||
if m.stsService == nil || m.stsService.Config == nil {
|
||||
return sts.DefaultTokenDuration
|
||||
}
|
||||
return int64(m.stsService.Config.TokenDuration.Duration / time.Second)
|
||||
}
|
||||
|
||||
// maxSessionLengthSeconds mirrors validateSessionDurationSeconds so a
|
||||
// materialized default stays inside the bound the service will enforce.
|
||||
func (m *IAMManager) maxSessionLengthSeconds() int64 {
|
||||
maxSec := int64(sts.DefaultMaxSessionLength)
|
||||
if m.stsService != nil && m.stsService.Config != nil && m.stsService.Config.MaxSessionLength.Duration > 0 {
|
||||
if configured := int64(m.stsService.Config.MaxSessionLength.Duration / time.Second); configured >= 900 {
|
||||
maxSec = configured
|
||||
}
|
||||
}
|
||||
return maxSec
|
||||
}
|
||||
|
||||
// AssumeRoleWithCredentials assumes a role using credentials (LDAP)
|
||||
@@ -1044,9 +1534,10 @@ func (m *IAMManager) AssumeRoleWithCredentials(ctx context.Context, request *sts
|
||||
}
|
||||
|
||||
// Apply role-level MaxSessionDuration cap.
|
||||
request.DurationSeconds = capDurationByRole(request.DurationSeconds, roleDef.MaxSessionDuration)
|
||||
request.DurationSeconds = capDurationByRole(request.DurationSeconds, roleDef.MaxSessionDuration, m.defaultTokenDurationSeconds(), m.maxSessionLengthSeconds())
|
||||
|
||||
// Use STS service to assume the role
|
||||
request.RoleId = roleDef.RoleId
|
||||
return m.stsService.AssumeRoleWithCredentials(ctx, request)
|
||||
}
|
||||
|
||||
@@ -1060,6 +1551,10 @@ func (m *IAMManager) IsActionAllowed(ctx context.Context, request *ActionRequest
|
||||
// We always try to validate with the internal STS service first if it's a SeaweedFS token.
|
||||
// This ensures that session policies embedded in the token are correctly extracted and enforced.
|
||||
var sessionInfo *sts.SessionInfo
|
||||
// boundRole is the role a session carrying a role ID was checked against;
|
||||
// its policies are the ones evaluated, so the check and the evaluation
|
||||
// see one definition even if the role is replaced in between.
|
||||
var boundRole *RoleDefinition
|
||||
if request.SessionToken != "" {
|
||||
// Parse unverified to check issuer
|
||||
parsed, _, err := new(jwt.Parser).ParseUnverified(request.SessionToken, jwt.MapClaims{})
|
||||
@@ -1092,6 +1587,9 @@ func (m *IAMManager) IsActionAllowed(ctx context.Context, request *ActionRequest
|
||||
return false, fmt.Errorf("session has been revoked")
|
||||
}
|
||||
}
|
||||
if boundRole, err = m.checkSessionRoleBinding(ctx, sessionInfo); err != nil {
|
||||
return false, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1188,9 +1686,12 @@ func (m *IAMManager) IsActionAllowed(ctx context.Context, request *ActionRequest
|
||||
policies = user.GetPolicyNames()
|
||||
} else {
|
||||
// Get role definition
|
||||
roleDef, err := m.roleStore.GetRole(ctx, m.getFilerAddress(), roleName)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("role not found: %s", roleName)
|
||||
roleDef := boundRole
|
||||
if roleDef == nil || roleDef.RoleName != roleName {
|
||||
roleDef, err = m.roleStore.GetRole(ctx, m.getFilerAddress(), roleName)
|
||||
if err != nil {
|
||||
return false, fmt.Errorf("role not found: %s", roleName)
|
||||
}
|
||||
}
|
||||
|
||||
hasManagedSubject = true
|
||||
|
||||
@@ -2,16 +2,30 @@ package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/utils"
|
||||
)
|
||||
|
||||
// ErrTrustPolicyDenied is wrapped when a role's trust policy does not admit
|
||||
// the principal.
|
||||
var ErrTrustPolicyDenied = errors.New("trust policy denies access to principal")
|
||||
|
||||
// ValidateTrustPolicyForPrincipal validates if a principal is allowed to assume a role
|
||||
func (m *IAMManager) ValidateTrustPolicyForPrincipal(ctx context.Context, roleArn, principalArn string) error {
|
||||
_, err := m.ResolveRoleForPrincipal(ctx, roleArn, principalArn)
|
||||
return err
|
||||
}
|
||||
|
||||
// ResolveRoleForPrincipal returns the role roleArn names if its trust policy
|
||||
// admits principalArn. Issuing a session from the definition returned binds
|
||||
// the session to the role whose trust was evaluated, not to a role that
|
||||
// replaced it under the same name in between.
|
||||
func (m *IAMManager) ResolveRoleForPrincipal(ctx context.Context, roleArn, principalArn string) (*RoleDefinition, error) {
|
||||
if !m.initialized {
|
||||
return fmt.Errorf("IAM manager not initialized")
|
||||
return nil, fmt.Errorf("IAM manager not initialized")
|
||||
}
|
||||
|
||||
// Extract role name from ARN
|
||||
@@ -20,11 +34,11 @@ func (m *IAMManager) ValidateTrustPolicyForPrincipal(ctx context.Context, roleAr
|
||||
// Get role definition
|
||||
roleDef, err := m.roleStore.GetRole(ctx, m.getFilerAddress(), roleName)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to get role %s: %w", roleName, err)
|
||||
return nil, fmt.Errorf("failed to get role %s: %w", roleName, err)
|
||||
}
|
||||
|
||||
if roleDef.TrustPolicy == nil {
|
||||
return fmt.Errorf("role has no trust policy")
|
||||
return nil, fmt.Errorf("%w: role has no trust policy", ErrTrustPolicyDenied)
|
||||
}
|
||||
|
||||
// Create evaluation context with RequestContext populated so that
|
||||
@@ -43,8 +57,8 @@ func (m *IAMManager) ValidateTrustPolicyForPrincipal(ctx context.Context, roleAr
|
||||
|
||||
// Evaluate the trust policy
|
||||
if !m.evaluateTrustPolicy(roleDef.TrustPolicy, evalCtx) {
|
||||
return fmt.Errorf("trust policy denies access to principal: %s", principalArn)
|
||||
return nil, fmt.Errorf("%w: %s", ErrTrustPolicyDenied, principalArn)
|
||||
}
|
||||
|
||||
return nil
|
||||
return roleDef, nil
|
||||
}
|
||||
@@ -0,0 +1,561 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// persistentTestStore stands in for a store that outlives the process and may
|
||||
// be shared (the filer store): anything but *MemoryOIDCProviderStore is
|
||||
// treated as persistent.
|
||||
type persistentTestStore struct{ *MemoryOIDCProviderStore }
|
||||
|
||||
const (
|
||||
persistTestStaticIssuer = "https://static.example"
|
||||
persistTestAPIIssuer = "https://api.example"
|
||||
)
|
||||
|
||||
// persistTestConfig is an IAM config whose file defines the given OIDC
|
||||
// issuers.
|
||||
func persistTestConfig(issuers ...string) *IAMConfig {
|
||||
var providers []*sts.ProviderConfig
|
||||
for i, issuer := range issuers {
|
||||
providers = append(providers, &sts.ProviderConfig{
|
||||
Name: "static-" + string(rune('a'+i)),
|
||||
Type: sts.ProviderTypeOIDC,
|
||||
Enabled: true,
|
||||
Config: map[string]interface{}{"issuer": issuer, "clientId": "aud"},
|
||||
})
|
||||
}
|
||||
return &IAMConfig{
|
||||
STS: &sts.STSConfig{
|
||||
TokenDuration: sts.FlexibleDuration{Duration: time.Hour},
|
||||
MaxSessionLength: sts.FlexibleDuration{Duration: 12 * time.Hour},
|
||||
Issuer: "test-sts",
|
||||
SigningKey: []byte("test-signing-key-32-characters-long"),
|
||||
Providers: providers,
|
||||
},
|
||||
Policy: &policy.PolicyEngineConfig{DefaultEffect: "Deny", StoreType: "memory"},
|
||||
Roles: &RoleStoreConfig{StoreType: "memory"},
|
||||
}
|
||||
}
|
||||
|
||||
// startServer initializes a manager as an S3 server would at boot, with the
|
||||
// given config file providers and OIDC provider store.
|
||||
func startServer(t *testing.T, store OIDCProviderStore, issuers ...string) *IAMManager {
|
||||
t.Helper()
|
||||
cfg := persistTestConfig(issuers...)
|
||||
mgr := NewIAMManager()
|
||||
require.NoError(t, mgr.Initialize(cfg, func() string { return "localhost:8888" }))
|
||||
mgr.installOIDCProviderStore(store, cfg.STS)
|
||||
return mgr
|
||||
}
|
||||
|
||||
func arnOf(t *testing.T, issuer string) string {
|
||||
t.Helper()
|
||||
arn, err := DeriveOIDCProviderARN("", issuer)
|
||||
require.NoError(t, err)
|
||||
return arn
|
||||
}
|
||||
|
||||
func listedARNs(t *testing.T, mgr *IAMManager) map[string]bool {
|
||||
t.Helper()
|
||||
recs, err := mgr.ListOIDCProviders(context.Background())
|
||||
require.NoError(t, err)
|
||||
out := map[string]bool{}
|
||||
for _, r := range recs {
|
||||
out[r.ARN] = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func storedARNs(t *testing.T, store OIDCProviderStore) map[string]bool {
|
||||
t.Helper()
|
||||
recs, err := store.ListProviders(context.Background(), "")
|
||||
require.NoError(t, err)
|
||||
out := map[string]bool{}
|
||||
for _, r := range recs {
|
||||
out[r.ARN] = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func createAPIProvider(t *testing.T, mgr *IAMManager, issuer string) {
|
||||
t.Helper()
|
||||
require.NoError(t, mgr.CreateOIDCProvider(context.Background(), &OIDCProviderRecord{
|
||||
ARN: arnOf(t, issuer), URL: issuer, ClientIDs: []string{"aud"},
|
||||
}))
|
||||
}
|
||||
|
||||
// stsKnowsIssuer reports whether STS resolves a provider for the issuer. The
|
||||
// token is not validly signed; the only question is which error comes back.
|
||||
func stsKnowsIssuer(t *testing.T, mgr *IAMManager, issuer string) bool {
|
||||
t.Helper()
|
||||
tok, err := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
|
||||
"iss": issuer, "sub": "probe", "aud": "aud", "exp": time.Now().Add(time.Hour).Unix(),
|
||||
}).SignedString([]byte("not-the-providers-key"))
|
||||
require.NoError(t, err)
|
||||
_, _, err = mgr.GetSTSService().ValidateWebIdentityToken(context.Background(), tok)
|
||||
require.Error(t, err, "an unsigned-by-provider token for %s was accepted", issuer)
|
||||
return !strings.Contains(err.Error(), "no identity provider registered")
|
||||
}
|
||||
|
||||
// A persistent store never receives the config file's providers: it outlives
|
||||
// the file and may be shared with servers whose files differ.
|
||||
func TestPersistentStoreNeverHoldsConfigFileProviders(t *testing.T) {
|
||||
store := &persistentTestStore{NewMemoryOIDCProviderStore()}
|
||||
mgr := startServer(t, store, persistTestStaticIssuer)
|
||||
|
||||
assert.Empty(t, storedARNs(t, store), "a config-file provider was written to the persistent store")
|
||||
assert.True(t, listedARNs(t, mgr)[arnOf(t, persistTestStaticIssuer)], "the IAM API no longer lists the config-file provider")
|
||||
rec, err := mgr.GetOIDCProvider(context.Background(), arnOf(t, persistTestStaticIssuer))
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, persistTestStaticIssuer, rec.URL)
|
||||
assert.True(t, stsKnowsIssuer(t, mgr, persistTestStaticIssuer), "STS stopped trusting the config-file provider")
|
||||
}
|
||||
|
||||
// Servers sharing a store, with different config files, must not remove or
|
||||
// replace each other's providers — including a zero-config server.
|
||||
func TestServersSharingAStoreKeepEachOthersProviders(t *testing.T) {
|
||||
store := &persistentTestStore{NewMemoryOIDCProviderStore()}
|
||||
configured := startServer(t, store, persistTestStaticIssuer)
|
||||
createAPIProvider(t, configured, persistTestAPIIssuer)
|
||||
|
||||
zeroConfig := startServer(t, store)
|
||||
|
||||
assert.True(t, storedARNs(t, store)[arnOf(t, persistTestAPIIssuer)], "a peer's start removed an API-created provider")
|
||||
assert.True(t, listedARNs(t, configured)[arnOf(t, persistTestStaticIssuer)], "the configured server lost its config-file provider")
|
||||
assert.False(t, listedARNs(t, zeroConfig)[arnOf(t, persistTestStaticIssuer)], "a server lists a provider only its peer's config file defines")
|
||||
assert.True(t, stsKnowsIssuer(t, zeroConfig, persistTestAPIIssuer), "the peer does not trust the shared API-created provider")
|
||||
assert.False(t, stsKnowsIssuer(t, zeroConfig, persistTestStaticIssuer), "the peer trusts a provider only another server's config file defines")
|
||||
}
|
||||
|
||||
// Removing a provider from the config file revokes it at the next start.
|
||||
func TestRemovingAProviderFromTheConfigFileRevokesIt(t *testing.T) {
|
||||
store := &persistentTestStore{NewMemoryOIDCProviderStore()}
|
||||
startServer(t, store, persistTestStaticIssuer)
|
||||
|
||||
restarted := startServer(t, store) // the file no longer lists it
|
||||
|
||||
assert.False(t, listedARNs(t, restarted)[arnOf(t, persistTestStaticIssuer)])
|
||||
assert.False(t, stsKnowsIssuer(t, restarted, persistTestStaticIssuer), "a provider removed from the config file is still trusted")
|
||||
}
|
||||
|
||||
// The API cannot change a provider the config file defines, nor create one
|
||||
// with its ARN; the file is where it changes.
|
||||
func TestConfigFileProvidersCannotBeChangedThroughTheAPI(t *testing.T) {
|
||||
store := &persistentTestStore{NewMemoryOIDCProviderStore()}
|
||||
mgr := startServer(t, store, persistTestStaticIssuer)
|
||||
ctx := context.Background()
|
||||
arn := arnOf(t, persistTestStaticIssuer)
|
||||
|
||||
for name, err := range map[string]error{
|
||||
"add client ID": mgr.AddClientIDToOIDCProvider(ctx, arn, "other"),
|
||||
"remove client ID": mgr.RemoveClientIDFromOIDCProvider(ctx, arn, "aud"),
|
||||
"update thumbprint": mgr.UpdateOIDCProviderThumbprints(ctx, arn, []string{"9e99a48a9960b14926bb7f3b02e22da2b0ab7280"}),
|
||||
"tag": mgr.TagOIDCProvider(ctx, arn, map[string]string{"k": "v"}),
|
||||
"untag": mgr.UntagOIDCProvider(ctx, arn, []string{"k"}),
|
||||
"delete": mgr.DeleteOIDCProvider(ctx, arn),
|
||||
} {
|
||||
assert.ErrorIs(t, err, ErrOIDCProviderStatic, name)
|
||||
}
|
||||
err := mgr.CreateOIDCProvider(ctx, &OIDCProviderRecord{ARN: arn, URL: persistTestStaticIssuer, ClientIDs: []string{"aud"}})
|
||||
assert.ErrorIs(t, err, ErrOIDCProviderAlreadyExists)
|
||||
assert.Empty(t, storedARNs(t, store), "a refused change still wrote to the store")
|
||||
}
|
||||
|
||||
// Providers created through the API on an earlier boot, or on a peer, are
|
||||
// trusted at startup rather than after the next change.
|
||||
func TestStartupLoadsStoredProvidersIntoSTS(t *testing.T) {
|
||||
store := &persistentTestStore{NewMemoryOIDCProviderStore()}
|
||||
createAPIProvider(t, startServer(t, store), persistTestAPIIssuer)
|
||||
|
||||
restarted := startServer(t, store)
|
||||
assert.True(t, stsKnowsIssuer(t, restarted, persistTestAPIIssuer))
|
||||
}
|
||||
|
||||
// An in-memory store keeps its behaviour: the config file's providers are
|
||||
// records in it, as before.
|
||||
func TestInMemoryStoreStillHoldsConfigFileProviders(t *testing.T) {
|
||||
store := NewMemoryOIDCProviderStore()
|
||||
startServer(t, store, persistTestStaticIssuer)
|
||||
assert.True(t, storedARNs(t, store)[arnOf(t, persistTestStaticIssuer)])
|
||||
}
|
||||
|
||||
// unreachableThenReadyStore fails its first reads, as a filer that is not up
|
||||
// yet when the S3 server starts.
|
||||
type unreachableThenReadyStore struct {
|
||||
*MemoryOIDCProviderStore
|
||||
mu sync.Mutex
|
||||
failsLeft int
|
||||
}
|
||||
|
||||
func (s *unreachableThenReadyStore) ListProviders(ctx context.Context, addr string) ([]*OIDCProviderRecord, error) {
|
||||
s.mu.Lock()
|
||||
if s.failsLeft > 0 {
|
||||
s.failsLeft--
|
||||
s.mu.Unlock()
|
||||
return nil, errors.New("filer unavailable")
|
||||
}
|
||||
s.mu.Unlock()
|
||||
return s.MemoryOIDCProviderStore.ListProviders(ctx, addr)
|
||||
}
|
||||
|
||||
// A store that cannot be read at startup is retried: the metadata
|
||||
// subscription only reports later changes, so without a retry the providers
|
||||
// already stored would stay unknown to STS.
|
||||
func TestStartupLoadRetriesUntilTheStoreIsReadable(t *testing.T) {
|
||||
saved := oidcHydrateRetry
|
||||
oidcHydrateRetry.initial, oidcHydrateRetry.max = time.Millisecond, 5*time.Millisecond
|
||||
t.Cleanup(func() { oidcHydrateRetry = saved })
|
||||
|
||||
seeded := NewMemoryOIDCProviderStore()
|
||||
require.NoError(t, seeded.StoreProvider(context.Background(), "", &OIDCProviderRecord{
|
||||
ARN: arnOf(t, persistTestAPIIssuer), URL: persistTestAPIIssuer, ClientIDs: []string{"aud"},
|
||||
}))
|
||||
mgr := startServer(t, &unreachableThenReadyStore{MemoryOIDCProviderStore: seeded, failsLeft: 3})
|
||||
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for !stsKnowsIssuer(t, mgr, persistTestAPIIssuer) {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("STS never learned the stored provider after the store became readable")
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// A provider stored under a config-file provider's ARN takes precedence, as it
|
||||
// does in STS; the API then changes the stored one, and deleting it brings the
|
||||
// config-file provider back.
|
||||
func TestStoredProviderTakesPrecedenceOverTheConfigFileOne(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := &persistentTestStore{NewMemoryOIDCProviderStore()}
|
||||
configured := startServer(t, store, persistTestStaticIssuer)
|
||||
peer := startServer(t, store)
|
||||
arn := arnOf(t, persistTestStaticIssuer)
|
||||
require.NoError(t, peer.CreateOIDCProvider(ctx, &OIDCProviderRecord{ARN: arn, URL: persistTestStaticIssuer, ClientIDs: []string{"stored"}}))
|
||||
|
||||
rec, err := configured.GetOIDCProvider(ctx, arn)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"stored"}, rec.ClientIDs, "the config-file provider hides the stored one")
|
||||
assert.NoError(t, configured.AddClientIDToOIDCProvider(ctx, arn, "more"), "the stored provider cannot be changed")
|
||||
|
||||
require.NoError(t, configured.DeleteOIDCProvider(ctx, arn))
|
||||
rec, err = configured.GetOIDCProvider(ctx, arn)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, []string{"aud"}, rec.ClientIDs, "deleting the stored provider did not bring the config-file one back")
|
||||
}
|
||||
|
||||
// A store installed through SetOIDCProviderStore behaves like one installed
|
||||
// at startup: stored providers load into STS and config-file providers stay
|
||||
// visible to the IAM API.
|
||||
func TestSetOIDCProviderStoreInstallsLikeStartup(t *testing.T) {
|
||||
store := &persistentTestStore{NewMemoryOIDCProviderStore()}
|
||||
require.NoError(t, store.StoreProvider(context.Background(), "", &OIDCProviderRecord{
|
||||
ARN: arnOf(t, persistTestAPIIssuer), URL: persistTestAPIIssuer, ClientIDs: []string{"aud"},
|
||||
}))
|
||||
|
||||
cfg := persistTestConfig(persistTestStaticIssuer)
|
||||
mgr := NewIAMManager()
|
||||
require.NoError(t, mgr.Initialize(cfg, func() string { return "localhost:8888" }))
|
||||
mgr.SetOIDCProviderStore(store)
|
||||
|
||||
assert.True(t, stsKnowsIssuer(t, mgr, persistTestAPIIssuer), "a stored provider was not trusted after install")
|
||||
assert.True(t, listedARNs(t, mgr)[arnOf(t, persistTestStaticIssuer)], "the IAM API no longer lists the config-file provider")
|
||||
assert.ErrorIs(t, mgr.DeleteOIDCProvider(context.Background(), arnOf(t, persistTestStaticIssuer)), ErrOIDCProviderStatic)
|
||||
}
|
||||
|
||||
// A config-file provider reports no creation time: a time taken at startup
|
||||
// would change with every restart.
|
||||
func TestConfigFileProvidersReportNoCreationTime(t *testing.T) {
|
||||
store := &persistentTestStore{NewMemoryOIDCProviderStore()}
|
||||
mgr := startServer(t, store, persistTestStaticIssuer)
|
||||
rec, err := mgr.GetOIDCProvider(context.Background(), arnOf(t, persistTestStaticIssuer))
|
||||
require.NoError(t, err)
|
||||
assert.True(t, rec.CreatedAt.IsZero())
|
||||
}
|
||||
|
||||
// countingUnreadableStore never becomes readable and counts the attempts.
|
||||
type countingUnreadableStore struct {
|
||||
*MemoryOIDCProviderStore
|
||||
mu sync.Mutex
|
||||
reads int
|
||||
}
|
||||
|
||||
func (s *countingUnreadableStore) ListProviders(context.Context, string) ([]*OIDCProviderRecord, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.reads++
|
||||
return nil, errors.New("filer unavailable")
|
||||
}
|
||||
|
||||
func (s *countingUnreadableStore) readCount() int {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.reads
|
||||
}
|
||||
|
||||
// Installing another store stops the previous one's startup retry.
|
||||
func TestInstallingAnotherStoreStopsThePreviousRetry(t *testing.T) {
|
||||
saved := oidcHydrateRetry
|
||||
oidcHydrateRetry.initial, oidcHydrateRetry.max = time.Millisecond, time.Millisecond
|
||||
t.Cleanup(func() { oidcHydrateRetry = saved })
|
||||
|
||||
first := &countingUnreadableStore{MemoryOIDCProviderStore: NewMemoryOIDCProviderStore()}
|
||||
mgr := startServer(t, first)
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for first.readCount() <= 1 {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("precondition: the first store is never retried")
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
|
||||
mgr.installOIDCProviderStore(&persistentTestStore{NewMemoryOIDCProviderStore()}, persistTestConfig().STS)
|
||||
time.Sleep(10 * time.Millisecond) // let an in-flight attempt finish
|
||||
settled := first.readCount()
|
||||
time.Sleep(30 * time.Millisecond)
|
||||
assert.Equal(t, settled, first.readCount(), "the superseded store is still being retried")
|
||||
}
|
||||
|
||||
// blockingListStore blocks the first ListProviders call after arm, having
|
||||
// already read its snapshot, until release is closed.
|
||||
type blockingListStore struct {
|
||||
*MemoryOIDCProviderStore
|
||||
mu sync.Mutex
|
||||
armed bool
|
||||
entered chan struct{}
|
||||
release chan struct{}
|
||||
}
|
||||
|
||||
func (s *blockingListStore) arm() {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.armed, s.entered, s.release = true, make(chan struct{}), make(chan struct{})
|
||||
}
|
||||
|
||||
func (s *blockingListStore) ListProviders(ctx context.Context, addr string) ([]*OIDCProviderRecord, error) {
|
||||
records, err := s.MemoryOIDCProviderStore.ListProviders(ctx, addr)
|
||||
s.mu.Lock()
|
||||
block := s.armed
|
||||
s.armed = false
|
||||
s.mu.Unlock()
|
||||
if block {
|
||||
close(s.entered)
|
||||
<-s.release
|
||||
}
|
||||
return records, err
|
||||
}
|
||||
|
||||
// A refresh that read the store before a provider was deleted cannot leave the
|
||||
// deleted provider trusted by finishing after the deletion's own refresh.
|
||||
func TestAnOlderRefreshCannotRestoreADeletedProvider(t *testing.T) {
|
||||
store := &blockingListStore{MemoryOIDCProviderStore: NewMemoryOIDCProviderStore()}
|
||||
mgr := startServer(t, store)
|
||||
createAPIProvider(t, mgr, persistTestAPIIssuer)
|
||||
require.True(t, stsKnowsIssuer(t, mgr, persistTestAPIIssuer), "precondition: the provider is trusted")
|
||||
|
||||
store.arm()
|
||||
stale := make(chan struct{})
|
||||
go func() {
|
||||
defer close(stale)
|
||||
_ = mgr.RefreshOIDCProvidersFromStore(context.Background())
|
||||
}()
|
||||
<-store.entered // the stale refresh holds a snapshot with the provider
|
||||
|
||||
deleted := make(chan error, 1)
|
||||
go func() { deleted <- mgr.DeleteOIDCProvider(context.Background(), arnOf(t, persistTestAPIIssuer)) }()
|
||||
// Serialized, the deletion's refresh waits for the stale one; otherwise
|
||||
// let it finish first, which is the ordering that went wrong.
|
||||
var deleteErr error
|
||||
select {
|
||||
case deleteErr = <-deleted:
|
||||
deleted = nil
|
||||
case <-time.After(200 * time.Millisecond):
|
||||
}
|
||||
close(store.release)
|
||||
<-stale
|
||||
if deleted != nil {
|
||||
deleteErr = <-deleted
|
||||
}
|
||||
require.NoError(t, deleteErr)
|
||||
assert.False(t, stsKnowsIssuer(t, mgr, persistTestAPIIssuer), "a refresh older than the deletion left the deleted provider trusted")
|
||||
}
|
||||
|
||||
// A refresh that fails is retried until the store answers. A change event reports each mutation once, so
|
||||
// a subscription refresh that found the filer unreachable — mid-restart, say — left the provider set stale
|
||||
// until some unrelated later change; a peer's new provider stayed untrusted and a deleted one trusted.
|
||||
func TestAFailedRefreshIsRetriedUntilTheStoreAnswers(t *testing.T) {
|
||||
saved := oidcHydrateRetry
|
||||
oidcHydrateRetry.initial, oidcHydrateRetry.max = time.Millisecond, 5*time.Millisecond
|
||||
t.Cleanup(func() { oidcHydrateRetry = saved })
|
||||
|
||||
store := &unreachableThenReadyStore{MemoryOIDCProviderStore: NewMemoryOIDCProviderStore()}
|
||||
mgr := startServer(t, store)
|
||||
require.NoError(t, store.StoreProvider(context.Background(), "", &OIDCProviderRecord{
|
||||
ARN: arnOf(t, persistTestAPIIssuer), URL: persistTestAPIIssuer, ClientIDs: []string{"aud"},
|
||||
}))
|
||||
store.mu.Lock()
|
||||
store.failsLeft = 3
|
||||
store.mu.Unlock()
|
||||
require.Error(t, mgr.RefreshOIDCProvidersFromStore(context.Background()), "precondition: the refresh fails")
|
||||
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for !stsKnowsIssuer(t, mgr, persistTestAPIIssuer) {
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("a failed refresh was never retried: the stored provider stays untrusted until an unrelated change")
|
||||
}
|
||||
time.Sleep(5 * time.Millisecond)
|
||||
}
|
||||
}
|
||||
|
||||
// Failures during an outage start ONE retry, not one per event: a filer that is down for a while produces a
|
||||
// change event per mutation, and each would otherwise add a goroutine polling the same store. Once the store
|
||||
// answers and the retry ends, a later failure starts a new one.
|
||||
func TestFailedRefreshesShareOneRetry(t *testing.T) {
|
||||
saved := oidcHydrateRetry
|
||||
oidcHydrateRetry.initial, oidcHydrateRetry.max = time.Millisecond, time.Millisecond
|
||||
t.Cleanup(func() { oidcHydrateRetry = saved })
|
||||
|
||||
store := &unreachableThenReadyStore{MemoryOIDCProviderStore: NewMemoryOIDCProviderStore()}
|
||||
mgr := startServer(t, store)
|
||||
store.mu.Lock()
|
||||
store.failsLeft = 1 << 30
|
||||
store.mu.Unlock()
|
||||
for range 20 {
|
||||
require.Error(t, mgr.RefreshOIDCProvidersFromStore(context.Background()))
|
||||
}
|
||||
mgr.oidcRetryMu.Lock()
|
||||
started := mgr.oidcRetrySeq
|
||||
mgr.oidcRetryMu.Unlock()
|
||||
assert.Equal(t, uint64(1), started, "twenty failed refreshes started more than one retry")
|
||||
|
||||
store.mu.Lock()
|
||||
store.failsLeft = 0
|
||||
store.mu.Unlock()
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for {
|
||||
mgr.oidcRetryMu.Lock()
|
||||
running := mgr.oidcRetryGen != 0
|
||||
mgr.oidcRetryMu.Unlock()
|
||||
if !running {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("the retry never ended after the store answered")
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
store.mu.Lock()
|
||||
store.failsLeft = 1
|
||||
store.mu.Unlock()
|
||||
require.Error(t, mgr.RefreshOIDCProvidersFromStore(context.Background()))
|
||||
mgr.oidcRetryMu.Lock()
|
||||
assert.Equal(t, uint64(2), mgr.oidcRetrySeq, "a failure after the retry ended starts a new one")
|
||||
mgr.oidcRetryMu.Unlock()
|
||||
}
|
||||
|
||||
// flakyCountingStore fails while fail is set and counts the lists that succeed.
|
||||
type flakyCountingStore struct {
|
||||
*MemoryOIDCProviderStore
|
||||
mu sync.Mutex
|
||||
fail bool
|
||||
ok int
|
||||
}
|
||||
|
||||
func (s *flakyCountingStore) ListProviders(ctx context.Context, addr string) ([]*OIDCProviderRecord, error) {
|
||||
s.mu.Lock()
|
||||
if s.fail {
|
||||
s.mu.Unlock()
|
||||
return nil, errors.New("filer unavailable")
|
||||
}
|
||||
s.ok++
|
||||
s.mu.Unlock()
|
||||
return s.MemoryOIDCProviderStore.ListProviders(ctx, addr)
|
||||
}
|
||||
|
||||
func (s *flakyCountingStore) set(fail bool) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
s.fail = fail
|
||||
}
|
||||
|
||||
func (s *flakyCountingStore) successes() int {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
return s.ok
|
||||
}
|
||||
|
||||
// A refresh of store A that fails as store B is installed must not start a retry for A: nothing would cancel
|
||||
// it, and when A answered it would replace B's providers (a removed one trusted again, B's own untrusted).
|
||||
func TestAFailedRefreshOfASupersededStoreStartsNoRetry(t *testing.T) {
|
||||
a := &persistentTestStore{NewMemoryOIDCProviderStore()}
|
||||
mgr := startServer(t, a)
|
||||
mgr.SetOIDCProviderStore(&persistentTestStore{NewMemoryOIDCProviderStore()})
|
||||
mgr.oidcRetryMu.Lock()
|
||||
before := mgr.oidcRetrySeq
|
||||
mgr.oidcRetryMu.Unlock()
|
||||
|
||||
mgr.startOIDCRetry(a) // the late call of A's failed refresh, after B's install
|
||||
|
||||
mgr.oidcRetryMu.Lock()
|
||||
defer mgr.oidcRetryMu.Unlock()
|
||||
assert.Equal(t, before, mgr.oidcRetrySeq, "a retry was started for the store that was replaced")
|
||||
assert.Zero(t, mgr.oidcRetryGen)
|
||||
}
|
||||
|
||||
// A refresh that listed store A before B was installed must not hand STS A's providers afterwards.
|
||||
func TestASupersededSnapshotIsNotApplied(t *testing.T) {
|
||||
a := &persistentTestStore{NewMemoryOIDCProviderStore()}
|
||||
require.NoError(t, a.StoreProvider(context.Background(), "", &OIDCProviderRecord{
|
||||
ARN: arnOf(t, persistTestAPIIssuer), URL: persistTestAPIIssuer, ClientIDs: []string{"aud"},
|
||||
}))
|
||||
b := &persistentTestStore{NewMemoryOIDCProviderStore()}
|
||||
require.NoError(t, b.StoreProvider(context.Background(), "", &OIDCProviderRecord{
|
||||
ARN: arnOf(t, persistTestStaticIssuer), URL: persistTestStaticIssuer, ClientIDs: []string{"aud"},
|
||||
}))
|
||||
mgr := startServer(t, a)
|
||||
mgr.SetOIDCProviderStore(b)
|
||||
|
||||
assert.Error(t, mgr.refreshOIDCProvidersFrom(context.Background(), a), "a snapshot of the replaced store was applied")
|
||||
assert.False(t, stsKnowsIssuer(t, mgr, persistTestAPIIssuer), "the replaced store's provider is trusted")
|
||||
assert.True(t, stsKnowsIssuer(t, mgr, persistTestStaticIssuer), "the current store's provider is not")
|
||||
}
|
||||
|
||||
// A refresh that fails while a retry runs is not dropped: the retry may already have listed an older snapshot,
|
||||
// so after its success it runs once more and picks up whatever the failed refresh would have seen.
|
||||
func TestAFailureDuringARetryIsNotDropped(t *testing.T) {
|
||||
saved := oidcHydrateRetry
|
||||
oidcHydrateRetry.initial, oidcHydrateRetry.max = time.Millisecond, 2*time.Millisecond
|
||||
t.Cleanup(func() { oidcHydrateRetry = saved })
|
||||
|
||||
store := &flakyCountingStore{MemoryOIDCProviderStore: NewMemoryOIDCProviderStore(), fail: true}
|
||||
mgr := startServer(t, store) // the startup load fails: a retry is running
|
||||
require.Error(t, mgr.RefreshOIDCProvidersFromStore(context.Background()), "a later refresh fails while it runs")
|
||||
store.set(false)
|
||||
|
||||
deadline := time.Now().Add(2 * time.Second)
|
||||
for {
|
||||
mgr.oidcRetryMu.Lock()
|
||||
running := mgr.oidcRetryGen != 0
|
||||
mgr.oidcRetryMu.Unlock()
|
||||
if !running {
|
||||
break
|
||||
}
|
||||
if time.Now().After(deadline) {
|
||||
t.Fatal("the retry never ended")
|
||||
}
|
||||
time.Sleep(time.Millisecond)
|
||||
}
|
||||
assert.GreaterOrEqual(t, store.successes(), 2, "the retry ended on its first success, dropping the refresh that failed while it ran")
|
||||
}
|
||||
@@ -27,6 +27,9 @@ import (
|
||||
var (
|
||||
ErrOIDCProviderNotFound = errors.New("OIDC provider not found")
|
||||
ErrOIDCProviderAlreadyExists = errors.New("OIDC provider already exists")
|
||||
// ErrOIDCProviderStatic refuses a change to a provider defined in the
|
||||
// server's IAM config file: change it there instead.
|
||||
ErrOIDCProviderStatic = errors.New("OIDC provider is defined in the IAM config file")
|
||||
)
|
||||
|
||||
// OIDCProviderRecord is the persisted, IAM-managed view of an OIDC identity
|
||||
@@ -267,15 +270,20 @@ func (f *FilerOIDCProviderStore) GetProviderByARN(ctx context.Context, filerAddr
|
||||
|
||||
var data []byte
|
||||
err := f.withFilerClient(filerAddress, func(client filer_pb.SeaweedFilerClient) error {
|
||||
resp, err := client.LookupDirectoryEntry(ctx, &filer_pb.LookupDirectoryEntryRequest{
|
||||
resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: f.basePath,
|
||||
Name: f.fileName(arn),
|
||||
})
|
||||
// Only a confirmed absence is ErrOIDCProviderNotFound: callers create
|
||||
// on it, so an unreachable filer must not read as "no such provider".
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return fmt.Errorf("%w: %s", ErrOIDCProviderNotFound, arn)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("%w: %v", ErrOIDCProviderNotFound, err)
|
||||
return fmt.Errorf("lookup OIDC provider %s: %w", arn, err)
|
||||
}
|
||||
if resp.Entry == nil {
|
||||
return fmt.Errorf("OIDC provider not found: %s", arn)
|
||||
return fmt.Errorf("%w: %s", ErrOIDCProviderNotFound, arn)
|
||||
}
|
||||
data = resp.Entry.Content
|
||||
return nil
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// A session is bound to the role it was issued for, not to the role's name:
|
||||
// deleting the role ends it, and a role created later under the same name —
|
||||
// by whoever may create roles — must not inherit it.
|
||||
func TestSessionIsBoundToTheRoleNotItsName(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
m := setupIntegratedIAMSystem(t)
|
||||
|
||||
assume := func() (token, principal string) {
|
||||
resp, err := m.AssumeRoleWithWebIdentity(ctx, &sts.AssumeRoleWithWebIdentityRequest{
|
||||
RoleArn: "arn:aws:iam::role/S3ReadOnlyRole",
|
||||
WebIdentityToken: createTestJWT(t, "https://test-issuer.com", "test-user-123", "test-signing-key"),
|
||||
RoleSessionName: "binding-test",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
return resp.Credentials.SessionToken, resp.AssumedRoleUser.Arn
|
||||
}
|
||||
allowed := func(token, principal string) bool {
|
||||
ok, _ := m.IsActionAllowed(ctx, &ActionRequest{
|
||||
Principal: principal,
|
||||
Action: "s3:GetObject",
|
||||
Resource: "arn:aws:s3:::test-bucket/file.txt",
|
||||
SessionToken: token,
|
||||
})
|
||||
return ok
|
||||
}
|
||||
|
||||
original, err := m.GetRole(ctx, "S3ReadOnlyRole")
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, original.RoleId, "a created role has an ID")
|
||||
|
||||
token, principal := assume()
|
||||
require.True(t, allowed(token, principal), "precondition: the session works")
|
||||
|
||||
require.NoError(t, m.DeleteRole(ctx, "S3ReadOnlyRole"))
|
||||
assert.False(t, allowed(token, principal), "the session outlived its role's deletion")
|
||||
|
||||
recreated := *original
|
||||
recreated.RoleId = ""
|
||||
require.NoError(t, m.CreateRole(ctx, "", "S3ReadOnlyRole", &recreated))
|
||||
assert.NotEqual(t, original.RoleId, recreated.RoleId, "a role created again under the same name got the same ID")
|
||||
assert.False(t, allowed(token, principal), "a session of the deleted role works again under a new role of the same name")
|
||||
|
||||
fresh, freshPrincipal := assume()
|
||||
assert.True(t, allowed(fresh, freshPrincipal), "a session issued for the new role is refused")
|
||||
}
|
||||
|
||||
// A session carries its role's attached policies, and S3 evaluates those
|
||||
// rather than looking the role up; the binding must hold on that path too.
|
||||
func TestASessionCarryingItsPoliciesIsStillBoundToItsRole(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
m := setupIntegratedIAMSystem(t)
|
||||
|
||||
original, err := m.GetRole(ctx, "S3ReadOnlyRole")
|
||||
require.NoError(t, err)
|
||||
require.NotEmpty(t, original.AttachedPolicies, "precondition: the role attaches a policy")
|
||||
resp, err := m.AssumeRoleWithWebIdentity(ctx, &sts.AssumeRoleWithWebIdentityRequest{
|
||||
RoleArn: "arn:aws:iam::role/S3ReadOnlyRole",
|
||||
WebIdentityToken: createTestJWT(t, "https://test-issuer.com", "test-user-123", "test-signing-key"),
|
||||
RoleSessionName: "binding-test",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
allowed := func() bool {
|
||||
ok, _ := m.IsActionAllowed(ctx, &ActionRequest{
|
||||
Principal: resp.AssumedRoleUser.Arn,
|
||||
Action: "s3:GetObject",
|
||||
Resource: "arn:aws:s3:::test-bucket/file.txt",
|
||||
SessionToken: resp.Credentials.SessionToken,
|
||||
PolicyNames: original.AttachedPolicies,
|
||||
})
|
||||
return ok
|
||||
}
|
||||
require.True(t, allowed(), "precondition: the session works")
|
||||
|
||||
require.NoError(t, m.DeleteRole(ctx, "S3ReadOnlyRole"))
|
||||
assert.False(t, allowed(), "the session's embedded policies outlived its role's deletion")
|
||||
|
||||
recreated := *original
|
||||
recreated.RoleId = ""
|
||||
require.NoError(t, m.CreateRole(ctx, "", "S3ReadOnlyRole", &recreated))
|
||||
assert.False(t, allowed(), "the session's embedded policies work again under a new role of the same name")
|
||||
}
|
||||
|
||||
func TestStaticRoleIDIsStableAndRuntimeIDsAreUnique(t *testing.T) {
|
||||
trusting := func(principal string) *policy.PolicyDocument {
|
||||
return &policy.PolicyDocument{Version: "2012-10-17", Statement: []policy.Statement{{
|
||||
Effect: "Allow", Action: []string{"sts:AssumeRoleWithWebIdentity"},
|
||||
Principal: map[string]interface{}{"Federated": principal},
|
||||
}}}
|
||||
}
|
||||
app := &RoleDefinition{RoleName: "app", TrustPolicy: trusting("https://a.example")}
|
||||
restarted := &RoleDefinition{RoleName: "app", TrustPolicy: trusting("https://a.example")}
|
||||
replaced := &RoleDefinition{RoleName: "app", TrustPolicy: trusting("https://b.example")}
|
||||
|
||||
assert.Equal(t, StaticRoleID(app), StaticRoleID(restarted), "a config-file role must keep its ID across restarts")
|
||||
assert.NotEqual(t, StaticRoleID(app), StaticRoleID(replaced), "a different role under the same name inherits the old one's ID")
|
||||
assert.NotEqual(t, StaticRoleID(app), StaticRoleID(&RoleDefinition{RoleName: "other", TrustPolicy: trusting("https://a.example")}))
|
||||
assert.Regexp(t, `^AROA[A-Z0-9]{17}$`, StaticRoleID(app))
|
||||
assert.NotEqual(t, NewRoleID(), NewRoleID())
|
||||
assert.Regexp(t, `^AROA[A-Z2-7]{17}$`, NewRoleID())
|
||||
}
|
||||
|
||||
// replacedAfterFirstReadStore serves the stored role on its first read and a
|
||||
// replacement of the same name afterwards: a role replaced while a request
|
||||
// is being authorized.
|
||||
type replacedAfterFirstReadStore struct {
|
||||
RoleStore
|
||||
reads int
|
||||
replacement *RoleDefinition
|
||||
}
|
||||
|
||||
func (s *replacedAfterFirstReadStore) GetRole(ctx context.Context, addr, name string) (*RoleDefinition, error) {
|
||||
s.reads++
|
||||
if s.reads > 1 && name == s.replacement.RoleName {
|
||||
return copyRoleDefinition(s.replacement), nil
|
||||
}
|
||||
return s.RoleStore.GetRole(ctx, addr, name)
|
||||
}
|
||||
|
||||
// The session's binding is checked against one definition of its role, and
|
||||
// that definition's policies are the ones evaluated: a replacement read in
|
||||
// between must not lend the session its permissions.
|
||||
func TestAuthorizationEvaluatesTheRoleTheBindingCheckSaw(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
m := setupIntegratedIAMSystem(t)
|
||||
require.NoError(t, m.CreatePolicy(ctx, "", "S3WritePolicy", &policy.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy.Statement{{
|
||||
Effect: "Allow", Action: []string{"s3:PutObject"},
|
||||
Resource: []string{"arn:aws:s3:::test-bucket/*"},
|
||||
}},
|
||||
}))
|
||||
resp, err := m.AssumeRoleWithWebIdentity(ctx, &sts.AssumeRoleWithWebIdentityRequest{
|
||||
RoleArn: "arn:aws:iam::role/S3ReadOnlyRole",
|
||||
WebIdentityToken: createTestJWT(t, "https://test-issuer.com", "test-user-123", "test-signing-key"),
|
||||
RoleSessionName: "snapshot-test",
|
||||
})
|
||||
require.NoError(t, err)
|
||||
|
||||
original, err := m.GetRole(ctx, "S3ReadOnlyRole")
|
||||
require.NoError(t, err)
|
||||
replacement := *original
|
||||
replacement.RoleId = NewRoleID()
|
||||
replacement.AttachedPolicies = []string{"S3WritePolicy"}
|
||||
m.roleStore = &replacedAfterFirstReadStore{RoleStore: m.roleStore, replacement: &replacement}
|
||||
|
||||
allowed, _ := m.IsActionAllowed(ctx, &ActionRequest{
|
||||
Principal: resp.AssumedRoleUser.Arn,
|
||||
Action: "s3:PutObject",
|
||||
Resource: "arn:aws:s3:::test-bucket/file.txt",
|
||||
SessionToken: resp.Credentials.SessionToken,
|
||||
})
|
||||
assert.False(t, allowed, "the session was authorized by the replacement role's policies")
|
||||
}
|
||||
@@ -6,21 +6,27 @@ func intPtr(v int64) *int64 { return &v }
|
||||
|
||||
func TestCapDurationByRole(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
requested *int64
|
||||
roleMax int64
|
||||
want *int64
|
||||
name string
|
||||
requested *int64
|
||||
roleMax int64
|
||||
defaultSec int64
|
||||
serviceMaxSec int64
|
||||
want *int64
|
||||
}{
|
||||
{"no cap, no request", nil, 0, nil},
|
||||
{"no cap, with request", intPtr(7200), 0, intPtr(7200)},
|
||||
{"cap only, no request -> nil so STS default applies", nil, 3600, nil},
|
||||
{"request below cap -> request", intPtr(1800), 3600, intPtr(1800)},
|
||||
{"request equal cap -> request", intPtr(3600), 3600, intPtr(3600)},
|
||||
{"request above cap -> cap", intPtr(43200), 3600, intPtr(3600)},
|
||||
{"no cap, no request -> nil keeps service default", nil, 0, 3600, 43200, nil},
|
||||
{"no cap, with request", intPtr(7200), 0, 3600, 43200, intPtr(7200)},
|
||||
{"cap below default, no request -> cap", nil, 1800, 3600, 43200, intPtr(1800)},
|
||||
{"cap above default, no request -> nil", nil, 43200, 3600, 43200, nil},
|
||||
{"request below cap -> request", intPtr(1800), 3600, 900, 43200, intPtr(1800)},
|
||||
{"request equal cap -> request", intPtr(3600), 3600, 900, 43200, intPtr(3600)},
|
||||
{"request above cap -> cap", intPtr(43200), 3600, 900, 43200, intPtr(3600)},
|
||||
{"default above service max -> service cap materialized", nil, 0, 7200, 3600, intPtr(3600)},
|
||||
{"role bound above service max -> service cap still applies", nil, 40000, 43200, 3600, intPtr(3600)},
|
||||
{"role bound below service floor -> tightest issuable", nil, 500, 3600, 43200, intPtr(900)},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := capDurationByRole(tc.requested, tc.roleMax)
|
||||
got := capDurationByRole(tc.requested, tc.roleMax, tc.defaultSec, tc.serviceMaxSec)
|
||||
switch {
|
||||
case got == nil && tc.want == nil:
|
||||
return
|
||||
|
||||
@@ -3,7 +3,10 @@ package integration
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"regexp"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
@@ -13,9 +16,38 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
)
|
||||
|
||||
// ErrRoleNotFound is wrapped by every RoleStore's GetRole when the role does
|
||||
// not exist, so callers can tell a missing role from a store that could not
|
||||
// be read.
|
||||
var ErrRoleNotFound = errors.New("role not found")
|
||||
|
||||
// ErrRoleStatic refuses a change to a role defined in the server's IAM config
|
||||
// file: change it there instead.
|
||||
var ErrRoleStatic = errors.New("role is defined in the IAM config file")
|
||||
|
||||
// ErrRoleExists is returned by an UpdateRole whose update refuses a role that
|
||||
// already exists (CreateRole).
|
||||
var ErrRoleExists = errors.New("role already exists")
|
||||
|
||||
// RoleUpdate computes a role's new definition from its current one, nil when
|
||||
// the role does not exist. It returns nil to delete the role, and an error to
|
||||
// leave it unchanged. It may run more than once: it is called again with the
|
||||
// fresh definition when another writer changed the role in between.
|
||||
type RoleUpdate func(current *RoleDefinition) (*RoleDefinition, error)
|
||||
|
||||
// maxRoleUpdateAttempts bounds UpdateRole's retries under contention.
|
||||
const maxRoleUpdateAttempts = 10
|
||||
|
||||
// errRoleUpdateContended is returned when the role kept changing under
|
||||
// UpdateRole for maxRoleUpdateAttempts reads.
|
||||
var errRoleUpdateContended = errors.New("role changed concurrently; retry")
|
||||
|
||||
// RoleStore defines the interface for storing IAM role definitions
|
||||
type RoleStore interface {
|
||||
// StoreRole stores a role definition (filerAddress ignored for memory stores)
|
||||
@@ -29,6 +61,14 @@ type RoleStore interface {
|
||||
|
||||
// DeleteRole deletes a role definition (filerAddress ignored for memory stores)
|
||||
DeleteRole(ctx context.Context, filerAddress string, roleName string) error
|
||||
|
||||
// UpdateRole replaces a role with update's result, atomically: the write
|
||||
// lands only if the role is still as update saw it, absent included, and
|
||||
// update is retried against the current role otherwise. Every change the
|
||||
// IAM API and the filer IAM service make to a role goes through it, so
|
||||
// writers on different servers neither lose each other's changes nor bring
|
||||
// back a role deleted in between.
|
||||
UpdateRole(ctx context.Context, filerAddress string, roleName string, update RoleUpdate) error
|
||||
}
|
||||
|
||||
// MemoryRoleStore implements RoleStore using in-memory storage
|
||||
@@ -72,7 +112,7 @@ func (m *MemoryRoleStore) GetRole(ctx context.Context, filerAddress string, role
|
||||
|
||||
role, exists := m.roles[roleName]
|
||||
if !exists {
|
||||
return nil, fmt.Errorf("role not found: %s", roleName)
|
||||
return nil, fmt.Errorf("%w: %s", ErrRoleNotFound, roleName)
|
||||
}
|
||||
|
||||
// Return a copy to prevent external modifications
|
||||
@@ -105,6 +145,26 @@ func (m *MemoryRoleStore) DeleteRole(ctx context.Context, filerAddress string, r
|
||||
return nil
|
||||
}
|
||||
|
||||
// UpdateRole applies update under the store's lock (filerAddress ignored for
|
||||
// memory store).
|
||||
func (m *MemoryRoleStore) UpdateRole(ctx context.Context, filerAddress string, roleName string, update RoleUpdate) error {
|
||||
if roleName == "" {
|
||||
return fmt.Errorf("role name cannot be empty")
|
||||
}
|
||||
m.mutex.Lock()
|
||||
defer m.mutex.Unlock()
|
||||
next, err := update(copyRoleDefinition(m.roles[roleName]))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if next == nil {
|
||||
delete(m.roles, roleName)
|
||||
return nil
|
||||
}
|
||||
m.roles[roleName] = copyRoleDefinition(next)
|
||||
return nil
|
||||
}
|
||||
|
||||
// copyRoleDefinition creates a deep copy of a role definition
|
||||
func copyRoleDefinition(original *RoleDefinition) *RoleDefinition {
|
||||
if original == nil {
|
||||
@@ -112,9 +172,13 @@ func copyRoleDefinition(original *RoleDefinition) *RoleDefinition {
|
||||
}
|
||||
|
||||
copied := &RoleDefinition{
|
||||
RoleName: original.RoleName,
|
||||
RoleArn: original.RoleArn,
|
||||
Description: original.Description,
|
||||
RoleName: original.RoleName,
|
||||
RoleArn: original.RoleArn,
|
||||
Description: original.Description,
|
||||
MaxSessionDuration: original.MaxSessionDuration,
|
||||
Source: original.Source,
|
||||
CreatedAt: original.CreatedAt,
|
||||
RoleId: original.RoleId,
|
||||
}
|
||||
|
||||
// Deep copy trust policy if it exists
|
||||
@@ -135,6 +199,10 @@ func copyRoleDefinition(original *RoleDefinition) *RoleDefinition {
|
||||
return copied
|
||||
}
|
||||
|
||||
// roleListPageSize is the number of entries FilerRoleStore.ListRoles asks the
|
||||
// filer for per page.
|
||||
const roleListPageSize = 1000
|
||||
|
||||
// FilerRoleStore implements RoleStore using SeaweedFS filer
|
||||
type FilerRoleStore struct {
|
||||
grpcDialOption grpc.DialOption
|
||||
@@ -213,6 +281,139 @@ func (f *FilerRoleStore) StoreRole(ctx context.Context, filerAddress string, rol
|
||||
})
|
||||
}
|
||||
|
||||
// UpdateRole reads the role's entry, applies update, and writes the result on
|
||||
// the condition that the entry is unchanged since the read — absent, when the
|
||||
// role did not exist — so the filer refuses a write racing another writer's
|
||||
// change or delete, and update is applied again to what that writer left. A
|
||||
// delete is made on the same condition, so it removes the role update saw and
|
||||
// not one written after it.
|
||||
func (f *FilerRoleStore) UpdateRole(ctx context.Context, filerAddress string, roleName string, update RoleUpdate) error {
|
||||
if filerAddress == "" && f.filerAddressProvider != nil {
|
||||
filerAddress = f.filerAddressProvider()
|
||||
}
|
||||
if filerAddress == "" {
|
||||
return fmt.Errorf("filer address is required for FilerRoleStore")
|
||||
}
|
||||
if roleName == "" {
|
||||
return fmt.Errorf("role name cannot be empty")
|
||||
}
|
||||
return f.withFilerClient(filerAddress, func(client filer_pb.SeaweedFilerClient) error {
|
||||
for attempt := 0; attempt < maxRoleUpdateAttempts; attempt++ {
|
||||
var entry *filer_pb.Entry
|
||||
var current *RoleDefinition
|
||||
resp, err := filer_pb.LookupEntry(ctx, client, &filer_pb.LookupDirectoryEntryRequest{
|
||||
Directory: f.basePath,
|
||||
Name: f.getRoleFileName(roleName),
|
||||
})
|
||||
switch {
|
||||
case errors.Is(err, filer_pb.ErrNotFound):
|
||||
case err != nil:
|
||||
return fmt.Errorf("lookup role %s: %w", roleName, err)
|
||||
case resp.Entry != nil:
|
||||
entry = resp.Entry
|
||||
current = &RoleDefinition{}
|
||||
if err := json.Unmarshal(entry.Content, current); err != nil {
|
||||
return fmt.Errorf("failed to deserialize role %s: %v", roleName, err)
|
||||
}
|
||||
}
|
||||
|
||||
next, err := update(current)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if next == nil {
|
||||
if entry == nil {
|
||||
return nil
|
||||
}
|
||||
deleted, err := f.deleteRoleEntryIfUnchanged(ctx, client, entry)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to delete role %s: %w", roleName, err)
|
||||
}
|
||||
if !deleted {
|
||||
glog.V(3).Infof("Role %s changed before its delete; retrying", roleName)
|
||||
continue
|
||||
}
|
||||
return nil
|
||||
}
|
||||
roleData, err := json.MarshalIndent(next, "", " ")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to serialize role: %v", err)
|
||||
}
|
||||
|
||||
clause := &filer_pb.WriteCondition_Clause{Kind: filer_pb.WriteCondition_IF_NOT_EXISTS}
|
||||
if entry != nil {
|
||||
clause = &filer_pb.WriteCondition_Clause{Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL, ExpectedEntry: entry}
|
||||
}
|
||||
now := time.Now().Unix()
|
||||
created, err := client.CreateEntry(ctx, &filer_pb.CreateEntryRequest{
|
||||
Directory: f.basePath,
|
||||
Entry: &filer_pb.Entry{
|
||||
Name: f.getRoleFileName(roleName),
|
||||
Attributes: &filer_pb.FuseAttributes{
|
||||
Mtime: now,
|
||||
Crtime: now,
|
||||
FileMode: uint32(0600),
|
||||
},
|
||||
Content: roleData,
|
||||
},
|
||||
Condition: &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{clause}},
|
||||
})
|
||||
if isRoleWriteConflict(created, err) {
|
||||
glog.V(3).Infof("Role %s changed during update; retrying", roleName)
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to store role %s: %v", roleName, err)
|
||||
}
|
||||
if created.Error != "" {
|
||||
return fmt.Errorf("failed to store role %s: %s", roleName, created.Error)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
return fmt.Errorf("update role %s: %w", roleName, errRoleUpdateContended)
|
||||
})
|
||||
}
|
||||
|
||||
// deleteRoleEntryIfUnchanged deletes the role's entry if it still equals
|
||||
// entry, reporting false when it changed. The delete is routed and locked as
|
||||
// the conditional CreateEntry of the same path is, so the two serialize.
|
||||
func (f *FilerRoleStore) deleteRoleEntryIfUnchanged(ctx context.Context, client filer_pb.SeaweedFilerClient, entry *filer_pb.Entry) (bool, error) {
|
||||
fullPath := f.basePath + "/" + entry.Name
|
||||
resp, err := client.ObjectTransaction(ctx, &filer_pb.ObjectTransactionRequest{
|
||||
LockKey: fullPath,
|
||||
RouteKey: s3_constants.ObjectWriteRouteKeyPrefix + fullPath,
|
||||
Condition: &filer_pb.WriteCondition{Clauses: []*filer_pb.WriteCondition_Clause{{
|
||||
Kind: filer_pb.WriteCondition_IF_ENTRY_EQUAL, ExpectedEntry: entry,
|
||||
}}},
|
||||
Mutations: []*filer_pb.ObjectMutation{{
|
||||
Type: filer_pb.ObjectMutation_DELETE, Directory: f.basePath, Name: entry.Name, IsDeleteData: true,
|
||||
}},
|
||||
})
|
||||
if err != nil {
|
||||
if status.Code(err) == codes.FailedPrecondition {
|
||||
return false, nil
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
if resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED {
|
||||
return false, nil
|
||||
}
|
||||
if resp.Error != "" {
|
||||
return false, errors.New(resp.Error)
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
|
||||
// isRoleWriteConflict reports a write the filer refused because its condition
|
||||
// no longer held: in the response, or as FailedPrecondition when the write
|
||||
// was forwarded to the entry's owner filer.
|
||||
func isRoleWriteConflict(resp *filer_pb.CreateEntryResponse, err error) bool {
|
||||
if err != nil {
|
||||
return status.Code(err) == codes.FailedPrecondition
|
||||
}
|
||||
return resp != nil && resp.ErrorCode == filer_pb.FilerError_PRECONDITION_FAILED
|
||||
}
|
||||
|
||||
// GetRole retrieves a role definition from filer
|
||||
func (f *FilerRoleStore) GetRole(ctx context.Context, filerAddress string, roleName string) (*RoleDefinition, error) {
|
||||
// Use provider function if filerAddress is not provided
|
||||
@@ -234,13 +435,16 @@ func (f *FilerRoleStore) GetRole(ctx context.Context, filerAddress string, roleN
|
||||
}
|
||||
|
||||
glog.V(3).Infof("Looking up role %s", roleName)
|
||||
response, err := client.LookupDirectoryEntry(ctx, request)
|
||||
response, err := filer_pb.LookupEntry(ctx, client, request)
|
||||
if errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return fmt.Errorf("%w: %s", ErrRoleNotFound, roleName)
|
||||
}
|
||||
if err != nil {
|
||||
return fmt.Errorf("role not found: %v", err)
|
||||
return fmt.Errorf("lookup role %s: %w", roleName, err)
|
||||
}
|
||||
|
||||
if response.Entry == nil {
|
||||
return fmt.Errorf("role not found")
|
||||
return fmt.Errorf("%w: %s", ErrRoleNotFound, roleName)
|
||||
}
|
||||
|
||||
roleData = response.Entry.Content
|
||||
@@ -270,46 +474,50 @@ func (f *FilerRoleStore) ListRoles(ctx context.Context, filerAddress string) ([]
|
||||
return nil, fmt.Errorf("filer address is required for FilerRoleStore")
|
||||
}
|
||||
|
||||
// Page through the directory, and fail on a broken stream rather than
|
||||
// return what arrived: a truncated list would let DeletePolicy miss a role
|
||||
// that still attaches the policy (RolesAttachingPolicy).
|
||||
var roleNames []string
|
||||
|
||||
err := f.withFilerClient(filerAddress, func(client filer_pb.SeaweedFilerClient) error {
|
||||
request := &filer_pb.ListEntriesRequest{
|
||||
Directory: f.basePath,
|
||||
Prefix: "",
|
||||
StartFromFileName: "",
|
||||
InclusiveStartFrom: false,
|
||||
Limit: 1000, // Process in batches of 1000
|
||||
}
|
||||
|
||||
glog.V(3).Infof("Listing roles in %s", f.basePath)
|
||||
stream, err := client.ListEntries(ctx, request)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to list roles: %v", err)
|
||||
}
|
||||
|
||||
startFrom := ""
|
||||
for {
|
||||
resp, err := stream.Recv()
|
||||
stream, err := client.ListEntries(ctx, &filer_pb.ListEntriesRequest{
|
||||
Directory: f.basePath,
|
||||
StartFromFileName: startFrom,
|
||||
Limit: roleListPageSize,
|
||||
})
|
||||
if err != nil {
|
||||
break // End of stream or error
|
||||
return err
|
||||
}
|
||||
|
||||
if resp.Entry == nil || resp.Entry.IsDirectory {
|
||||
continue
|
||||
received := 0
|
||||
for {
|
||||
resp, err := stream.Recv()
|
||||
if errors.Is(err, io.EOF) {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if resp.Entry == nil {
|
||||
continue
|
||||
}
|
||||
received++
|
||||
startFrom = resp.Entry.Name
|
||||
if resp.Entry.IsDirectory {
|
||||
continue
|
||||
}
|
||||
if name, ok := strings.CutSuffix(resp.Entry.Name, ".json"); ok {
|
||||
roleNames = append(roleNames, name)
|
||||
}
|
||||
}
|
||||
|
||||
// Extract role name from filename
|
||||
filename := resp.Entry.Name
|
||||
if strings.HasSuffix(filename, ".json") {
|
||||
roleName := strings.TrimSuffix(filename, ".json")
|
||||
roleNames = append(roleNames, roleName)
|
||||
if received < roleListPageSize {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("failed to list roles: %w", err)
|
||||
}
|
||||
|
||||
return roleNames, nil
|
||||
@@ -388,3 +596,146 @@ type CachedFilerRoleStoreConfig struct {
|
||||
ListTTL string `json:"listTtl,omitempty"` // e.g., "1m", "30s"
|
||||
MaxCacheSize int `json:"maxCacheSize,omitempty"` // Maximum number of cached roles
|
||||
}
|
||||
|
||||
// RolesAttachingPolicy returns the names of the roles that attach the policy.
|
||||
// A policy is attached to a role by name, so deleting it while attached would
|
||||
// let a policy created later under the same name take effect on the role;
|
||||
// callers refuse the delete instead, as AWS does (DeleteConflict).
|
||||
//
|
||||
// It sees the stored roles, which every server sharing the store sees, and
|
||||
// this server's config-file roles. A role defined only in another server's
|
||||
// config file is invisible here: servers sharing a role store may have
|
||||
// different config files, but a config-file role that attaches a managed
|
||||
// (API-created) policy is protected only on the servers whose file defines it.
|
||||
// Keep such roles in every server's file, or attach only config-file policies
|
||||
// to config-file roles.
|
||||
func RolesAttachingPolicy(ctx context.Context, store RoleStore, policyName string) ([]string, error) {
|
||||
names, err := store.ListRoles(ctx, "")
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("list roles: %w", err)
|
||||
}
|
||||
var attaching []string
|
||||
for _, name := range names {
|
||||
role, err := store.GetRole(ctx, "", name)
|
||||
if errors.Is(err, ErrRoleNotFound) {
|
||||
continue // deleted between list and read
|
||||
}
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("get role %s: %w", name, err)
|
||||
}
|
||||
for _, attached := range role.AttachedPolicies {
|
||||
if attached == policyName {
|
||||
attaching = append(attaching, name)
|
||||
break
|
||||
}
|
||||
}
|
||||
}
|
||||
return attaching, nil
|
||||
}
|
||||
|
||||
// MaxManagedPoliciesPerRole caps the managed policies attached to one role,
|
||||
// as AWS's default quota does (and as MaxManagedPoliciesPerUser does for users).
|
||||
const MaxManagedPoliciesPerRole = 10
|
||||
|
||||
var roleNamePattern = regexp.MustCompile(`^[\w+=,.@-]{1,64}$`)
|
||||
|
||||
// ValidateRoleName checks a role name against AWS's rules. A role is stored as
|
||||
// <name>.json in the filer, so the rules also keep a name from leaving the
|
||||
// role store's directory.
|
||||
func ValidateRoleName(name string) error {
|
||||
if !roleNamePattern.MatchString(name) {
|
||||
return fmt.Errorf("invalid role name %q: must be 1-64 characters of letters, digits and +=,.@_-", name)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// staticRoleOverlay serves the IAM config file's roles from memory beside a
|
||||
// persistent store, which never holds them (see IAMManager.LoadStaticRoles).
|
||||
// A role stored under the same name takes precedence, as a stored OIDC
|
||||
// provider does over a config-file one; deleting it brings the config-file
|
||||
// role back. A config-file role itself cannot be stored over or deleted.
|
||||
type staticRoleOverlay struct {
|
||||
static map[string]*RoleDefinition
|
||||
inner RoleStore
|
||||
}
|
||||
|
||||
// storedRoleExists reports whether the store itself holds the role.
|
||||
func (o *staticRoleOverlay) storedRoleExists(ctx context.Context, filerAddress, roleName string) (bool, error) {
|
||||
_, err := o.inner.GetRole(ctx, filerAddress, roleName)
|
||||
if errors.Is(err, ErrRoleNotFound) {
|
||||
return false, nil
|
||||
}
|
||||
return err == nil, err
|
||||
}
|
||||
|
||||
func (o *staticRoleOverlay) StoreRole(ctx context.Context, filerAddress string, roleName string, role *RoleDefinition) error {
|
||||
if _, ok := o.static[roleName]; ok {
|
||||
stored, err := o.storedRoleExists(ctx, filerAddress, roleName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !stored {
|
||||
return fmt.Errorf("%w: %s", ErrRoleStatic, roleName)
|
||||
}
|
||||
}
|
||||
return o.inner.StoreRole(ctx, filerAddress, roleName, role)
|
||||
}
|
||||
|
||||
// UpdateRole refuses to create a stored role over a config-file role, as
|
||||
// StoreRole does; a stored role of that name may be changed.
|
||||
func (o *staticRoleOverlay) UpdateRole(ctx context.Context, filerAddress string, roleName string, update RoleUpdate) error {
|
||||
_, static := o.static[roleName]
|
||||
return o.inner.UpdateRole(ctx, filerAddress, roleName, func(current *RoleDefinition) (*RoleDefinition, error) {
|
||||
if current == nil && static {
|
||||
return nil, fmt.Errorf("%w: %s", ErrRoleStatic, roleName)
|
||||
}
|
||||
return update(current)
|
||||
})
|
||||
}
|
||||
|
||||
func (o *staticRoleOverlay) GetRole(ctx context.Context, filerAddress string, roleName string) (*RoleDefinition, error) {
|
||||
role, err := o.inner.GetRole(ctx, filerAddress, roleName)
|
||||
if errors.Is(err, ErrRoleNotFound) {
|
||||
if static, ok := o.static[roleName]; ok {
|
||||
return copyRoleDefinition(static), nil
|
||||
}
|
||||
}
|
||||
return role, err
|
||||
}
|
||||
|
||||
func (o *staticRoleOverlay) ListRoles(ctx context.Context, filerAddress string) ([]string, error) {
|
||||
names, err := o.inner.ListRoles(ctx, filerAddress)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
seen := make(map[string]bool, len(names))
|
||||
for _, name := range names {
|
||||
seen[name] = true
|
||||
}
|
||||
for name := range o.static {
|
||||
if !seen[name] {
|
||||
names = append(names, name)
|
||||
}
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func (o *staticRoleOverlay) DeleteRole(ctx context.Context, filerAddress string, roleName string) error {
|
||||
if _, ok := o.static[roleName]; ok {
|
||||
stored, err := o.storedRoleExists(ctx, filerAddress, roleName)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if !stored {
|
||||
return fmt.Errorf("%w: %s", ErrRoleStatic, roleName)
|
||||
}
|
||||
}
|
||||
return o.inner.DeleteRole(ctx, filerAddress, roleName)
|
||||
}
|
||||
|
||||
// ClearCache forwards cache invalidation to the store underneath.
|
||||
func (o *staticRoleOverlay) ClearCache() {
|
||||
if cached, ok := o.inner.(interface{ ClearCache() }); ok {
|
||||
cached.ClearCache()
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,286 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net"
|
||||
"slices"
|
||||
"sort"
|
||||
"strconv"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/credentials/insecure"
|
||||
"google.golang.org/grpc/status"
|
||||
"google.golang.org/protobuf/proto"
|
||||
)
|
||||
|
||||
// roleStoreTestFiler is a filer holding one directory. It evaluates the write
|
||||
// conditions FilerRoleStore sends as the filer does, and can run another
|
||||
// writer between a role's read and its write (afterLookup) or break a listing
|
||||
// stream partway (failListAfter).
|
||||
type roleStoreTestFiler struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
mu sync.Mutex
|
||||
entries map[string]*filer_pb.Entry
|
||||
afterLookup func()
|
||||
failListAfter int
|
||||
}
|
||||
|
||||
func (s *roleStoreTestFiler) LookupDirectoryEntry(_ context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
|
||||
s.mu.Lock()
|
||||
entry, found := s.entries[req.Name]
|
||||
hook := s.afterLookup
|
||||
s.afterLookup = nil
|
||||
s.mu.Unlock()
|
||||
if hook != nil {
|
||||
defer hook()
|
||||
}
|
||||
if !found {
|
||||
return nil, status.Error(codes.NotFound, filer_pb.ErrNotFound.Error())
|
||||
}
|
||||
return &filer_pb.LookupDirectoryEntryResponse{Entry: proto.Clone(entry).(*filer_pb.Entry)}, nil
|
||||
}
|
||||
|
||||
func (s *roleStoreTestFiler) CreateEntry(_ context.Context, req *filer_pb.CreateEntryRequest) (*filer_pb.CreateEntryResponse, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
current, exists := s.entries[req.Entry.Name]
|
||||
for _, c := range req.GetCondition().GetClauses() {
|
||||
var ok bool
|
||||
switch c.Kind {
|
||||
case filer_pb.WriteCondition_IF_NOT_EXISTS:
|
||||
ok = !exists
|
||||
case filer_pb.WriteCondition_IF_ENTRY_EQUAL:
|
||||
ok = exists && proto.Equal(current, c.ExpectedEntry)
|
||||
default:
|
||||
return nil, fmt.Errorf("unexpected condition %v", c.Kind)
|
||||
}
|
||||
if !ok {
|
||||
return &filer_pb.CreateEntryResponse{Error: "precondition failed", ErrorCode: filer_pb.FilerError_PRECONDITION_FAILED}, nil
|
||||
}
|
||||
}
|
||||
s.entries[req.Entry.Name] = proto.Clone(req.Entry).(*filer_pb.Entry)
|
||||
return &filer_pb.CreateEntryResponse{}, nil
|
||||
}
|
||||
|
||||
// ObjectTransaction applies the conditional delete FilerRoleStore sends.
|
||||
func (s *roleStoreTestFiler) ObjectTransaction(_ context.Context, req *filer_pb.ObjectTransactionRequest) (*filer_pb.ObjectTransactionResponse, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
if len(req.Mutations) != 1 || req.Mutations[0].Type != filer_pb.ObjectMutation_DELETE {
|
||||
return nil, fmt.Errorf("unexpected mutations %v", req.Mutations)
|
||||
}
|
||||
name := req.Mutations[0].Name
|
||||
current, exists := s.entries[name]
|
||||
for _, c := range req.GetCondition().GetClauses() {
|
||||
if c.Kind != filer_pb.WriteCondition_IF_ENTRY_EQUAL {
|
||||
return nil, fmt.Errorf("unexpected condition %v", c.Kind)
|
||||
}
|
||||
if !exists || !proto.Equal(current, c.ExpectedEntry) {
|
||||
return &filer_pb.ObjectTransactionResponse{Error: "precondition failed", ErrorCode: filer_pb.FilerError_PRECONDITION_FAILED}, nil
|
||||
}
|
||||
}
|
||||
delete(s.entries, name)
|
||||
return &filer_pb.ObjectTransactionResponse{}, nil
|
||||
}
|
||||
|
||||
func (s *roleStoreTestFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream grpc.ServerStreamingServer[filer_pb.ListEntriesResponse]) error {
|
||||
s.mu.Lock()
|
||||
var names []string
|
||||
for name := range s.entries {
|
||||
if name > req.StartFromFileName {
|
||||
names = append(names, name)
|
||||
}
|
||||
}
|
||||
sort.Strings(names)
|
||||
if req.Limit > 0 && len(names) > int(req.Limit) {
|
||||
names = names[:req.Limit]
|
||||
}
|
||||
page := make([]*filer_pb.Entry, 0, len(names))
|
||||
for _, name := range names {
|
||||
page = append(page, proto.Clone(s.entries[name]).(*filer_pb.Entry))
|
||||
}
|
||||
failAfter := s.failListAfter
|
||||
s.mu.Unlock()
|
||||
for i, entry := range page {
|
||||
if failAfter > 0 && i == failAfter {
|
||||
return status.Error(codes.Unavailable, "filer went away")
|
||||
}
|
||||
if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: entry}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *roleStoreTestFiler) DeleteEntry(_ context.Context, req *filer_pb.DeleteEntryRequest) (*filer_pb.DeleteEntryResponse, error) {
|
||||
s.mu.Lock()
|
||||
defer s.mu.Unlock()
|
||||
delete(s.entries, req.Name)
|
||||
return &filer_pb.DeleteEntryResponse{}, nil
|
||||
}
|
||||
|
||||
func newTestFilerRoleStore(t *testing.T) (*FilerRoleStore, *roleStoreTestFiler) {
|
||||
t.Helper()
|
||||
lis, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
require.NoError(t, err)
|
||||
filer := &roleStoreTestFiler{entries: map[string]*filer_pb.Entry{}}
|
||||
server := pb.NewGrpcServer()
|
||||
filer_pb.RegisterSeaweedFilerServer(server, filer)
|
||||
go func() { _ = server.Serve(lis) }()
|
||||
t.Cleanup(func() {
|
||||
server.Stop()
|
||||
_ = lis.Close()
|
||||
})
|
||||
host, port, err := net.SplitHostPort(lis.Addr().String())
|
||||
require.NoError(t, err)
|
||||
grpcPort, err := strconv.Atoi(port)
|
||||
require.NoError(t, err)
|
||||
store, err := NewFilerRoleStore(nil, func() string { return string(pb.NewServerAddress(host, 1, grpcPort)) })
|
||||
require.NoError(t, err)
|
||||
store.grpcDialOption = grpc.WithTransportCredentials(insecure.NewCredentials())
|
||||
return store, filer
|
||||
}
|
||||
|
||||
func attachPolicy(policyName string) RoleUpdate {
|
||||
return func(current *RoleDefinition) (*RoleDefinition, error) {
|
||||
if current == nil {
|
||||
return nil, ErrRoleNotFound
|
||||
}
|
||||
current.AttachedPolicies = append(current.AttachedPolicies, policyName)
|
||||
return current, nil
|
||||
}
|
||||
}
|
||||
|
||||
func createRole(roleID string) RoleUpdate {
|
||||
return func(current *RoleDefinition) (*RoleDefinition, error) {
|
||||
if current != nil {
|
||||
return nil, ErrRoleExists
|
||||
}
|
||||
return &RoleDefinition{RoleName: "app", RoleId: roleID}, nil
|
||||
}
|
||||
}
|
||||
|
||||
// Two servers changing one role: the change written second is applied to
|
||||
// what the first left, not to the role as it read it.
|
||||
func TestFilerRoleUpdateIsNotLostToAConcurrentChange(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, filer := newTestFilerRoleStore(t)
|
||||
require.NoError(t, store.UpdateRole(ctx, "", "app", createRole("AROA1")))
|
||||
|
||||
filer.afterLookup = func() { assert.NoError(t, store.UpdateRole(ctx, "", "app", attachPolicy("peer"))) }
|
||||
require.NoError(t, store.UpdateRole(ctx, "", "app", attachPolicy("mine")))
|
||||
|
||||
role, err := store.GetRole(ctx, "", "app")
|
||||
require.NoError(t, err)
|
||||
assert.ElementsMatch(t, []string{"peer", "mine"}, role.AttachedPolicies, "one server's change was lost")
|
||||
}
|
||||
|
||||
// A change racing a delete must not write the role back.
|
||||
func TestFilerRoleUpdateDoesNotReviveADeletedRole(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, filer := newTestFilerRoleStore(t)
|
||||
require.NoError(t, store.UpdateRole(ctx, "", "app", createRole("AROA1")))
|
||||
|
||||
filer.afterLookup = func() { assert.NoError(t, store.DeleteRole(ctx, "", "app")) }
|
||||
err := store.UpdateRole(ctx, "", "app", attachPolicy("mine"))
|
||||
assert.ErrorIs(t, err, ErrRoleNotFound)
|
||||
|
||||
_, err = store.GetRole(ctx, "", "app")
|
||||
assert.ErrorIs(t, err, ErrRoleNotFound, "the deleted role was written back")
|
||||
}
|
||||
|
||||
// Of two creates of one name, the second sees the first's role.
|
||||
func TestFilerRoleCreateRefusesARoleCreatedConcurrently(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, filer := newTestFilerRoleStore(t)
|
||||
|
||||
filer.afterLookup = func() { assert.NoError(t, store.UpdateRole(ctx, "", "app", createRole("AROA-FIRST"))) }
|
||||
err := store.UpdateRole(ctx, "", "app", createRole("AROA-SECOND"))
|
||||
assert.ErrorIs(t, err, ErrRoleExists)
|
||||
|
||||
role, err := store.GetRole(ctx, "", "app")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "AROA-FIRST", role.RoleId, "the second create replaced the first role")
|
||||
}
|
||||
|
||||
var errRoleHasPolicies = errors.New("role has attached policies")
|
||||
|
||||
// deleteUnattached deletes the role only if it attaches no policy, as
|
||||
// DeleteRole requires.
|
||||
func deleteUnattached(current *RoleDefinition) (*RoleDefinition, error) {
|
||||
if current == nil {
|
||||
return nil, ErrRoleNotFound
|
||||
}
|
||||
if len(current.AttachedPolicies) > 0 {
|
||||
return nil, errRoleHasPolicies
|
||||
}
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
func TestFilerRoleUpdateCanDeleteTheRole(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, _ := newTestFilerRoleStore(t)
|
||||
require.NoError(t, store.UpdateRole(ctx, "", "app", createRole("AROA1")))
|
||||
|
||||
require.NoError(t, store.UpdateRole(ctx, "", "app", deleteUnattached))
|
||||
_, err := store.GetRole(ctx, "", "app")
|
||||
assert.ErrorIs(t, err, ErrRoleNotFound)
|
||||
}
|
||||
|
||||
// A delete is decided against the role it removes: a policy attached between
|
||||
// the check and the delete makes it refuse, not delete the role anyway.
|
||||
func TestFilerRoleDeleteIsDecidedAgainstTheRoleItRemoves(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store, filer := newTestFilerRoleStore(t)
|
||||
require.NoError(t, store.UpdateRole(ctx, "", "app", createRole("AROA1")))
|
||||
|
||||
filer.afterLookup = func() { assert.NoError(t, store.UpdateRole(ctx, "", "app", attachPolicy("peer"))) }
|
||||
err := store.UpdateRole(ctx, "", "app", deleteUnattached)
|
||||
assert.ErrorIs(t, err, errRoleHasPolicies)
|
||||
|
||||
role, err := store.GetRole(ctx, "", "app")
|
||||
require.NoError(t, err, "the role was deleted although a policy was attached to it")
|
||||
assert.Equal(t, []string{"peer"}, role.AttachedPolicies)
|
||||
}
|
||||
|
||||
func TestFilerRoleListingPagesPastTheFirstThousand(t *testing.T) {
|
||||
store, filer := newTestFilerRoleStore(t)
|
||||
for i := range roleListPageSize + 1 {
|
||||
name := fmt.Sprintf("role-%04d.json", i)
|
||||
filer.entries[name] = &filer_pb.Entry{Name: name}
|
||||
}
|
||||
filer.entries["role-0500"] = &filer_pb.Entry{Name: "role-0500", IsDirectory: true}
|
||||
|
||||
names, err := store.ListRoles(context.Background(), "")
|
||||
require.NoError(t, err)
|
||||
assert.Len(t, names, roleListPageSize+1)
|
||||
assert.True(t, slices.Contains(names, fmt.Sprintf("role-%04d", roleListPageSize)), "the role past the first page is missing")
|
||||
}
|
||||
|
||||
// A listing cut short must fail: DeletePolicy decides from it whether any
|
||||
// role still attaches the policy.
|
||||
func TestFilerRoleListingFailsOnABrokenStream(t *testing.T) {
|
||||
store, filer := newTestFilerRoleStore(t)
|
||||
for i := range 5 {
|
||||
name := fmt.Sprintf("role-%d.json", i)
|
||||
filer.entries[name] = &filer_pb.Entry{Name: name}
|
||||
}
|
||||
filer.failListAfter = 3
|
||||
|
||||
_, err := store.ListRoles(context.Background(), "")
|
||||
require.Error(t, err, "a partial listing was returned as complete")
|
||||
|
||||
attaching, err := RolesAttachingPolicy(context.Background(), store, "read")
|
||||
assert.Error(t, err)
|
||||
assert.Nil(t, attaching)
|
||||
assert.False(t, errors.Is(err, ErrRoleNotFound))
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestMemoryRoleStoreWrapsErrRoleNotFound(t *testing.T) {
|
||||
_, err := NewMemoryRoleStore().GetRole(context.Background(), "", "missing")
|
||||
if !errors.Is(err, ErrRoleNotFound) {
|
||||
t.Fatalf("missing role error does not wrap ErrRoleNotFound: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
package integration
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// persistentTestRoleStore stands in for a role store that outlives the process
|
||||
// and may be shared (the filer store): anything but *MemoryRoleStore is
|
||||
// treated as persistent.
|
||||
type persistentTestRoleStore struct {
|
||||
*MemoryRoleStore
|
||||
cleared int
|
||||
}
|
||||
|
||||
func (s *persistentTestRoleStore) ClearCache() { s.cleared++ }
|
||||
|
||||
// startRoleServer initializes a manager as an S3 server would at boot, with the
|
||||
// given role store and config file roles.
|
||||
func startRoleServer(t *testing.T, store RoleStore, staticRoles ...string) *IAMManager {
|
||||
t.Helper()
|
||||
mgr := NewIAMManager()
|
||||
require.NoError(t, mgr.Initialize(persistTestConfig(), func() string { return "localhost:8888" }))
|
||||
mgr.roleStore = store
|
||||
var defs []*RoleDefinition
|
||||
for _, name := range staticRoles {
|
||||
defs = append(defs, &RoleDefinition{RoleName: name})
|
||||
}
|
||||
mgr.LoadStaticRoles(context.Background(), defs)
|
||||
return mgr
|
||||
}
|
||||
|
||||
func roleNames(t *testing.T, store RoleStore) map[string]bool {
|
||||
t.Helper()
|
||||
names, err := store.ListRoles(context.Background(), "")
|
||||
require.NoError(t, err)
|
||||
out := map[string]bool{}
|
||||
for _, n := range names {
|
||||
out[n] = true
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// A persistent store never receives the config file's roles: it outlives the
|
||||
// file and may be shared with servers whose files differ.
|
||||
func TestPersistentRoleStoreNeverHoldsConfigFileRoles(t *testing.T) {
|
||||
store := &persistentTestRoleStore{MemoryRoleStore: NewMemoryRoleStore()}
|
||||
mgr := startRoleServer(t, store, "from-file")
|
||||
|
||||
assert.Empty(t, roleNames(t, store), "a config-file role was written to the persistent store")
|
||||
assert.True(t, roleNames(t, mgr.GetRoleStore())["from-file"], "the config-file role is not listed")
|
||||
role, err := mgr.GetRole(context.Background(), "from-file")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, RoleSourceStaticConfig, role.Source)
|
||||
assert.Equal(t, StaticRoleID(&RoleDefinition{RoleName: "from-file"}), role.RoleId)
|
||||
}
|
||||
|
||||
// Servers sharing a store, with different config files, must not remove or
|
||||
// replace each other's roles — including a zero-config server.
|
||||
func TestServersSharingARoleStoreKeepEachOthersRoles(t *testing.T) {
|
||||
store := &persistentTestRoleStore{MemoryRoleStore: NewMemoryRoleStore()}
|
||||
configured := startRoleServer(t, store, "from-file")
|
||||
require.NoError(t, configured.CreateRole(context.Background(), "", "created-at-runtime", &RoleDefinition{}))
|
||||
|
||||
zeroConfig := startRoleServer(t, store)
|
||||
|
||||
assert.True(t, roleNames(t, store)["created-at-runtime"], "a peer's start removed a role created at runtime")
|
||||
assert.True(t, roleNames(t, configured.GetRoleStore())["from-file"], "the configured server lost its config-file role")
|
||||
_, err := zeroConfig.GetRole(context.Background(), "from-file")
|
||||
assert.ErrorIs(t, err, ErrRoleNotFound, "a server sees a role only its peer's config file defines")
|
||||
_, err = zeroConfig.GetRole(context.Background(), "created-at-runtime")
|
||||
assert.NoError(t, err, "the peer does not see the shared role created at runtime")
|
||||
}
|
||||
|
||||
// Removing a role from the config file removes it at the next start.
|
||||
func TestRemovingARoleFromTheConfigFileRemovesIt(t *testing.T) {
|
||||
store := &persistentTestRoleStore{MemoryRoleStore: NewMemoryRoleStore()}
|
||||
startRoleServer(t, store, "from-file")
|
||||
|
||||
restarted := startRoleServer(t, store) // the file no longer lists it
|
||||
|
||||
_, err := restarted.GetRole(context.Background(), "from-file")
|
||||
assert.ErrorIs(t, err, ErrRoleNotFound, "a role removed from the config file is still served")
|
||||
}
|
||||
|
||||
// The store refuses to replace or delete a role the config file defines; the
|
||||
// file is where it changes.
|
||||
func TestConfigFileRolesCannotBeReplacedOrDeletedThroughTheStore(t *testing.T) {
|
||||
store := &persistentTestRoleStore{MemoryRoleStore: NewMemoryRoleStore()}
|
||||
mgr := startRoleServer(t, store, "from-file")
|
||||
|
||||
err := mgr.CreateRole(context.Background(), "", "from-file", &RoleDefinition{})
|
||||
assert.ErrorIs(t, err, ErrRoleStatic)
|
||||
assert.ErrorIs(t, mgr.DeleteRole(context.Background(), "from-file"), ErrRoleStatic)
|
||||
assert.Empty(t, roleNames(t, store), "a refused change still wrote to the store")
|
||||
}
|
||||
|
||||
// An in-memory store keeps its behaviour: the config file's roles are records
|
||||
// in it.
|
||||
func TestInMemoryRoleStoreStillHoldsConfigFileRoles(t *testing.T) {
|
||||
store := NewMemoryRoleStore()
|
||||
startRoleServer(t, store, "from-file")
|
||||
assert.True(t, roleNames(t, store)["from-file"])
|
||||
}
|
||||
|
||||
// Invalidating the role cache reaches the store beneath the config-file roles.
|
||||
func TestRoleCacheInvalidationReachesTheStoreBeneathTheOverlay(t *testing.T) {
|
||||
store := &persistentTestRoleStore{MemoryRoleStore: NewMemoryRoleStore()}
|
||||
mgr := startRoleServer(t, store, "from-file")
|
||||
mgr.InvalidateRoleCache()
|
||||
assert.Equal(t, 1, store.cleared)
|
||||
}
|
||||
|
||||
func TestRoleCopiesKeepSource(t *testing.T) {
|
||||
role := &RoleDefinition{RoleName: "r", Source: RoleSourceStaticConfig}
|
||||
assert.Equal(t, RoleSourceStaticConfig, copyRoleDefinition(role).Source)
|
||||
assert.Equal(t, RoleSourceStaticConfig, genericCopyRoleDefinition(role).Source)
|
||||
}
|
||||
|
||||
// Config-file roles report no creation time: a time taken at load would
|
||||
// change with every restart.
|
||||
func TestConfigFileRolesReportNoCreationTime(t *testing.T) {
|
||||
for name, store := range map[string]RoleStore{
|
||||
"persistent": &persistentTestRoleStore{MemoryRoleStore: NewMemoryRoleStore()},
|
||||
"in-memory": NewMemoryRoleStore(),
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
mgr := startRoleServer(t, store, "from-file")
|
||||
role, err := mgr.GetRole(context.Background(), "from-file")
|
||||
require.NoError(t, err)
|
||||
assert.True(t, role.CreatedAt.IsZero())
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A role stored under a config-file role's name takes precedence, as a stored
|
||||
// OIDC provider does; it can be changed, and deleting it brings the
|
||||
// config-file role back.
|
||||
func TestStoredRoleTakesPrecedenceOverTheConfigFileOne(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
store := &persistentTestRoleStore{MemoryRoleStore: NewMemoryRoleStore()}
|
||||
configured := startRoleServer(t, store, "shared-name")
|
||||
peer := startRoleServer(t, store)
|
||||
require.NoError(t, peer.CreateRole(ctx, "", "shared-name", &RoleDefinition{Description: "stored"}))
|
||||
|
||||
role, err := configured.GetRole(ctx, "shared-name")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "stored", role.Description, "the config-file role hides the stored one")
|
||||
|
||||
role.Description = "changed"
|
||||
assert.NoError(t, configured.CreateRole(ctx, "", "shared-name", role), "the stored role cannot be changed")
|
||||
|
||||
require.NoError(t, configured.DeleteRole(ctx, "shared-name"))
|
||||
role, err = configured.GetRole(ctx, "shared-name")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, RoleSourceStaticConfig, role.Source, "deleting the stored role did not bring the config-file one back")
|
||||
}
|
||||
|
||||
// A store installed through SetRoleStore behaves like one installed at
|
||||
// startup: the config-file roles stay visible and protected, and it serves
|
||||
// the roles it holds.
|
||||
func TestSetRoleStoreInstallsLikeStartup(t *testing.T) {
|
||||
mgr := startRoleServer(t, &persistentTestRoleStore{MemoryRoleStore: NewMemoryRoleStore()}, "from-file")
|
||||
|
||||
store := &persistentTestRoleStore{MemoryRoleStore: NewMemoryRoleStore()}
|
||||
require.NoError(t, store.StoreRole(context.Background(), "", "stored", &RoleDefinition{RoleName: "stored"}))
|
||||
mgr.SetRoleStore(store)
|
||||
|
||||
names := roleNames(t, mgr.GetRoleStore())
|
||||
assert.True(t, names["from-file"], "the config-file role is no longer listed")
|
||||
assert.True(t, names["stored"], "the new store's role is not listed")
|
||||
assert.ErrorIs(t, mgr.GetRoleStore().DeleteRole(context.Background(), "", "from-file"), ErrRoleStatic)
|
||||
assert.False(t, roleNames(t, store)["from-file"], "the config-file role was written into the new store")
|
||||
}
|
||||
|
||||
// S3 servers watch the directory a filer-backed role store keeps roles in, so
|
||||
// a store configured with its own basePath must report it, through the
|
||||
// cache and the config-file overlay alike.
|
||||
func TestRoleStoreDirectoryIsTheConfiguredBasePath(t *testing.T) {
|
||||
provider := func() string { return "localhost:8888" }
|
||||
cached, err := NewGenericCachedRoleStore(map[string]interface{}{"basePath": "/custom/roles"}, provider)
|
||||
require.NoError(t, err)
|
||||
mgr := startRoleServer(t, cached, "from-file")
|
||||
assert.Equal(t, "/custom/roles", mgr.RoleStoreDirectory())
|
||||
|
||||
uncached, err := NewFilerRoleStore(nil, provider)
|
||||
require.NoError(t, err)
|
||||
mgr.SetRoleStore(uncached)
|
||||
assert.Equal(t, "/etc/iam/roles", mgr.RoleStoreDirectory())
|
||||
|
||||
mgr.SetRoleStore(NewMemoryRoleStore())
|
||||
assert.Empty(t, mgr.RoleStoreDirectory(), "a memory store has no directory")
|
||||
}
|
||||
@@ -473,8 +473,11 @@ func (e *PolicyEngine) EvaluateTrustPolicy(ctx context.Context, trustPolicy *Pol
|
||||
return nil, fmt.Errorf("trust policy cannot be nil")
|
||||
}
|
||||
|
||||
// A trust policy is deny-by-default, whatever the engine's DefaultEffect:
|
||||
// a role may be assumed only by a principal a trust statement explicitly
|
||||
// allows.
|
||||
result := &EvaluationResult{
|
||||
Effect: Effect(e.config.DefaultEffect),
|
||||
Effect: EffectDeny,
|
||||
EvaluationDetails: &EvaluationDetails{
|
||||
Principal: evalCtx.Principal,
|
||||
Action: evalCtx.Action,
|
||||
@@ -511,7 +514,7 @@ func (e *PolicyEngine) EvaluateTrustPolicy(ctx context.Context, trustPolicy *Pol
|
||||
// AWS IAM evaluation logic:
|
||||
// 1. If there's an explicit Deny, the result is Deny
|
||||
// 2. If there's an Allow and no Deny, the result is Allow
|
||||
// 3. Otherwise, use the default effect
|
||||
// 3. Otherwise, the implicit deny stands
|
||||
if explicitDeny {
|
||||
result.Effect = EffectDeny
|
||||
} else if hasAllow {
|
||||
|
||||
@@ -0,0 +1,80 @@
|
||||
package policy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
)
|
||||
|
||||
const subjectBoundTrustPolicy = `{"Version":"2012-10-17","Statement":[{"Effect":"Allow",
|
||||
"Principal":{"Federated":"https://oidc.example"},"Action":["sts:AssumeRoleWithWebIdentity"],
|
||||
"Condition":{"StringEquals":{"oidc:sub":"spiffe://example.org/ns/app/sa/app"}}}]}`
|
||||
|
||||
func webIdentityContext(sub string) *EvaluationContext {
|
||||
return &EvaluationContext{
|
||||
Principal: "web-identity-user",
|
||||
Action: "sts:AssumeRoleWithWebIdentity",
|
||||
Resource: "arn:aws:iam::role/app",
|
||||
RequestContext: map[string]interface{}{
|
||||
"aws:FederatedProvider": "https://oidc.example",
|
||||
"oidc:iss": "https://oidc.example",
|
||||
"oidc:sub": sub,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// A trust policy is deny-by-default. The engine's DefaultEffect decides
|
||||
// requests no identity policy speaks to; it must not let a principal the trust
|
||||
// policy does not allow assume the role.
|
||||
func TestEvaluateTrustPolicyIsImplicitDenyWhateverTheDefaultEffect(t *testing.T) {
|
||||
var trust PolicyDocument
|
||||
if err := json.Unmarshal([]byte(subjectBoundTrustPolicy), &trust); err != nil {
|
||||
t.Fatalf("parse test trust policy: %v", err)
|
||||
}
|
||||
for _, defaultEffect := range []string{"Allow", "Deny"} {
|
||||
t.Run("defaultEffect="+defaultEffect, func(t *testing.T) {
|
||||
engine := NewPolicyEngine()
|
||||
if err := engine.Initialize(&PolicyEngineConfig{DefaultEffect: defaultEffect, StoreType: "memory"}); err != nil {
|
||||
t.Fatalf("initialize policy engine: %v", err)
|
||||
}
|
||||
|
||||
res, err := engine.EvaluateTrustPolicy(context.Background(), &trust, webIdentityContext("spiffe://example.org/ns/other/sa/x"))
|
||||
if err != nil {
|
||||
t.Fatalf("evaluate trust policy: %v", err)
|
||||
}
|
||||
if res.Effect != EffectDeny {
|
||||
t.Errorf("a subject the trust policy does not allow got %s", res.Effect)
|
||||
}
|
||||
|
||||
res, err = engine.EvaluateTrustPolicy(context.Background(), &trust, webIdentityContext("spiffe://example.org/ns/app/sa/app"))
|
||||
if err != nil {
|
||||
t.Fatalf("evaluate trust policy: %v", err)
|
||||
}
|
||||
if res.Effect != EffectAllow {
|
||||
t.Errorf("the subject the trust policy allows got %s", res.Effect)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestEvaluateTrustPolicyExplicitDenyWins(t *testing.T) {
|
||||
var trust PolicyDocument
|
||||
doc := `{"Version":"2012-10-17","Statement":[
|
||||
{"Effect":"Allow","Principal":{"Federated":"https://oidc.example"},"Action":["sts:AssumeRoleWithWebIdentity"]},
|
||||
{"Effect":"Deny","Principal":{"Federated":"https://oidc.example"},"Action":["sts:AssumeRoleWithWebIdentity"],
|
||||
"Condition":{"StringEquals":{"oidc:sub":"spiffe://example.org/ns/app/sa/app"}}}]}`
|
||||
if err := json.Unmarshal([]byte(doc), &trust); err != nil {
|
||||
t.Fatalf("parse test trust policy: %v", err)
|
||||
}
|
||||
engine := NewPolicyEngine()
|
||||
if err := engine.Initialize(&PolicyEngineConfig{DefaultEffect: "Allow", StoreType: "memory"}); err != nil {
|
||||
t.Fatalf("initialize policy engine: %v", err)
|
||||
}
|
||||
res, err := engine.EvaluateTrustPolicy(context.Background(), &trust, webIdentityContext("spiffe://example.org/ns/app/sa/app"))
|
||||
if err != nil {
|
||||
t.Fatalf("evaluate trust policy: %v", err)
|
||||
}
|
||||
if res.Effect != EffectDeny {
|
||||
t.Errorf("explicit Deny did not win: %s", res.Effect)
|
||||
}
|
||||
}
|
||||
@@ -532,3 +532,83 @@ type ListUserTagsResponse struct {
|
||||
} `xml:"ListUserTagsResult"`
|
||||
CommonResponse
|
||||
}
|
||||
|
||||
// IAMRole is the Role element returned by the role actions.
|
||||
type IAMRole struct {
|
||||
Path string `xml:"Path"`
|
||||
RoleName string `xml:"RoleName"`
|
||||
RoleId string `xml:"RoleId"`
|
||||
Arn string `xml:"Arn"`
|
||||
CreateDate string `xml:"CreateDate,omitempty"`
|
||||
AssumeRolePolicyDocument string `xml:"AssumeRolePolicyDocument,omitempty"`
|
||||
Description string `xml:"Description,omitempty"`
|
||||
MaxSessionDuration int64 `xml:"MaxSessionDuration,omitempty"`
|
||||
}
|
||||
|
||||
// IAMAttachedPolicy is one element of ListAttachedRolePolicies.
|
||||
type IAMAttachedPolicy struct {
|
||||
PolicyName string `xml:"PolicyName"`
|
||||
PolicyArn string `xml:"PolicyArn"`
|
||||
}
|
||||
|
||||
// CreateRoleResponse is the response for CreateRole.
|
||||
type CreateRoleResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ CreateRoleResponse"`
|
||||
CreateRoleResult struct {
|
||||
Role IAMRole `xml:"Role"`
|
||||
} `xml:"CreateRoleResult"`
|
||||
CommonResponse
|
||||
}
|
||||
|
||||
// GetRoleResponse is the response for GetRole.
|
||||
type GetRoleResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ GetRoleResponse"`
|
||||
GetRoleResult struct {
|
||||
Role IAMRole `xml:"Role"`
|
||||
} `xml:"GetRoleResult"`
|
||||
CommonResponse
|
||||
}
|
||||
|
||||
// ListRolesResponse is the response for ListRoles.
|
||||
type ListRolesResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ ListRolesResponse"`
|
||||
ListRolesResult struct {
|
||||
Roles []*IAMRole `xml:"Roles>member"`
|
||||
IsTruncated bool `xml:"IsTruncated"`
|
||||
} `xml:"ListRolesResult"`
|
||||
CommonResponse
|
||||
}
|
||||
|
||||
// DeleteRoleResponse is the response for DeleteRole.
|
||||
type DeleteRoleResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ DeleteRoleResponse"`
|
||||
CommonResponse
|
||||
}
|
||||
|
||||
// UpdateAssumeRolePolicyResponse is the response for UpdateAssumeRolePolicy.
|
||||
type UpdateAssumeRolePolicyResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ UpdateAssumeRolePolicyResponse"`
|
||||
CommonResponse
|
||||
}
|
||||
|
||||
// AttachRolePolicyResponse is the response for AttachRolePolicy.
|
||||
type AttachRolePolicyResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ AttachRolePolicyResponse"`
|
||||
CommonResponse
|
||||
}
|
||||
|
||||
// DetachRolePolicyResponse is the response for DetachRolePolicy.
|
||||
type DetachRolePolicyResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ DetachRolePolicyResponse"`
|
||||
CommonResponse
|
||||
}
|
||||
|
||||
// ListAttachedRolePoliciesResponse is the response for ListAttachedRolePolicies.
|
||||
type ListAttachedRolePoliciesResponse struct {
|
||||
XMLName xml.Name `xml:"https://iam.amazonaws.com/doc/2010-05-08/ ListAttachedRolePoliciesResponse"`
|
||||
ListAttachedRolePoliciesResult struct {
|
||||
AttachedPolicies []*IAMAttachedPolicy `xml:"AttachedPolicies>member"`
|
||||
IsTruncated bool `xml:"IsTruncated"`
|
||||
} `xml:"ListAttachedRolePoliciesResult"`
|
||||
CommonResponse
|
||||
}
|
||||
@@ -65,9 +65,10 @@ type STSSessionClaims struct {
|
||||
TokenType string `json:"typ"` // token_type
|
||||
|
||||
// Role information
|
||||
RoleArn string `json:"role"` // role_arn
|
||||
AssumedRole string `json:"assumed"` // assumed_role_user
|
||||
Principal string `json:"principal"` // principal_arn
|
||||
RoleArn string `json:"role"` // role_arn
|
||||
RoleId string `json:"rid,omitempty"` // unique ID of the assumed role
|
||||
AssumedRole string `json:"assumed"` // assumed_role_user
|
||||
Principal string `json:"principal"` // principal_arn
|
||||
|
||||
// Authorization data
|
||||
Policies []string `json:"pol,omitempty"` // policies (abbreviated)
|
||||
@@ -136,6 +137,7 @@ func (c *STSSessionClaims) ToSessionInfo(credGen *CredentialGenerator) *SessionI
|
||||
SessionId: c.SessionId,
|
||||
SessionName: c.SessionName,
|
||||
RoleArn: c.RoleArn,
|
||||
RoleId: c.RoleId,
|
||||
AssumedRoleUser: c.AssumedRole,
|
||||
Principal: c.Principal,
|
||||
Policies: c.Policies,
|
||||
@@ -196,6 +198,13 @@ func (c *STSSessionClaims) WithRoleInfo(roleArn, assumedRole, principal string)
|
||||
}
|
||||
|
||||
// WithPolicies sets the policies associated with this session
|
||||
// WithRoleId binds the session to the assumed role's unique ID. An empty ID
|
||||
// leaves the session unbound (roles that predate role IDs).
|
||||
func (c *STSSessionClaims) WithRoleId(roleId string) *STSSessionClaims {
|
||||
c.RoleId = roleId
|
||||
return c
|
||||
}
|
||||
|
||||
func (c *STSSessionClaims) WithPolicies(policies []string) *STSSessionClaims {
|
||||
c.Policies = policies
|
||||
return c
|
||||
|
||||
@@ -187,6 +187,11 @@ type AssumeRoleWithWebIdentityRequest struct {
|
||||
|
||||
// Policy is an optional session policy (optional)
|
||||
Policy *string `json:"Policy,omitempty"`
|
||||
|
||||
// RoleId is the assumed role's unique ID, set by the IAM manager after it
|
||||
// resolves the role. It is embedded in the session so the session is bound
|
||||
// to this role and not to whatever role later holds the same name.
|
||||
RoleId string `json:"-"`
|
||||
}
|
||||
|
||||
// AssumeRoleWithCredentialsRequest represents a request to assume role with username/password
|
||||
@@ -211,6 +216,9 @@ type AssumeRoleWithCredentialsRequest struct {
|
||||
|
||||
// Policy is an optional session policy (optional)
|
||||
Policy *string `json:"Policy,omitempty"`
|
||||
|
||||
// RoleId is set by the IAM manager; see AssumeRoleWithWebIdentityRequest.
|
||||
RoleId string `json:"-"`
|
||||
}
|
||||
|
||||
// AssumeRoleResponse represents the response from assume role operations
|
||||
@@ -304,6 +312,10 @@ type SessionInfo struct {
|
||||
|
||||
// ParentUser is the stable hashed identity (sub+iss) derived at federation time.
|
||||
ParentUser string `json:"parentUser,omitempty"`
|
||||
|
||||
// RoleId is the unique ID of the role the session was issued for; empty
|
||||
// for sessions issued before role IDs were recorded.
|
||||
RoleId string `json:"roleId,omitempty"`
|
||||
}
|
||||
|
||||
// NewSTSService creates a new STS service
|
||||
@@ -604,7 +616,7 @@ func (s *STSService) AssumeRoleWithWebIdentity(ctx context.Context, request *Ass
|
||||
}
|
||||
|
||||
// 4. Calculate session duration
|
||||
sessionDuration := s.calculateSessionDuration(request.DurationSeconds)
|
||||
sessionDuration := s.CalculateSessionDuration(request.DurationSeconds)
|
||||
expiresAt := time.Now().Add(sessionDuration)
|
||||
|
||||
// 5. Generate session ID and credentials
|
||||
@@ -688,6 +700,7 @@ func (s *STSService) AssumeRoleWithWebIdentity(ctx context.Context, request *Ass
|
||||
sessionClaims := NewSTSSessionClaims(sessionId, s.Config.Issuer, expiresAt).
|
||||
WithSessionName(request.RoleSessionName).
|
||||
WithRoleInfo(effectiveRoleArn, assumedRoleUser.Arn, assumedRoleUser.Arn).
|
||||
WithRoleId(request.RoleId).
|
||||
WithIdentityProvider(provider.Name(), externalIdentity.UserID, externalIdentity.Issuer).
|
||||
WithMaxDuration(sessionDuration).
|
||||
WithRequestContext(requestContext)
|
||||
@@ -760,16 +773,16 @@ func (s *STSService) AssumeRoleWithCredentials(ctx context.Context, request *Ass
|
||||
}
|
||||
|
||||
// 4-7. Mint the session
|
||||
return s.issueSession(request.RoleArn, request.RoleSessionName, sessionPolicy,
|
||||
return s.issueSession(request.RoleArn, request.RoleId, request.RoleSessionName, sessionPolicy,
|
||||
request.DurationSeconds, provider.Name(), externalIdentity.UserID)
|
||||
}
|
||||
|
||||
// issueSession mints temporary credentials and the self-contained JWT that
|
||||
// carries the whole session, shared by every assume-role entry point.
|
||||
func (s *STSService) issueSession(roleArn, roleSessionName, sessionPolicy string,
|
||||
func (s *STSService) issueSession(roleArn, roleId, roleSessionName, sessionPolicy string,
|
||||
durationSeconds *int64, providerName, subject string) (*AssumeRoleResponse, error) {
|
||||
|
||||
sessionDuration := s.calculateSessionDuration(durationSeconds)
|
||||
sessionDuration := s.CalculateSessionDuration(durationSeconds)
|
||||
expiresAt := time.Now().Add(sessionDuration)
|
||||
|
||||
sessionId, err := GenerateSessionId()
|
||||
@@ -791,6 +804,7 @@ func (s *STSService) issueSession(roleArn, roleSessionName, sessionPolicy string
|
||||
sessionClaims := NewSTSSessionClaims(sessionId, s.Config.Issuer, expiresAt).
|
||||
WithSessionName(roleSessionName).
|
||||
WithRoleInfo(roleArn, assumedRoleUser.Arn, assumedRoleUser.Arn).
|
||||
WithRoleId(roleId).
|
||||
WithIdentityProvider(providerName, subject, "").
|
||||
WithMaxDuration(sessionDuration)
|
||||
if sessionPolicy != "" {
|
||||
@@ -891,7 +905,9 @@ func (s *STSService) AssumeRoleForPrincipal(ctx context.Context, request *Assume
|
||||
return nil, fmt.Errorf("role assumption denied: %w", err)
|
||||
}
|
||||
|
||||
return s.issueSession(request.RoleArn, request.RoleSessionName, sessionPolicy,
|
||||
// Iceberg credential vending resolves no role definition, so its sessions
|
||||
// carry no role ID and stay bound by name.
|
||||
return s.issueSession(request.RoleArn, "", request.RoleSessionName, sessionPolicy,
|
||||
request.DurationSeconds, request.ProviderName, request.Principal)
|
||||
}
|
||||
|
||||
@@ -1120,11 +1136,11 @@ func (s *STSService) validateRoleAssumptionForCredentials(ctx context.Context, r
|
||||
return nil
|
||||
}
|
||||
|
||||
// calculateSessionDuration returns the requested DurationSeconds, or the
|
||||
// CalculateSessionDuration returns the requested DurationSeconds, or the
|
||||
// configured TokenDuration default, capped at MaxSessionLength. The source
|
||||
// token's exp deliberately plays no part: per AWS semantics the session
|
||||
// outlives the (already verified) web identity token.
|
||||
func (s *STSService) calculateSessionDuration(durationSeconds *int64) time.Duration {
|
||||
func (s *STSService) CalculateSessionDuration(durationSeconds *int64) time.Duration {
|
||||
var duration time.Duration
|
||||
if durationSeconds != nil {
|
||||
duration = time.Duration(*durationSeconds) * time.Second
|
||||
|
||||
@@ -30,8 +30,8 @@ func TestCalculateSessionDuration(t *testing.T) {
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
if got := svc.calculateSessionDuration(tc.durationSeconds); got != tc.want {
|
||||
t.Errorf("calculateSessionDuration(%v) = %v, want %v", tc.durationSeconds, got, tc.want)
|
||||
if got := svc.CalculateSessionDuration(tc.durationSeconds); got != tc.want {
|
||||
t.Errorf("CalculateSessionDuration(%v) = %v, want %v", tc.durationSeconds, got, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -45,11 +45,11 @@ func DeleteFileIds(masterFn GetMasterFn, usePublicUrl bool, grpcDialOption grpc.
|
||||
return
|
||||
}
|
||||
|
||||
return DeleteFileIdsWithLookupVolumeId(grpcDialOption, fileIds, lookupFunc)
|
||||
return DeleteFileIdsWithLookupVolumeId(context.Background(), grpcDialOption, fileIds, lookupFunc)
|
||||
|
||||
}
|
||||
|
||||
func DeleteFileIdsWithLookupVolumeId(grpcDialOption grpc.DialOption, fileIds []string, lookupFunc func(vid []string) (map[string]*LookupResult, error)) []*volume_server_pb.DeleteResult {
|
||||
func DeleteFileIdsWithLookupVolumeId(ctx context.Context, grpcDialOption grpc.DialOption, fileIds []string, lookupFunc func(vid []string) (map[string]*LookupResult, error)) []*volume_server_pb.DeleteResult {
|
||||
|
||||
var ret []*volume_server_pb.DeleteResult
|
||||
|
||||
@@ -117,7 +117,7 @@ func DeleteFileIdsWithLookupVolumeId(grpcDialOption grpc.DialOption, fileIds []s
|
||||
go func(server pb.ServerAddress, fidList []string) {
|
||||
defer wg.Done()
|
||||
|
||||
resultChan <- DeleteFileIdsAtOneVolumeServer(server, grpcDialOption, fidList, false)
|
||||
resultChan <- DeleteFileIdsAtOneVolumeServer(ctx, server, grpcDialOption, fidList, false)
|
||||
|
||||
}(server, fidList)
|
||||
}
|
||||
@@ -133,7 +133,7 @@ func DeleteFileIdsWithLookupVolumeId(grpcDialOption grpc.DialOption, fileIds []s
|
||||
|
||||
// DeleteFileIdsAtOneVolumeServer deletes a list of files that is on one volume server via gRpc
|
||||
// Returns individual results for each file ID. Check result.Error for per-file failures.
|
||||
func DeleteFileIdsAtOneVolumeServer(volumeServer pb.ServerAddress, grpcDialOption grpc.DialOption, fileIds []string, includeCookie bool) []*volume_server_pb.DeleteResult {
|
||||
func DeleteFileIdsAtOneVolumeServer(ctx context.Context, volumeServer pb.ServerAddress, grpcDialOption grpc.DialOption, fileIds []string, includeCookie bool) []*volume_server_pb.DeleteResult {
|
||||
|
||||
var ret []*volume_server_pb.DeleteResult
|
||||
|
||||
@@ -144,7 +144,7 @@ func DeleteFileIdsAtOneVolumeServer(volumeServer pb.ServerAddress, grpcDialOptio
|
||||
SkipCookieCheck: !includeCookie,
|
||||
}
|
||||
|
||||
resp, err := volumeServerClient.BatchDelete(context.Background(), req)
|
||||
resp, err := volumeServerClient.BatchDelete(ctx, req)
|
||||
|
||||
// fmt.Printf("deleted %v %v: %v\n", fileIds, err, resp)
|
||||
|
||||
|
||||
@@ -168,6 +168,7 @@ message VacuumVolumeCheckRequest {
|
||||
}
|
||||
message VacuumVolumeCheckResponse {
|
||||
double garbage_ratio = 1;
|
||||
bool disk_space_low = 4; // the volume is read-only solely because its disk is low on space — a cause compaction itself reclaims
|
||||
}
|
||||
|
||||
message VacuumVolumeCompactRequest {
|
||||
@@ -477,6 +478,7 @@ message VolumeEcShardsDeleteRequest {
|
||||
repeated uint32 shard_ids = 3;
|
||||
bool full_teardown = 4; // pre-encode cleanup: wipe every EC artifact + generation for this volume, not just shard_ids
|
||||
int64 encode_ts_ns = 5; // full_teardown generation fence: delete only a disk whose .vif generation is strictly OLDER than this; preserve same-or-newer, generation 0, and an unreadable .vif. 0 => wipe-all (shell pre-encode / pre-upgrade)
|
||||
uint32 delete_generations_older_than = 6; // post-commit cleanup: delete only staged <base>.*.v<N> artifacts with N strictly below this; 0 disables
|
||||
}
|
||||
message VolumeEcShardsDeleteResponse {
|
||||
bool full_teardown_done = 1; // set by a new server that performed full_teardown; absent from an old server lets the caller detect the silent no-op
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go. DO NOT EDIT.
|
||||
// versions:
|
||||
// protoc-gen-go v1.36.6
|
||||
// protoc v6.33.4
|
||||
// protoc v3.21.12
|
||||
// source: volume_server.proto
|
||||
|
||||
package volume_server_pb
|
||||
@@ -436,6 +436,7 @@ func (x *VacuumVolumeCheckRequest) GetVolumeId() uint32 {
|
||||
type VacuumVolumeCheckResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
GarbageRatio float64 `protobuf:"fixed64,1,opt,name=garbage_ratio,json=garbageRatio,proto3" json:"garbage_ratio,omitempty"`
|
||||
DiskSpaceLow bool `protobuf:"varint,4,opt,name=disk_space_low,json=diskSpaceLow,proto3" json:"disk_space_low,omitempty"` // the volume is read-only solely because its disk is low on space — a cause compaction itself reclaims
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
@@ -477,6 +478,13 @@ func (x *VacuumVolumeCheckResponse) GetGarbageRatio() float64 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *VacuumVolumeCheckResponse) GetDiskSpaceLow() bool {
|
||||
if x != nil {
|
||||
return x.DiskSpaceLow
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
type VacuumVolumeCompactRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
VolumeId uint32 `protobuf:"varint,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"`
|
||||
@@ -1469,7 +1477,8 @@ type VolumeDeleteRequest struct {
|
||||
// used for moves where another server is taking over the same .vif.
|
||||
KeepRemoteData bool `protobuf:"varint,3,opt,name=keep_remote_data,json=keepRemoteData,proto3" json:"keep_remote_data,omitempty"`
|
||||
// when true, delete only if every needle is deleted: the volume held
|
||||
// data once but nothing is live anymore.
|
||||
// data once but nothing is live anymore. Passing either check,
|
||||
// only_empty or this one, is enough to delete.
|
||||
OnlyGarbage bool `protobuf:"varint,4,opt,name=only_garbage,json=onlyGarbage,proto3" json:"only_garbage,omitempty"`
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
@@ -3732,14 +3741,15 @@ func (*VolumeEcShardsCopyResponse) Descriptor() ([]byte, []int) {
|
||||
}
|
||||
|
||||
type VolumeEcShardsDeleteRequest struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
VolumeId uint32 `protobuf:"varint,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"`
|
||||
Collection string `protobuf:"bytes,2,opt,name=collection,proto3" json:"collection,omitempty"`
|
||||
ShardIds []uint32 `protobuf:"varint,3,rep,packed,name=shard_ids,json=shardIds,proto3" json:"shard_ids,omitempty"`
|
||||
FullTeardown bool `protobuf:"varint,4,opt,name=full_teardown,json=fullTeardown,proto3" json:"full_teardown,omitempty"` // pre-encode cleanup: wipe every EC artifact + generation for this volume, not just shard_ids
|
||||
EncodeTsNs int64 `protobuf:"varint,5,opt,name=encode_ts_ns,json=encodeTsNs,proto3" json:"encode_ts_ns,omitempty"` // full_teardown generation fence: delete only a disk whose .vif generation is strictly OLDER than this; preserve same-or-newer, generation 0, and an unreadable .vif. 0 => wipe-all (shell pre-encode / pre-upgrade)
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
VolumeId uint32 `protobuf:"varint,1,opt,name=volume_id,json=volumeId,proto3" json:"volume_id,omitempty"`
|
||||
Collection string `protobuf:"bytes,2,opt,name=collection,proto3" json:"collection,omitempty"`
|
||||
ShardIds []uint32 `protobuf:"varint,3,rep,packed,name=shard_ids,json=shardIds,proto3" json:"shard_ids,omitempty"`
|
||||
FullTeardown bool `protobuf:"varint,4,opt,name=full_teardown,json=fullTeardown,proto3" json:"full_teardown,omitempty"` // pre-encode cleanup: wipe every EC artifact + generation for this volume, not just shard_ids
|
||||
EncodeTsNs int64 `protobuf:"varint,5,opt,name=encode_ts_ns,json=encodeTsNs,proto3" json:"encode_ts_ns,omitempty"` // full_teardown generation fence: delete only a disk whose .vif generation is strictly OLDER than this; preserve same-or-newer, generation 0, and an unreadable .vif. 0 => wipe-all (shell pre-encode / pre-upgrade)
|
||||
DeleteGenerationsOlderThan uint32 `protobuf:"varint,6,opt,name=delete_generations_older_than,json=deleteGenerationsOlderThan,proto3" json:"delete_generations_older_than,omitempty"` // post-commit cleanup: delete only staged <base>.*.v<N> artifacts with N strictly below this; 0 disables
|
||||
unknownFields protoimpl.UnknownFields
|
||||
sizeCache protoimpl.SizeCache
|
||||
}
|
||||
|
||||
func (x *VolumeEcShardsDeleteRequest) Reset() {
|
||||
@@ -3807,6 +3817,13 @@ func (x *VolumeEcShardsDeleteRequest) GetEncodeTsNs() int64 {
|
||||
return 0
|
||||
}
|
||||
|
||||
func (x *VolumeEcShardsDeleteRequest) GetDeleteGenerationsOlderThan() uint32 {
|
||||
if x != nil {
|
||||
return x.DeleteGenerationsOlderThan
|
||||
}
|
||||
return 0
|
||||
}
|
||||
|
||||
type VolumeEcShardsDeleteResponse struct {
|
||||
state protoimpl.MessageState `protogen:"open.v1"`
|
||||
FullTeardownDone bool `protobuf:"varint,1,opt,name=full_teardown_done,json=fullTeardownDone,proto3" json:"full_teardown_done,omitempty"` // set by a new server that performed full_teardown; absent from an old server lets the caller detect the silent no-op
|
||||
@@ -7267,9 +7284,10 @@ const file_volume_server_proto_rawDesc = "" +
|
||||
"\aversion\x18\x05 \x01(\rR\aversion\"\a\n" +
|
||||
"\x05Empty\"7\n" +
|
||||
"\x18VacuumVolumeCheckRequest\x12\x1b\n" +
|
||||
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\"@\n" +
|
||||
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\"f\n" +
|
||||
"\x19VacuumVolumeCheckResponse\x12#\n" +
|
||||
"\rgarbage_ratio\x18\x01 \x01(\x01R\fgarbageRatio\"[\n" +
|
||||
"\rgarbage_ratio\x18\x01 \x01(\x01R\fgarbageRatio\x12$\n" +
|
||||
"\x0edisk_space_low\x18\x04 \x01(\bR\fdiskSpaceLow\"[\n" +
|
||||
"\x1aVacuumVolumeCompactRequest\x12\x1b\n" +
|
||||
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\x12 \n" +
|
||||
"\vpreallocate\x18\x02 \x01(\x03R\vpreallocate\"f\n" +
|
||||
@@ -7505,7 +7523,7 @@ const file_volume_server_proto_rawDesc = "" +
|
||||
"\x0fcopy_ecsum_file\x18\t \x01(\bR\rcopyEcsumFile\x12+\n" +
|
||||
"\x12io_byte_per_second\x18\n" +
|
||||
" \x01(\x03R\x0fioBytePerSecond\"\x1c\n" +
|
||||
"\x1aVolumeEcShardsCopyResponse\"\xbe\x01\n" +
|
||||
"\x1aVolumeEcShardsCopyResponse\"\x81\x02\n" +
|
||||
"\x1bVolumeEcShardsDeleteRequest\x12\x1b\n" +
|
||||
"\tvolume_id\x18\x01 \x01(\rR\bvolumeId\x12\x1e\n" +
|
||||
"\n" +
|
||||
@@ -7514,7 +7532,8 @@ const file_volume_server_proto_rawDesc = "" +
|
||||
"\tshard_ids\x18\x03 \x03(\rR\bshardIds\x12#\n" +
|
||||
"\rfull_teardown\x18\x04 \x01(\bR\ffullTeardown\x12 \n" +
|
||||
"\fencode_ts_ns\x18\x05 \x01(\x03R\n" +
|
||||
"encodeTsNs\"L\n" +
|
||||
"encodeTsNs\x12A\n" +
|
||||
"\x1ddelete_generations_older_than\x18\x06 \x01(\rR\x1adeleteGenerationsOlderThan\"L\n" +
|
||||
"\x1cVolumeEcShardsDeleteResponse\x12,\n" +
|
||||
"\x12full_teardown_done\x18\x01 \x01(\bR\x10fullTeardownDone\"\xd4\x01\n" +
|
||||
"\x1aVolumeEcShardsMountRequest\x12\x1b\n" +
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
// Code generated by protoc-gen-go-grpc. DO NOT EDIT.
|
||||
// versions:
|
||||
// - protoc-gen-go-grpc v1.6.2
|
||||
// - protoc v6.33.4
|
||||
// - protoc v3.21.12
|
||||
// source: volume_server.proto
|
||||
|
||||
package volume_server_pb
|
||||
@@ -74,7 +74,7 @@ const (
|
||||
//
|
||||
// For semantics around ctx use and closing/ending streaming RPCs, please refer to https://pkg.go.dev/google.golang.org/grpc/?tab=doc#ClientConn.NewStream.
|
||||
type VolumeServerClient interface {
|
||||
// Experts only: takes multiple fid parameters. This function does not propagate deletes to replicas.
|
||||
//Experts only: takes multiple fid parameters. This function does not propagate deletes to replicas.
|
||||
BatchDelete(ctx context.Context, in *BatchDeleteRequest, opts ...grpc.CallOption) (*BatchDeleteResponse, error)
|
||||
VacuumVolumeCheck(ctx context.Context, in *VacuumVolumeCheckRequest, opts ...grpc.CallOption) (*VacuumVolumeCheckResponse, error)
|
||||
VacuumVolumeCompact(ctx context.Context, in *VacuumVolumeCompactRequest, opts ...grpc.CallOption) (grpc.ServerStreamingClient[VacuumVolumeCompactResponse], error)
|
||||
@@ -727,7 +727,7 @@ func (c *volumeServerClient) Ping(ctx context.Context, in *PingRequest, opts ...
|
||||
// All implementations must embed UnimplementedVolumeServerServer
|
||||
// for forward compatibility.
|
||||
type VolumeServerServer interface {
|
||||
// Experts only: takes multiple fid parameters. This function does not propagate deletes to replicas.
|
||||
//Experts only: takes multiple fid parameters. This function does not propagate deletes to replicas.
|
||||
BatchDelete(context.Context, *BatchDeleteRequest) (*BatchDeleteResponse, error)
|
||||
VacuumVolumeCheck(context.Context, *VacuumVolumeCheckRequest) (*VacuumVolumeCheckResponse, error)
|
||||
VacuumVolumeCompact(*VacuumVolumeCompactRequest, grpc.ServerStreamingServer[VacuumVolumeCompactResponse]) error
|
||||
|
||||
@@ -144,6 +144,43 @@ func TestAuditRequesterIdentityEmptyForNonFederatedSession(t *testing.T) {
|
||||
assert.Empty(t, log.RequesterIdentity, "non-federated session must not surface the session id as a requester_identity")
|
||||
}
|
||||
|
||||
// Authentication resolves the identity before the policy verdict, so a denied
|
||||
// request still has a requester and the audit entry must name it. See issue
|
||||
// #11474.
|
||||
func TestAuditRequesterForDeniedRequest(t *testing.T) {
|
||||
iam := &IdentityAccessManagement{}
|
||||
require.NoError(t, iam.loadS3ApiConfiguration(&iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{{
|
||||
Name: "read_only_user",
|
||||
Credentials: []*iam_pb.Credential{{AccessKey: "readonly_access_key", SecretKey: "readonly_secret_key"}},
|
||||
Actions: []string{"Read", "List"},
|
||||
}},
|
||||
}))
|
||||
|
||||
denied, err := newTestRequest(http.MethodDelete, "http://s3/bucket/obj", 0, nil)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, signRequestV4(denied, "readonly_access_key", "readonly_secret_key"))
|
||||
denied = s3_constants.EnsureIdentityHolder(denied)
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
iam.Auth(func(http.ResponseWriter, *http.Request) {
|
||||
t.Error("denied request must not reach the handler")
|
||||
}, s3_constants.ACTION_WRITE)(rec, denied)
|
||||
|
||||
require.Equal(t, http.StatusForbidden, rec.Code)
|
||||
log := s3err.GetAccessLog(denied, rec.Code, s3err.ErrAccessDenied)
|
||||
assert.Equal(t, "read_only_user", log.Requester, "denied request must still audit the requester")
|
||||
assert.Equal(t, "arn:aws:iam::"+defaultAccountID+":user/read_only_user", log.RequesterArn)
|
||||
|
||||
anonymous := s3_constants.EnsureIdentityHolder(httptest.NewRequest(http.MethodDelete, "http://s3/bucket/obj", nil))
|
||||
rec = httptest.NewRecorder()
|
||||
iam.handleAuthResult(rec, anonymous, nil, s3err.ErrAccessDenied, func(http.ResponseWriter, *http.Request) {
|
||||
t.Error("denied request must not reach the handler")
|
||||
})
|
||||
log = s3err.GetAccessLog(anonymous, rec.Code, s3err.ErrAccessDenied)
|
||||
assert.Empty(t, log.Requester, "unauthenticated denial must not attribute a requester")
|
||||
}
|
||||
|
||||
// A JWT-authenticated identity carries no PrincipalArn of its own — the auth
|
||||
// layer hands the principal over in a request header — so the audit entry has to
|
||||
// resolve the ARN the same way policy evaluation does.
|
||||
|
||||
@@ -1565,7 +1565,10 @@ func (iam *IdentityAccessManagement) Auth(f http.HandlerFunc, action Action) htt
|
||||
return
|
||||
}
|
||||
|
||||
identity, errCode := iam.authRequest(r, action)
|
||||
// authRequestWithAuthType keeps the resolved identity when authN
|
||||
// succeeds but authZ denies, so the denied request still audits its
|
||||
// requester; a failed authN resolves no identity at all.
|
||||
identity, errCode, _ := iam.authRequestWithAuthType(r, action)
|
||||
if errCode != s3err.ErrNone {
|
||||
glog.V(3).Infof("auth error: %v", errCode)
|
||||
}
|
||||
@@ -1631,11 +1634,12 @@ func recordIdentityInContext(r *http.Request, identity *Identity) context.Contex
|
||||
}
|
||||
|
||||
func (iam *IdentityAccessManagement) handleAuthResult(w http.ResponseWriter, r *http.Request, identity *Identity, errCode s3err.ErrorCode, f http.HandlerFunc) {
|
||||
// Store the authenticated identity in request context (secure, cannot be spoofed)
|
||||
// even on the deny path so audit records for rejected requests keep requester attribution
|
||||
if identity != nil && identity.Name != "" {
|
||||
r = r.WithContext(recordIdentityInContext(r, identity))
|
||||
}
|
||||
if errCode == s3err.ErrNone {
|
||||
// Store the authenticated identity in request context (secure, cannot be spoofed)
|
||||
if identity != nil && identity.Name != "" {
|
||||
r = r.WithContext(recordIdentityInContext(r, identity))
|
||||
}
|
||||
f(w, r)
|
||||
return
|
||||
}
|
||||
@@ -1749,6 +1753,23 @@ func (iam *IdentityAccessManagement) authenticateRequestInternal(r *http.Request
|
||||
return identity, s3Err, reqAuthType
|
||||
}
|
||||
|
||||
// isBucketListingRequest reports whether the request lists bucket contents:
|
||||
// the ACTION_LIST routes, and ListMultipartUploads (GET ?uploads), which the
|
||||
// router registers under ACTION_READ without an object-path constraint.
|
||||
// GET /bucket/key?uploads therefore also reaches the listing handler. Route
|
||||
// vars are used so a prefix promoted into the authorization object does not
|
||||
// hide the bucket-level shape.
|
||||
func isBucketListingRequest(r *http.Request, action Action) bool {
|
||||
if action == s3_constants.ACTION_LIST {
|
||||
return true
|
||||
}
|
||||
if r.Method != http.MethodGet || r.URL == nil || !r.URL.Query().Has("uploads") {
|
||||
return false
|
||||
}
|
||||
_, object := s3_constants.GetBucketAndObject(r)
|
||||
return object == "" || object == "/"
|
||||
}
|
||||
|
||||
// authRequestWithAuthType authenticates and then authorizes a request for a given action.
|
||||
func (iam *IdentityAccessManagement) authRequestWithAuthType(r *http.Request, action Action) (*Identity, s3err.ErrorCode, authType) {
|
||||
identity, s3Err, reqAuthType := iam.authenticateRequestInternal(r)
|
||||
@@ -1759,13 +1780,13 @@ func (iam *IdentityAccessManagement) authRequestWithAuthType(r *http.Request, ac
|
||||
bucket, object := s3_constants.GetBucketAndObject(r)
|
||||
prefix := s3_constants.GetPrefix(r)
|
||||
|
||||
// For List operations, use prefix for permission checking if available
|
||||
if action == s3_constants.ACTION_LIST && object == "" && prefix != "" {
|
||||
// List operation with prefix - check permission for the prefix path
|
||||
object = prefix
|
||||
} else if (object == "/" || object == "") && prefix != "" {
|
||||
// Using the aws cli with s3, and s3api, and with boto3, the object is often set to "/" or empty
|
||||
// but the prefix is set to the actual object key for permission checking
|
||||
// For bucket listings, use prefix for permission checking if available:
|
||||
// the aws cli, s3api, and boto3 carry the key scope in ?prefix= rather
|
||||
// than the URL path. Other actions must not promote it — a bucket-level
|
||||
// request has no object, and a promoted prefix would let an object-scoped
|
||||
// grant (e.g. Write:bucket/*) authorize bucket-subresource operations
|
||||
// like ?versioning or ?lifecycle as if they were object writes.
|
||||
if isBucketListingRequest(r, action) && (object == "" || object == "/") && prefix != "" {
|
||||
object = prefix
|
||||
}
|
||||
|
||||
@@ -1806,11 +1827,11 @@ func (iam *IdentityAccessManagement) authRequestWithAuthType(r *http.Request, ac
|
||||
if identity != nil {
|
||||
claims = identity.Claims
|
||||
}
|
||||
// List is bucket-level; the prefix promoted into object (for the
|
||||
// legacy CanDo path) must not scope the resource ARN. Prefix is
|
||||
// matched via the s3:prefix Condition.
|
||||
// Bucket listings are bucket-level; the prefix promoted into
|
||||
// object (for the legacy CanDo path) must not scope the resource
|
||||
// ARN. Prefix is matched via the s3:prefix Condition.
|
||||
policyObject := object
|
||||
if action == s3_constants.ACTION_LIST {
|
||||
if isBucketListingRequest(r, action) {
|
||||
policyObject = ""
|
||||
}
|
||||
allowed, evaluated, err := iam.policyEngine.EvaluatePolicy(bucket, policyObject, string(action), principal, r, claims, nil)
|
||||
@@ -2513,11 +2534,12 @@ func (iam *IdentityAccessManagement) evaluateAttachedIAMPolicies(r *http.Request
|
||||
return attachedIAMPolicyNoMatch
|
||||
}
|
||||
|
||||
// List is bucket-level; the prefix promoted into object (for the legacy
|
||||
// CanDo path) must not scope the resource ARN or the resolved action
|
||||
// (e.g. ListBucketVersions on ?versions). Prefix is matched via s3:prefix.
|
||||
// Bucket listings are bucket-level; the prefix promoted into object (for
|
||||
// the legacy CanDo path) must not scope the resource ARN or the resolved
|
||||
// action (e.g. ListBucketVersions on ?versions). Prefix is matched via
|
||||
// s3:prefix.
|
||||
resourceObject := object
|
||||
if action == s3_constants.ACTION_LIST {
|
||||
if isBucketListingRequest(r, action) {
|
||||
resourceObject = ""
|
||||
}
|
||||
resource := buildResourceARN(bucket, resourceObject)
|
||||
@@ -3017,11 +3039,11 @@ func (iam *IdentityAccessManagement) authorizeWithIAM(r *http.Request, identity
|
||||
// check evaluates the same action and resource ARN as the policy engine.
|
||||
func resolveS3AuthTarget(action Action, bucket, object string, r *http.Request) (s3Action, resourceArn string) {
|
||||
resourceObjectKey := object
|
||||
if action == s3_constants.ACTION_LIST {
|
||||
if isBucketListingRequest(r, action) {
|
||||
resourceObjectKey = ""
|
||||
}
|
||||
resourceArn = buildS3ResourceArn(bucket, resourceObjectKey)
|
||||
s3Action = ResolveS3Action(r, string(action), bucket, object)
|
||||
s3Action = ResolveS3Action(r, string(action), bucket, resourceObjectKey)
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
@@ -124,3 +124,54 @@ func TestAttachedPolicyExplicitDenyOverridesNativeAdmin(t *testing.T) {
|
||||
assert.Equal(t, s3err.ErrAccessDenied, errCode,
|
||||
"explicit Deny in an attached policy must override native Admin")
|
||||
}
|
||||
|
||||
// GET ?uploads lists multipart uploads at bucket level but routes under Read,
|
||||
// so the prefix promoted into object must not change the evaluated action or
|
||||
// resource: an explicit Deny on s3:ListBucketMultipartUploads must still
|
||||
// constrain a native admin, and an Allow on the bucket ARN must satisfy a
|
||||
// plain attached-policy identity.
|
||||
func TestMultipartListingResolvesBucketAction(t *testing.T) {
|
||||
mgr := newTestIAMManager(t)
|
||||
iam := &IdentityAccessManagement{}
|
||||
iam.SetIAMIntegration(NewS3IAMIntegration(mgr, ""))
|
||||
|
||||
denyDoc, _ := json.Marshal(map[string]interface{}{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]interface{}{
|
||||
{"Effect": "Deny", "Action": "s3:ListBucketMultipartUploads", "Resource": "arn:aws:s3:::mybucket"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, iam.PutPolicy("DenyUploadsListing", string(denyDoc)))
|
||||
allowDoc, _ := json.Marshal(map[string]interface{}{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]interface{}{
|
||||
{"Effect": "Allow", "Action": "s3:ListBucketMultipartUploads", "Resource": "arn:aws:s3:::mybucket"},
|
||||
},
|
||||
})
|
||||
require.NoError(t, iam.PutPolicy("AllowUploadsListing", string(allowDoc)))
|
||||
|
||||
uploadsReq := func() *http.Request {
|
||||
return httptest.NewRequest(http.MethodGet, "/mybucket?uploads&prefix=x/", nil)
|
||||
}
|
||||
admin := &Identity{
|
||||
Name: "admin",
|
||||
Account: &Account{DisplayName: "admin", Id: "admin"},
|
||||
Actions: []Action{s3_constants.ACTION_ADMIN},
|
||||
PolicyNames: []string{"DenyUploadsListing"},
|
||||
PrincipalArn: "arn:aws:iam::111122223333:user/admin",
|
||||
}
|
||||
reader := &Identity{
|
||||
Name: "reader",
|
||||
Account: &Account{DisplayName: "reader", Id: "reader"},
|
||||
PolicyNames: []string{"AllowUploadsListing"},
|
||||
PrincipalArn: "arn:aws:iam::111122223333:user/reader",
|
||||
}
|
||||
|
||||
// object carries the promoted prefix, matching authRequestWithAuthType
|
||||
assert.Equal(t, s3err.ErrAccessDenied,
|
||||
iam.VerifyActionPermission(uploadsReq(), admin, s3_constants.ACTION_READ, "mybucket", "x/"),
|
||||
"explicit Deny on the uploads listing must override native Admin")
|
||||
assert.Equal(t, s3err.ErrNone,
|
||||
iam.VerifyActionPermission(uploadsReq(), reader, s3_constants.ACTION_READ, "mybucket", "x/"),
|
||||
"s3:ListBucketMultipartUploads on the bucket must allow the uploads listing")
|
||||
}
|
||||
@@ -14,6 +14,9 @@ import (
|
||||
|
||||
const oidcProvidersDir = filer.IamConfigDirectory + "/oidc-providers"
|
||||
|
||||
// rolesDir is the filer role store's default base path (sts.DefaultRoleBasePath).
|
||||
const rolesDir = filer.IamConfigDirectory + "/roles"
|
||||
|
||||
func (s3a *S3ApiServer) subscribeMetaEvents(clientName string, lastTsNs int64, prefix string, directoriesToWatch []string) {
|
||||
|
||||
processEventFn := func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
@@ -33,6 +36,7 @@ func (s3a *S3ApiServer) subscribeMetaEvents(clientName string, lastTsNs int64, p
|
||||
_ = s3a.onBucketMetadataChange(dir, message.OldEntry, message.NewEntry)
|
||||
_ = s3a.onIamConfigChange(dir, message.OldEntry, message.NewEntry)
|
||||
_ = s3a.onOIDCProviderChange(dir, message.OldEntry, message.NewEntry)
|
||||
s3a.onRoleChange(dir)
|
||||
_ = s3a.onCircuitBreakerConfigChange(dir, message.OldEntry, message.NewEntry)
|
||||
|
||||
// For moves across directories, replay a delete event for the source directory
|
||||
@@ -40,6 +44,7 @@ func (s3a *S3ApiServer) subscribeMetaEvents(clientName string, lastTsNs int64, p
|
||||
_ = s3a.onBucketMetadataChange(resp.Directory, message.OldEntry, nil)
|
||||
_ = s3a.onIamConfigChange(resp.Directory, message.OldEntry, nil)
|
||||
_ = s3a.onOIDCProviderChange(resp.Directory, message.OldEntry, nil)
|
||||
s3a.onRoleChange(resp.Directory)
|
||||
_ = s3a.onCircuitBreakerConfigChange(resp.Directory, message.OldEntry, nil)
|
||||
}
|
||||
|
||||
@@ -137,6 +142,40 @@ func (s3a *S3ApiServer) onOIDCProviderChange(dir string, oldEntry *filer_pb.Entr
|
||||
return nil
|
||||
}
|
||||
|
||||
// roleStoreDir is the directory the persisted role store keeps roles in: its
|
||||
// configured basePath, else the default. The metadata subscription watches it.
|
||||
func (s3a *S3ApiServer) roleStoreDir() string {
|
||||
if s3a.iam != nil {
|
||||
if provider, ok := s3a.iam.iamIntegration.(IAMManagerProvider); ok {
|
||||
if mgr := provider.GetIAMManager(); mgr != nil {
|
||||
if dir := mgr.RoleStoreDirectory(); dir != "" {
|
||||
return dir
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return rolesDir
|
||||
}
|
||||
|
||||
// onRoleChange drops the cached role definitions when the persisted role
|
||||
// store's directory changes, so a role created, changed or deleted on a peer
|
||||
// takes effect here on the next lookup instead of after the cache TTL.
|
||||
func (s3a *S3ApiServer) onRoleChange(dir string) {
|
||||
base := s3a.roleStoreDir()
|
||||
if dir != base && !strings.HasPrefix(dir, base+"/") {
|
||||
return
|
||||
}
|
||||
if s3a.iam == nil || s3a.iam.iamIntegration == nil {
|
||||
return
|
||||
}
|
||||
s3iam, ok := s3a.iam.iamIntegration.(*S3IAMIntegration)
|
||||
if !ok || s3iam.iamManager == nil {
|
||||
return
|
||||
}
|
||||
s3iam.iamManager.InvalidateRoleCache()
|
||||
glog.V(2).Infof("Invalidated cached roles after %s change", dir)
|
||||
}
|
||||
|
||||
// onCircuitBreakerConfigChange handles circuit breaker config file changes (create, update, delete)
|
||||
func (s3a *S3ApiServer) onCircuitBreakerConfigChange(dir string, oldEntry *filer_pb.Entry, newEntry *filer_pb.Entry) error {
|
||||
if dir != s3_constants.CircuitBreakerConfigDir {
|
||||
|
||||
@@ -12,6 +12,7 @@ import (
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
v4 "github.com/aws/aws-sdk-go-v2/aws/signer/v4"
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
"github.com/stretchr/testify/assert"
|
||||
@@ -557,3 +558,108 @@ func TestRealSDKSignerWithForwardedHeaders(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// GHSA-8rrx-349w-6396: ?prefix= was promoted into the object for every action,
|
||||
// so PUT /cache?versioning&prefix=x authorized as Write:cache/x. An identity
|
||||
// holding only Write:cache/* could then change bucket versioning, lifecycle,
|
||||
// cors, and object-lock configuration.
|
||||
func TestPrefixParameterDoesNotEscalateBucketActions(t *testing.T) {
|
||||
resetMemoryStore()
|
||||
defer resetMemoryStore()
|
||||
|
||||
configContent := `{
|
||||
"identities": [
|
||||
{"name":"admin","credentials":[{"accessKey":"ADMINKEY","secretKey":"adminsecret0000000000000000000001"}],"actions":["Admin"]},
|
||||
{"name":"writer","credentials":[{"accessKey":"WRITERKEY","secretKey":"writersecret000000000000000000001"}],"actions":["Read:cache","Write:cache/*","List:cache"]},
|
||||
{"name":"uploadreader","credentials":[{"accessKey":"UPREADERKEY","secretKey":"upreadersecret00000000000000001"}],"actions":["Read:cache/uploads/*"]},
|
||||
{"name":"policywriter","credentials":[{"accessKey":"POLICYKEY","secretKey":"policysecret00000000000000000001"}],"policyNames":["WriterPolicy"]},
|
||||
{"name":"uploadlister","credentials":[{"accessKey":"UPLISTERKEY","secretKey":"uplistersecret00000000000000001"}],"policyNames":["UploadsPolicy"]},
|
||||
{"name":"getonly","credentials":[{"accessKey":"GETONLYKEY","secretKey":"getonlysecret0000000000000000001"}],"policyNames":["GetOnlyPolicy"]}
|
||||
],
|
||||
"policies":[
|
||||
{"name":"WriterPolicy","content":"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"s3:PutObject\"],\"Resource\":[\"arn:aws:s3:::cache/*\"]}]}"},
|
||||
{"name":"UploadsPolicy","content":"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"s3:ListBucketMultipartUploads\"],\"Resource\":[\"arn:aws:s3:::cache\"]}]}"},
|
||||
{"name":"GetOnlyPolicy","content":"{\"Version\":\"2012-10-17\",\"Statement\":[{\"Effect\":\"Allow\",\"Action\":[\"s3:GetObject\"],\"Resource\":[\"arn:aws:s3:::cache/*\"]}]}"}
|
||||
]
|
||||
}`
|
||||
tmpFile, err := os.CreateTemp("", "s3-config-*.json")
|
||||
require.NoError(t, err)
|
||||
defer os.Remove(tmpFile.Name())
|
||||
_, err = tmpFile.Write([]byte(configContent))
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, tmpFile.Close())
|
||||
|
||||
iam := NewIdentityAccessManagementWithStore(&S3ApiServerOption{Config: tmpFile.Name()}, nil, "memory")
|
||||
require.True(t, iam.isEnabled(), "Auth should be enabled")
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
access string
|
||||
secret string
|
||||
object string
|
||||
query string
|
||||
action Action
|
||||
want s3err.ErrorCode
|
||||
}{
|
||||
{"writer put object", "WRITERKEY", "writersecret000000000000000000001", "key", "", s3_constants.ACTION_WRITE, s3err.ErrNone},
|
||||
{"writer put versioning", "WRITERKEY", "writersecret000000000000000000001", "", "versioning", s3_constants.ACTION_WRITE, s3err.ErrAccessDenied},
|
||||
{"writer put versioning with prefix", "WRITERKEY", "writersecret000000000000000000001", "", "versioning&prefix=x", s3_constants.ACTION_WRITE, s3err.ErrAccessDenied},
|
||||
{"writer put lifecycle with prefix", "WRITERKEY", "writersecret000000000000000000001", "", "lifecycle&prefix=x", s3_constants.ACTION_WRITE, s3err.ErrAccessDenied},
|
||||
{"writer list with prefix", "WRITERKEY", "writersecret000000000000000000001", "", "list-type=2&prefix=x", s3_constants.ACTION_LIST, s3err.ErrNone},
|
||||
{"policywriter put object", "POLICYKEY", "policysecret00000000000000000001", "key", "", s3_constants.ACTION_WRITE, s3err.ErrNone},
|
||||
{"policywriter put versioning with prefix", "POLICYKEY", "policysecret00000000000000000001", "", "versioning&prefix=x", s3_constants.ACTION_WRITE, s3err.ErrAccessDenied},
|
||||
{"uploadreader lists uploads under prefix", "UPREADERKEY", "upreadersecret00000000000000001", "", "uploads&prefix=uploads/foo", s3_constants.ACTION_READ, s3err.ErrNone},
|
||||
{"uploadreader cannot list outside prefix", "UPREADERKEY", "upreadersecret00000000000000001", "", "uploads&prefix=other/", s3_constants.ACTION_READ, s3err.ErrAccessDenied},
|
||||
{"uploadlister lists uploads", "UPLISTERKEY", "uplistersecret00000000000000001", "", "uploads&prefix=x", s3_constants.ACTION_READ, s3err.ErrNone},
|
||||
{"getonly cannot list uploads", "GETONLYKEY", "getonlysecret0000000000000000001", "", "uploads&prefix=x", s3_constants.ACTION_READ, s3err.ErrAccessDenied},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
url := "http://localhost:8333/cache"
|
||||
if tc.object != "" {
|
||||
url += "/" + tc.object
|
||||
}
|
||||
if tc.query != "" {
|
||||
url += "?" + tc.query
|
||||
}
|
||||
r := httptest.NewRequest(http.MethodPut, url, nil)
|
||||
if tc.action == s3_constants.ACTION_LIST || tc.action == s3_constants.ACTION_READ {
|
||||
r.Method = http.MethodGet
|
||||
}
|
||||
r = mux.SetURLVars(r, map[string]string{"bucket": "cache", "object": tc.object})
|
||||
require.NoError(t, signRawHTTPRequest(context.Background(), r, tc.access, tc.secret, "us-east-1"))
|
||||
|
||||
_, errCode := iam.authRequest(r, tc.action)
|
||||
assert.Equal(t, tc.want, errCode)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The admin explicit-deny path resolves the same action and resource the
|
||||
// policy engine sees, so a promoted prefix must not hide a listing variant:
|
||||
// ?uploads resolves s3:ListBucketMultipartUploads on the bucket ARN, and
|
||||
// ?versions resolves s3:ListBucketVersions, both at bucket level.
|
||||
func TestResolveS3AuthTarget_BucketListings(t *testing.T) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
url string
|
||||
action Action
|
||||
object string
|
||||
wantAction string
|
||||
wantResource string
|
||||
}{
|
||||
{"uploads listing keeps its action", "/cache?uploads&prefix=uploads/", s3_constants.ACTION_READ, "uploads/",
|
||||
s3_constants.S3_ACTION_LIST_MULTIPART_UPLOADS, "arn:aws:s3:::cache"},
|
||||
{"versions listing keeps its action", "/cache?versions&prefix=a/", s3_constants.ACTION_LIST, "a/",
|
||||
s3_constants.S3_ACTION_LIST_BUCKET_VERSIONS, "arn:aws:s3:::cache"},
|
||||
{"plain list keeps its action", "/cache?list-type=2&prefix=a/", s3_constants.ACTION_LIST, "a/",
|
||||
s3_constants.S3_ACTION_LIST_BUCKET, "arn:aws:s3:::cache"},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
r := httptest.NewRequest(http.MethodGet, tt.url, nil)
|
||||
r = mux.SetURLVars(r, map[string]string{"bucket": "cache"})
|
||||
action, resource := resolveS3AuthTarget(tt.action, "cache", tt.object, r)
|
||||
assert.Equal(t, tt.wantAction, action)
|
||||
assert.Equal(t, tt.wantResource, resource)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -277,3 +277,66 @@ func TestLoadIAMManagerFromConfig_ExplicitFileEnforcesUserScopedPolicy(t *testin
|
||||
assert.NoError(t, err)
|
||||
assert.True(t, allowed, "user-scoped bucket creation should be allowed")
|
||||
}
|
||||
|
||||
func TestLoadIAMManagerFromConfig_HonorsOIDCProviderStore(t *testing.T) {
|
||||
// The documented oidcProviderStore key must reach the IAM manager; without
|
||||
// it, providers created through the IAM API live in one gateway's memory.
|
||||
cases := []struct {
|
||||
name string
|
||||
store string
|
||||
filer bool
|
||||
}{
|
||||
{"absent keeps memory", ``, false},
|
||||
{"filer persists", `,"oidcProviderStore":{"storeType":"filer"}`, true},
|
||||
{"no config file persists", "no-file", true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
configPath := ""
|
||||
if tc.store != "no-file" {
|
||||
configPath = filepath.Join(t.TempDir(), "iam_config.json")
|
||||
configContent := `{"sts":{"providers":[]},"policy":{"storeType":"memory","defaultEffect":"Deny"}` + tc.store + `}`
|
||||
assert.NoError(t, os.WriteFile(configPath, []byte(configContent), 0644))
|
||||
}
|
||||
|
||||
manager, err := loadIAMManagerFromConfig(configPath, func() string { return "localhost:8888" }, func() string { return "oidc-store-signing-key" })
|
||||
assert.NoError(t, err)
|
||||
_, isFiler := manager.GetOIDCProviderStore().(*integration.FilerOIDCProviderStore)
|
||||
assert.Equal(t, tc.filer, isFiler)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoadIAMManagerFromConfig_HonorsRoleStoreAndMarksStaticRoles(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
store string
|
||||
filer bool
|
||||
}{
|
||||
{"absent keeps memory", ``, false},
|
||||
{"filer persists", `,"roleStore":{"storeType":"filer"}`, true},
|
||||
{"no config file persists", "no-file", true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
configPath := ""
|
||||
if tc.store != "no-file" {
|
||||
configPath = filepath.Join(t.TempDir(), "iam_config.json")
|
||||
configContent := `{"sts":{"providers":[]},"policy":{"storeType":"memory","defaultEffect":"Deny"},` +
|
||||
`"roles":[{"roleName":"from-file","trustPolicy":{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Federated":"https://issuer.example"},"Action":["sts:AssumeRoleWithWebIdentity"]}]}}]` +
|
||||
tc.store + `}`
|
||||
assert.NoError(t, os.WriteFile(configPath, []byte(configContent), 0644))
|
||||
}
|
||||
|
||||
manager, err := loadIAMManagerFromConfig(configPath, func() string { return "localhost:8888" }, func() string { return "role-store-signing-key" })
|
||||
assert.NoError(t, err)
|
||||
_, inMemory := manager.GetRoleStore().(*integration.MemoryRoleStore)
|
||||
assert.Equal(t, tc.filer, !inMemory)
|
||||
if !tc.filer {
|
||||
role, err := manager.GetRole(context.Background(), "from-file")
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, integration.RoleSourceStaticConfig, role.Source)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,11 +1,17 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/integration"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/sts"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3err"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
@@ -106,6 +112,152 @@ func TestEvaluateIAMPolicies_ListBucketVersionsWithPrefix(t *testing.T) {
|
||||
"s3:ListBucketVersions must still resolve when listing with a prefix")
|
||||
}
|
||||
|
||||
// GET ?uploads routes under ACTION_READ, not ACTION_LIST, but it is a bucket
|
||||
// listing: a promoted prefix must not resolve it to s3:GetObject, and only
|
||||
// s3:ListBucketMultipartUploads on the bucket ARN may allow it.
|
||||
func TestEvaluateIAMPolicies_ListMultipartUploadsWithPrefix(t *testing.T) {
|
||||
const bucket = "test-bucket"
|
||||
|
||||
iam := &IdentityAccessManagement{}
|
||||
require.NoError(t, iam.PutPolicy("list-uploads", mustPolicy(t, map[string]any{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]any{{
|
||||
"Effect": "Allow",
|
||||
"Action": "s3:ListBucketMultipartUploads",
|
||||
"Resource": "arn:aws:s3:::" + bucket,
|
||||
}},
|
||||
})))
|
||||
require.NoError(t, iam.PutPolicy("get-object", mustPolicy(t, map[string]any{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": []map[string]any{{
|
||||
"Effect": "Allow",
|
||||
"Action": "s3:GetObject",
|
||||
"Resource": "arn:aws:s3:::" + bucket + "/*",
|
||||
}},
|
||||
})))
|
||||
|
||||
uploadsReader := &Identity{
|
||||
Name: "dave",
|
||||
Account: &AccountAdmin,
|
||||
PolicyNames: []string{"list-uploads"},
|
||||
Credentials: []*Credential{{AccessKey: "AKIAEXAMPLE", SecretKey: "secret"}},
|
||||
}
|
||||
getReader := &Identity{
|
||||
Name: "erin",
|
||||
Account: &AccountAdmin,
|
||||
PolicyNames: []string{"get-object"},
|
||||
Credentials: []*Credential{{AccessKey: "AKIAEXAMPLE", SecretKey: "secret"}},
|
||||
}
|
||||
|
||||
r := httptest.NewRequest("GET", "/"+bucket+"?uploads&prefix=uploads/", nil)
|
||||
require.True(t, iam.evaluateIAMPolicies(r, uploadsReader, s3_constants.ACTION_READ, bucket, "uploads/"),
|
||||
"s3:ListBucketMultipartUploads on the bucket must allow the uploads listing")
|
||||
require.False(t, iam.evaluateIAMPolicies(r, getReader, s3_constants.ACTION_READ, bucket, "uploads/"),
|
||||
"s3:GetObject must not satisfy the uploads listing")
|
||||
}
|
||||
|
||||
// The IAM-integration authorizer must resolve the listing variant the same way
|
||||
// evaluateIAMPolicies does: a prefix promoted into the object argument is not
|
||||
// part of the request URL, so ?versions&prefix=... still resolves to
|
||||
// s3:ListBucketVersions and an s3:ListBucket grant must not cover it.
|
||||
func TestAuthorizeAction_ListVersionsWithPromotedPrefix(t *testing.T) {
|
||||
const bucket = "test-bucket"
|
||||
|
||||
ctx := context.Background()
|
||||
iamManager := integration.NewIAMManager()
|
||||
require.NoError(t, iamManager.Initialize(&integration.IAMConfig{
|
||||
STS: &sts.STSConfig{
|
||||
TokenDuration: sts.FlexibleDuration{Duration: time.Hour},
|
||||
MaxSessionLength: sts.FlexibleDuration{Duration: 12 * time.Hour},
|
||||
Issuer: "test-sts",
|
||||
SigningKey: []byte("test-signing-key-32-characters-long"),
|
||||
},
|
||||
Policy: &policy.PolicyEngineConfig{DefaultEffect: "Deny", StoreType: "memory"},
|
||||
Roles: &integration.RoleStoreConfig{StoreType: "memory"},
|
||||
}, func() string { return "localhost:8888" }))
|
||||
|
||||
require.NoError(t, iamManager.CreatePolicy(ctx, "", "ListBucketOnly", &policy.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy.Statement{{
|
||||
Effect: "Allow",
|
||||
Action: []string{"s3:ListBucket"},
|
||||
Resource: []string{"arn:aws:s3:::" + bucket},
|
||||
Condition: map[string]map[string]interface{}{"StringLike": {"s3:prefix": "b/*"}},
|
||||
}},
|
||||
}))
|
||||
require.NoError(t, iamManager.CreatePolicy(ctx, "", "ListVersionsOnly", &policy.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy.Statement{{
|
||||
Effect: "Allow",
|
||||
Action: []string{"s3:ListBucketVersions"},
|
||||
Resource: []string{"arn:aws:s3:::" + bucket},
|
||||
}},
|
||||
}))
|
||||
require.NoError(t, iamManager.CreatePolicy(ctx, "", "ListUploadsOnly", &policy.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy.Statement{{
|
||||
Effect: "Allow",
|
||||
Action: []string{"s3:ListBucketMultipartUploads"},
|
||||
Resource: []string{"arn:aws:s3:::" + bucket},
|
||||
}},
|
||||
}))
|
||||
require.NoError(t, iamManager.CreatePolicy(ctx, "", "GetObjectOnly", &policy.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy.Statement{{
|
||||
Effect: "Allow",
|
||||
Action: []string{"s3:GetObject"},
|
||||
Resource: []string{"arn:aws:s3:::" + bucket + "/*"},
|
||||
}},
|
||||
}))
|
||||
|
||||
s3iam := NewS3IAMIntegration(iamManager, "localhost:8888")
|
||||
reader := &IAMIdentity{
|
||||
Name: "reader",
|
||||
Principal: "arn:aws:iam::000000000000:user/reader",
|
||||
PolicyNames: []string{"ListBucketOnly"},
|
||||
}
|
||||
|
||||
versionsReq := httptest.NewRequest("GET", "/"+bucket+"?versions&prefix=b/", nil)
|
||||
// object carries the promoted prefix, matching authRequestWithAuthType
|
||||
require.Equal(t, s3err.ErrAccessDenied,
|
||||
s3iam.AuthorizeAction(ctx, reader, s3_constants.ACTION_LIST, bucket, "b/", versionsReq),
|
||||
"an s3:ListBucket grant must not cover ?versions listing")
|
||||
|
||||
listReq := httptest.NewRequest("GET", "/"+bucket+"?list-type=2&prefix=b/", nil)
|
||||
require.Equal(t, s3err.ErrNone,
|
||||
s3iam.AuthorizeAction(ctx, reader, s3_constants.ACTION_LIST, bucket, "b/", listReq),
|
||||
"s3:ListBucket with a matching s3:prefix still lists")
|
||||
|
||||
versionsReader := &IAMIdentity{
|
||||
Name: "versions-reader",
|
||||
Principal: "arn:aws:iam::000000000000:user/versions-reader",
|
||||
PolicyNames: []string{"ListVersionsOnly"},
|
||||
}
|
||||
require.Equal(t, s3err.ErrNone,
|
||||
s3iam.AuthorizeAction(ctx, versionsReader, s3_constants.ACTION_LIST, bucket, "b/", versionsReq),
|
||||
"s3:ListBucketVersions allows the versions listing")
|
||||
|
||||
// GET ?uploads routes under ACTION_READ; a promoted prefix must still
|
||||
// resolve it to s3:ListBucketMultipartUploads, not s3:GetObject.
|
||||
uploadsReq := httptest.NewRequest("GET", "/"+bucket+"?uploads&prefix=b/", nil)
|
||||
uploadsReader := &IAMIdentity{
|
||||
Name: "uploads-reader",
|
||||
Principal: "arn:aws:iam::000000000000:user/uploads-reader",
|
||||
PolicyNames: []string{"ListUploadsOnly"},
|
||||
}
|
||||
require.Equal(t, s3err.ErrNone,
|
||||
s3iam.AuthorizeAction(ctx, uploadsReader, s3_constants.ACTION_READ, bucket, "b/", uploadsReq),
|
||||
"s3:ListBucketMultipartUploads allows the uploads listing")
|
||||
getReader := &IAMIdentity{
|
||||
Name: "get-reader",
|
||||
Principal: "arn:aws:iam::000000000000:user/get-reader",
|
||||
PolicyNames: []string{"GetObjectOnly"},
|
||||
}
|
||||
require.Equal(t, s3err.ErrAccessDenied,
|
||||
s3iam.AuthorizeAction(ctx, getReader, s3_constants.ACTION_READ, bucket, "b/", uploadsReq),
|
||||
"s3:GetObject must not satisfy the uploads listing")
|
||||
}
|
||||
|
||||
func mustPolicy(t *testing.T, doc map[string]any) string {
|
||||
t.Helper()
|
||||
b, err := json.Marshal(doc)
|
||||
|
||||
@@ -33,9 +33,11 @@ func ResolveS3Action(r *http.Request, baseAction string, bucket string, object s
|
||||
return baseAction
|
||||
}
|
||||
|
||||
// Object Lock actions are checked on top of another operation's request
|
||||
// shape (e.g. BypassGovernanceRetention on a versioned DELETE), so the
|
||||
// shape must not re-derive them.
|
||||
// Dedicated object-lock actions already name the operation — a query
|
||||
// parameter must not re-map them. In particular the governance-bypass
|
||||
// check authorizes against a synthetic DELETE ?versionId request, whose
|
||||
// shape would otherwise resolve to s3:DeleteObjectVersion and satisfy
|
||||
// the bypass check with the delete-version permission alone.
|
||||
switch baseAction {
|
||||
case s3_constants.ACTION_BYPASS_GOVERNANCE_RETENTION,
|
||||
s3_constants.ACTION_GET_OBJECT_RETENTION,
|
||||
|
||||
@@ -114,89 +114,6 @@ func TestResolveS3Action_AttributesBeforeVersionId(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestResolveS3Action_ObjectLockActionsIgnoreRequestShape(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
query string
|
||||
method string
|
||||
baseAction string
|
||||
object string
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "bypass on versioned delete",
|
||||
query: "versionId=abc123",
|
||||
method: http.MethodDelete,
|
||||
baseAction: s3_constants.ACTION_BYPASS_GOVERNANCE_RETENTION,
|
||||
object: "key",
|
||||
want: s3_constants.S3_ACTION_BYPASS_GOVERNANCE,
|
||||
},
|
||||
{
|
||||
name: "bypass on batch delete",
|
||||
query: "delete",
|
||||
method: http.MethodPost,
|
||||
baseAction: s3_constants.ACTION_BYPASS_GOVERNANCE_RETENTION,
|
||||
object: "key",
|
||||
want: s3_constants.S3_ACTION_BYPASS_GOVERNANCE,
|
||||
},
|
||||
{
|
||||
name: "get retention with versionId",
|
||||
query: "retention&versionId=abc123",
|
||||
method: http.MethodGet,
|
||||
baseAction: s3_constants.ACTION_GET_OBJECT_RETENTION,
|
||||
object: "key",
|
||||
want: s3_constants.S3_ACTION_GET_OBJECT_RETENTION,
|
||||
},
|
||||
{
|
||||
name: "get legal hold with versionId",
|
||||
query: "legal-hold&versionId=abc123",
|
||||
method: http.MethodGet,
|
||||
baseAction: s3_constants.ACTION_GET_OBJECT_LEGAL_HOLD,
|
||||
object: "key",
|
||||
want: s3_constants.S3_ACTION_GET_OBJECT_LEGAL_HOLD,
|
||||
},
|
||||
{
|
||||
name: "put retention with versionId",
|
||||
query: "retention&versionId=abc123",
|
||||
method: http.MethodPut,
|
||||
baseAction: s3_constants.ACTION_PUT_OBJECT_RETENTION,
|
||||
object: "key",
|
||||
want: s3_constants.S3_ACTION_PUT_OBJECT_RETENTION,
|
||||
},
|
||||
{
|
||||
name: "put legal hold with versionId",
|
||||
query: "legal-hold&versionId=abc123",
|
||||
method: http.MethodPut,
|
||||
baseAction: s3_constants.ACTION_PUT_OBJECT_LEGAL_HOLD,
|
||||
object: "key",
|
||||
want: s3_constants.S3_ACTION_PUT_OBJECT_LEGAL_HOLD,
|
||||
},
|
||||
{
|
||||
name: "get bucket object lock config",
|
||||
query: "object-lock",
|
||||
method: http.MethodGet,
|
||||
baseAction: s3_constants.ACTION_GET_BUCKET_OBJECT_LOCK_CONFIG,
|
||||
want: s3_constants.S3_ACTION_GET_BUCKET_OBJECT_LOCK,
|
||||
},
|
||||
{
|
||||
name: "put bucket object lock config",
|
||||
query: "object-lock",
|
||||
method: http.MethodPut,
|
||||
baseAction: s3_constants.ACTION_PUT_BUCKET_OBJECT_LOCK_CONFIG,
|
||||
want: s3_constants.S3_ACTION_PUT_BUCKET_OBJECT_LOCK,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
r, _ := http.NewRequest(tt.method, "http://localhost/bucket/"+tt.object+"?"+tt.query, nil)
|
||||
if got := ResolveS3Action(r, tt.baseAction, "bucket", tt.object); got != tt.want {
|
||||
t.Errorf("ResolveS3Action() = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Bucket subresources registered with ACTION_ADMIN must resolve to their own
|
||||
// S3 actions so a policy granting one of them does not need s3:*, and so no
|
||||
// broader grant sweeps them in.
|
||||
@@ -295,6 +212,47 @@ func TestResolveS3Action_Quota(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Dedicated object-lock actions already name the operation being authorized;
|
||||
// competing query parameters must not re-map them. Notably the synthetic
|
||||
// DELETE ?versionId request behind the governance-bypass check must stay
|
||||
// s3:BypassGovernanceRetention rather than resolving to s3:DeleteObjectVersion.
|
||||
func TestResolveS3ActionDedicatedObjectLockActions(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
method string
|
||||
object string
|
||||
query string
|
||||
baseAction string
|
||||
want string
|
||||
}{
|
||||
{"bypass on versioned delete shape", http.MethodDelete, "key", "versionId=abc123",
|
||||
s3_constants.ACTION_BYPASS_GOVERNANCE_RETENTION, s3_constants.S3_ACTION_BYPASS_GOVERNANCE},
|
||||
{"bypass on batch delete shape", http.MethodPost, "", "delete",
|
||||
s3_constants.ACTION_BYPASS_GOVERNANCE_RETENTION, s3_constants.S3_ACTION_BYPASS_GOVERNANCE},
|
||||
{"get retention with versionId", http.MethodGet, "key", "retention&versionId=abc123",
|
||||
s3_constants.ACTION_GET_OBJECT_RETENTION, s3_constants.S3_ACTION_GET_OBJECT_RETENTION},
|
||||
{"put retention with versionId", http.MethodPut, "key", "retention&versionId=abc123",
|
||||
s3_constants.ACTION_PUT_OBJECT_RETENTION, s3_constants.S3_ACTION_PUT_OBJECT_RETENTION},
|
||||
{"get legal hold with versionId", http.MethodGet, "key", "legal-hold&versionId=abc123",
|
||||
s3_constants.ACTION_GET_OBJECT_LEGAL_HOLD, s3_constants.S3_ACTION_GET_OBJECT_LEGAL_HOLD},
|
||||
{"put legal hold with versionId", http.MethodPut, "key", "legal-hold&versionId=abc123",
|
||||
s3_constants.ACTION_PUT_OBJECT_LEGAL_HOLD, s3_constants.S3_ACTION_PUT_OBJECT_LEGAL_HOLD},
|
||||
{"get object-lock config", http.MethodGet, "", "object-lock&versioning",
|
||||
s3_constants.ACTION_GET_BUCKET_OBJECT_LOCK_CONFIG, s3_constants.S3_ACTION_GET_BUCKET_OBJECT_LOCK},
|
||||
{"put object-lock config", http.MethodPut, "", "object-lock",
|
||||
s3_constants.ACTION_PUT_BUCKET_OBJECT_LOCK_CONFIG, s3_constants.S3_ACTION_PUT_BUCKET_OBJECT_LOCK},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
r, _ := http.NewRequest(tt.method, "http://localhost/bucket/"+tt.object+"?"+tt.query, nil)
|
||||
if got := ResolveS3Action(r, tt.baseAction, "bucket", tt.object); got != tt.want {
|
||||
t.Errorf("ResolveS3Action() = %q, want %q", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A base action naming another service carries no S3 request shape, so a query
|
||||
// parameter on the request must not redirect it to an S3 action.
|
||||
func TestResolveS3ActionKeepsNonS3Service(t *testing.T) {
|
||||
|
||||
@@ -2,6 +2,7 @@ package s3api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
@@ -202,3 +203,57 @@ func TestContentEncodingWithOtherHeaders(t *testing.T) {
|
||||
assert.Equal(t, "max-age=3600", getResp.Header().Get("Cache-Control"))
|
||||
assert.Equal(t, "attachment; filename=test.txt", getResp.Header().Get("Content-Disposition"))
|
||||
}
|
||||
|
||||
// TestContentEncodingDropsAwsChunked verifies that aws-chunked, the SigV4
|
||||
// streaming framing of the request body, is not stored with the object, also
|
||||
// when the encodings come in separate Content-Encoding fields
|
||||
func TestContentEncodingDropsAwsChunked(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
fields []string
|
||||
stored string
|
||||
}{
|
||||
{"last", []string{"gzip, aws-chunked"}, "gzip"},
|
||||
{"first", []string{"aws-chunked, gzip"}, "gzip"},
|
||||
{"no spaces", []string{"aws-chunked,gzip,br"}, "gzip, br"},
|
||||
{"alone", []string{"aws-chunked"}, ""},
|
||||
{"capitals", []string{"AWS-Chunked"}, ""},
|
||||
{"twice", []string{"aws-chunked, aws-chunked"}, ""},
|
||||
{"separate fields", []string{"aws-chunked", "gzip"}, "gzip"},
|
||||
{"separate fields, alone", []string{"aws-chunked", "aws-chunked"}, ""},
|
||||
{"without aws-chunked", []string{"deflate, gzip"}, "deflate, gzip"},
|
||||
{"without aws-chunked, separate fields", []string{"deflate", "gzip"}, "deflate, gzip"},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert.Equal(t, tc.stored, storedContentEncoding(tc.fields))
|
||||
|
||||
// CreateMultipartUpload
|
||||
putReq := httptest.NewRequest("PUT", "/test-bucket/test-object.txt", bytes.NewBufferString("body"))
|
||||
for _, field := range tc.fields {
|
||||
putReq.Header.Add("Content-Encoding", field)
|
||||
}
|
||||
metadata, errCode := ParseS3Metadata(putReq, nil, false)
|
||||
require.Equal(t, 0, int(errCode))
|
||||
if tc.stored == "" {
|
||||
assert.NotContains(t, metadata, "Content-Encoding")
|
||||
} else {
|
||||
assert.Equal(t, []byte(tc.stored), metadata["Content-Encoding"])
|
||||
}
|
||||
|
||||
// CopyObject with the REPLACE metadata directive
|
||||
copyReq := http.Header{}
|
||||
for _, field := range tc.fields {
|
||||
copyReq.Add("Content-Encoding", field)
|
||||
}
|
||||
metadata, err := processMetadataBytes(copyReq, map[string][]byte{"Content-Encoding": []byte("br")}, true, false)
|
||||
require.NoError(t, err)
|
||||
if tc.stored == "" {
|
||||
assert.NotContains(t, metadata, "Content-Encoding")
|
||||
} else {
|
||||
assert.Equal(t, []byte(tc.stored), metadata["Content-Encoding"])
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -222,7 +222,7 @@ func (s3iam *S3IAMIntegration) AuthorizeAction(ctx context.Context, identity *IA
|
||||
// resource ARN stays at bucket level (matching AWS ListBucket semantics).
|
||||
// See https://github.com/seaweedfs/seaweedfs/issues/8969
|
||||
resourceObjectKey := objectKey
|
||||
if action == "List" {
|
||||
if isBucketListingRequest(r, action) {
|
||||
listPrefix := r.URL.Query().Get("prefix")
|
||||
if listPrefix != "" {
|
||||
requestContext["s3:prefix"] = listPrefix
|
||||
@@ -258,8 +258,10 @@ func (s3iam *S3IAMIntegration) AuthorizeAction(ctx context.Context, identity *IA
|
||||
}
|
||||
}
|
||||
|
||||
// Determine the specific S3 action based on the HTTP request details
|
||||
specificAction := ResolveS3Action(r, string(action), bucket, objectKey)
|
||||
// Determine the specific S3 action based on the HTTP request details. The
|
||||
// prefix promoted into objectKey is not part of the URL; resolve against
|
||||
// the bucket-level object so ?versions and ?uploads keep their own action.
|
||||
specificAction := ResolveS3Action(r, string(action), bucket, resourceObjectKey)
|
||||
|
||||
// Create action request
|
||||
actionRequest := &integration.ActionRequest{
|
||||
|
||||
@@ -30,7 +30,7 @@ func ParseS3Metadata(r *http.Request, existing map[string][]byte, isReplace bool
|
||||
}
|
||||
|
||||
// Content-Encoding (standard HTTP header used by S3)
|
||||
if ce := r.Header.Get("Content-Encoding"); ce != "" {
|
||||
if ce := storedContentEncoding(r.Header.Values("Content-Encoding")); ce != "" {
|
||||
metadata["Content-Encoding"] = []byte(ce)
|
||||
}
|
||||
|
||||
@@ -108,3 +108,28 @@ func ParseS3Metadata(r *http.Request, existing map[string][]byte, isReplace bool
|
||||
|
||||
return metadata, s3err.ErrNone
|
||||
}
|
||||
|
||||
// storedContentEncoding returns the Content-Encoding to keep with an object,
|
||||
// from the values of the request's Content-Encoding fields, which it combines
|
||||
// as one list. aws-chunked names the SigV4 streaming framing of the request
|
||||
// body, which is decoded on upload, so S3 does not store it: "gzip,
|
||||
// aws-chunked" is kept as "gzip", and "aws-chunked" alone as no
|
||||
// Content-Encoding at all.
|
||||
func storedContentEncoding(values []string) string {
|
||||
value := strings.Join(values, ", ")
|
||||
var kept []string
|
||||
chunked := false
|
||||
for _, encoding := range strings.Split(value, ",") {
|
||||
encoding = strings.TrimSpace(encoding)
|
||||
switch {
|
||||
case strings.EqualFold(encoding, "aws-chunked"):
|
||||
chunked = true
|
||||
case encoding != "":
|
||||
kept = append(kept, encoding)
|
||||
}
|
||||
}
|
||||
if !chunked {
|
||||
return value
|
||||
}
|
||||
return strings.Join(kept, ", ")
|
||||
}
|
||||
@@ -0,0 +1,343 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
type fakeBucketDeleteFiler struct {
|
||||
filer_pb.UnimplementedSeaweedFilerServer
|
||||
entriesByDir map[string][]*filer_pb.Entry
|
||||
deleteReq *filer_pb.DeleteEntryRequest
|
||||
}
|
||||
|
||||
func (f *fakeBucketDeleteFiler) LookupDirectoryEntry(ctx context.Context, req *filer_pb.LookupDirectoryEntryRequest) (*filer_pb.LookupDirectoryEntryResponse, error) {
|
||||
entries, ok := f.entriesByDir[req.Directory]
|
||||
if !ok {
|
||||
return nil, filer_pb.ErrNotFound
|
||||
}
|
||||
for _, e := range entries {
|
||||
if e.Name == req.Name {
|
||||
return &filer_pb.LookupDirectoryEntryResponse{Entry: e}, nil
|
||||
}
|
||||
}
|
||||
return nil, filer_pb.ErrNotFound
|
||||
}
|
||||
|
||||
func (f *fakeBucketDeleteFiler) ListEntries(req *filer_pb.ListEntriesRequest, stream filer_pb.SeaweedFiler_ListEntriesServer) error {
|
||||
entries := f.entriesByDir[req.Directory]
|
||||
if inPrefix := req.Prefix; inPrefix != "" && inPrefix != "/" {
|
||||
filtered := make([]*filer_pb.Entry, 0)
|
||||
for _, e := range entries {
|
||||
if strings.HasPrefix(e.Name, inPrefix) {
|
||||
filtered = append(filtered, e)
|
||||
}
|
||||
}
|
||||
entries = filtered
|
||||
}
|
||||
if req.StartFromFileName != "" {
|
||||
filtered := make([]*filer_pb.Entry, 0)
|
||||
for _, e := range entries {
|
||||
if e.Name > req.StartFromFileName || (req.InclusiveStartFrom && e.Name == req.StartFromFileName) {
|
||||
filtered = append(filtered, e)
|
||||
}
|
||||
}
|
||||
entries = filtered
|
||||
}
|
||||
if req.Limit > 0 && int(req.Limit) < len(entries) {
|
||||
entries = entries[:req.Limit]
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if err := stream.Send(&filer_pb.ListEntriesResponse{Entry: entry}); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (f *fakeBucketDeleteFiler) DeleteEntry(ctx context.Context, req *filer_pb.DeleteEntryRequest) (*filer_pb.DeleteEntryResponse, error) {
|
||||
f.deleteReq = req
|
||||
return &filer_pb.DeleteEntryResponse{}, nil
|
||||
}
|
||||
|
||||
func newBucketDeleteTestServer(t *testing.T, f *fakeBucketDeleteFiler, allowDeleteBucketNotEmpty bool) *S3ApiServer {
|
||||
t.Helper()
|
||||
s3a := newFailoverTestServer(t, startFakeFiler(t, f))
|
||||
s3a.option.BucketsPath = "/buckets"
|
||||
s3a.option.AllowDeleteBucketNotEmpty = allowDeleteBucketNotEmpty
|
||||
s3a.bucketConfigCache = NewBucketConfigCache(time.Minute)
|
||||
s3a.iam = &IdentityAccessManagement{}
|
||||
return s3a
|
||||
}
|
||||
|
||||
func TestBucketHasUserObjects_EmptyDirectories(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
entriesByDir map[string][]*filer_pb.Entry
|
||||
wantHasUser bool
|
||||
}{
|
||||
{
|
||||
name: "completely empty bucket",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {},
|
||||
},
|
||||
wantHasUser: false,
|
||||
},
|
||||
{
|
||||
name: "bucket with root file",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {
|
||||
{Name: "file.txt", IsDirectory: false},
|
||||
},
|
||||
},
|
||||
wantHasUser: true,
|
||||
},
|
||||
{
|
||||
name: "bucket with leftover empty directory from rm --recursive",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {
|
||||
{Name: "data", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
|
||||
},
|
||||
"/buckets/b/data": {},
|
||||
},
|
||||
wantHasUser: false,
|
||||
},
|
||||
{
|
||||
name: "bucket with nested leftover empty directories",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {
|
||||
{Name: "data", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
|
||||
},
|
||||
"/buckets/b/data": {
|
||||
{Name: "2026", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
|
||||
},
|
||||
"/buckets/b/data/2026": {},
|
||||
},
|
||||
wantHasUser: false,
|
||||
},
|
||||
{
|
||||
name: "bucket with nested directory containing a file",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {
|
||||
{Name: "data", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
|
||||
},
|
||||
"/buckets/b/data": {
|
||||
{Name: "2026", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
|
||||
},
|
||||
"/buckets/b/data/2026": {
|
||||
{Name: "report.pdf", IsDirectory: false},
|
||||
},
|
||||
},
|
||||
wantHasUser: true,
|
||||
},
|
||||
{
|
||||
name: "bucket with explicit directory object (MIME set)",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {
|
||||
{Name: "logs", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: "application/x-directory"}},
|
||||
},
|
||||
"/buckets/b/logs": {},
|
||||
},
|
||||
wantHasUser: true,
|
||||
},
|
||||
{
|
||||
name: "bucket with only reserved folders (.uploads, *.versions)",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {
|
||||
{Name: s3_constants.MultipartUploadsFolder, IsDirectory: true},
|
||||
{Name: "oldfile.txt" + s3_constants.VersionsFolder, IsDirectory: true},
|
||||
},
|
||||
},
|
||||
wantHasUser: false,
|
||||
},
|
||||
{
|
||||
name: "nested versions-named directories are internal",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {
|
||||
{Name: "logs", IsDirectory: true},
|
||||
},
|
||||
"/buckets/b/logs": {
|
||||
{Name: "foo" + s3_constants.VersionsFolder, IsDirectory: true},
|
||||
},
|
||||
"/buckets/b/logs/foo" + s3_constants.VersionsFolder: {
|
||||
{Name: "v1", IsDirectory: false},
|
||||
},
|
||||
},
|
||||
wantHasUser: false,
|
||||
},
|
||||
{
|
||||
name: "nested uploads-named directories are internal",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {
|
||||
{Name: "data", IsDirectory: true},
|
||||
},
|
||||
"/buckets/b/data": {
|
||||
{Name: s3_constants.MultipartUploadsFolder, IsDirectory: true},
|
||||
},
|
||||
"/buckets/b/data/" + s3_constants.MultipartUploadsFolder: {
|
||||
{Name: "part-1", IsDirectory: false},
|
||||
},
|
||||
},
|
||||
wantHasUser: false,
|
||||
},
|
||||
{
|
||||
name: "directory object with a reserved name counts",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {
|
||||
{Name: "data", IsDirectory: true},
|
||||
},
|
||||
"/buckets/b/data": {
|
||||
{Name: s3_constants.MultipartUploadsFolder, IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: s3_constants.FolderMimeType}},
|
||||
},
|
||||
},
|
||||
wantHasUser: true,
|
||||
},
|
||||
{
|
||||
name: "file with a reserved name counts",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {
|
||||
{Name: "dir", IsDirectory: true},
|
||||
},
|
||||
"/buckets/b/dir": {
|
||||
{Name: "data" + s3_constants.VersionsFolder, IsDirectory: false},
|
||||
},
|
||||
},
|
||||
wantHasUser: true,
|
||||
},
|
||||
{
|
||||
name: "file with backslash in name",
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {
|
||||
{Name: `a\b`, IsDirectory: false},
|
||||
},
|
||||
},
|
||||
wantHasUser: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
f := &fakeBucketDeleteFiler{entriesByDir: tc.entriesByDir}
|
||||
s3a := newBucketDeleteTestServer(t, f, false)
|
||||
|
||||
got, err := s3a.bucketHasUserObjects("b")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, tc.wantHasUser, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBucketHasUserObjects_DeepEmptyChain(t *testing.T) {
|
||||
entriesByDir := map[string][]*filer_pb.Entry{
|
||||
"/buckets/b": {{Name: "d0", IsDirectory: true}},
|
||||
}
|
||||
dir := "/buckets/b/d0"
|
||||
for i := 1; i < 500; i++ {
|
||||
child := fmt.Sprintf("d%d", i)
|
||||
entriesByDir[dir] = []*filer_pb.Entry{{Name: child, IsDirectory: true}}
|
||||
dir = dir + "/" + child
|
||||
}
|
||||
entriesByDir[dir] = []*filer_pb.Entry{}
|
||||
|
||||
f := &fakeBucketDeleteFiler{entriesByDir: entriesByDir}
|
||||
s3a := newBucketDeleteTestServer(t, f, false)
|
||||
|
||||
got, err := s3a.bucketHasUserObjects("b")
|
||||
require.NoError(t, err)
|
||||
assert.False(t, got)
|
||||
}
|
||||
|
||||
func TestDeleteBucketHandler_EmptyDirectoriesAllowedWhenNotEmptyFalse(t *testing.T) {
|
||||
// A bucket that holds only an empty directory leftover from deleted objects
|
||||
// must succeed when AllowDeleteBucketNotEmpty is false.
|
||||
f := &fakeBucketDeleteFiler{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets": {
|
||||
{Name: "repro-bucket", IsDirectory: true},
|
||||
},
|
||||
"/buckets/repro-bucket": {
|
||||
{Name: "data", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
|
||||
},
|
||||
"/buckets/repro-bucket/data": {},
|
||||
},
|
||||
}
|
||||
s3a := newBucketDeleteTestServer(t, f, false)
|
||||
s3a.bucketConfigCache.Set("repro-bucket", &BucketConfig{Name: "repro-bucket"})
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/repro-bucket", nil)
|
||||
req = mux.SetURLVars(req, map[string]string{"bucket": "repro-bucket"})
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
s3a.DeleteBucketHandler(rr, req)
|
||||
|
||||
assert.Equal(t, http.StatusNoContent, rr.Code, "deleting bucket with only empty directory must succeed: %s", rr.Body.String())
|
||||
assert.NotNil(t, f.deleteReq)
|
||||
assert.Equal(t, "/buckets", f.deleteReq.Directory)
|
||||
assert.Equal(t, "repro-bucket", f.deleteReq.Name)
|
||||
assert.True(t, f.deleteReq.IsRecursive)
|
||||
}
|
||||
|
||||
func TestDeleteBucketHandler_RefusesBucketWithFilesWhenNotEmptyFalse(t *testing.T) {
|
||||
f := &fakeBucketDeleteFiler{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets": {
|
||||
{Name: "non-empty-bucket", IsDirectory: true},
|
||||
},
|
||||
"/buckets/non-empty-bucket": {
|
||||
{Name: "data", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: ""}},
|
||||
},
|
||||
"/buckets/non-empty-bucket/data": {
|
||||
{Name: "hello.txt", IsDirectory: false},
|
||||
},
|
||||
},
|
||||
}
|
||||
s3a := newBucketDeleteTestServer(t, f, false)
|
||||
s3a.bucketConfigCache.Set("non-empty-bucket", &BucketConfig{Name: "non-empty-bucket"})
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/non-empty-bucket", nil)
|
||||
req = mux.SetURLVars(req, map[string]string{"bucket": "non-empty-bucket"})
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
s3a.DeleteBucketHandler(rr, req)
|
||||
|
||||
assert.Equal(t, http.StatusConflict, rr.Code)
|
||||
assert.Contains(t, rr.Body.String(), "<Code>BucketNotEmpty</Code>")
|
||||
assert.Nil(t, f.deleteReq, "delete request must not have been sent to filer")
|
||||
}
|
||||
|
||||
func TestDeleteBucketHandler_RefusesBucketWithDirectoryObjectWhenNotEmptyFalse(t *testing.T) {
|
||||
f := &fakeBucketDeleteFiler{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets": {
|
||||
{Name: "dir-obj-bucket", IsDirectory: true},
|
||||
},
|
||||
"/buckets/dir-obj-bucket": {
|
||||
{Name: "photos", IsDirectory: true, Attributes: &filer_pb.FuseAttributes{Mime: "application/x-directory"}},
|
||||
},
|
||||
"/buckets/dir-obj-bucket/photos": {},
|
||||
},
|
||||
}
|
||||
s3a := newBucketDeleteTestServer(t, f, false)
|
||||
s3a.bucketConfigCache.Set("dir-obj-bucket", &BucketConfig{Name: "dir-obj-bucket"})
|
||||
|
||||
req := httptest.NewRequest(http.MethodDelete, "/dir-obj-bucket", nil)
|
||||
req = mux.SetURLVars(req, map[string]string{"bucket": "dir-obj-bucket"})
|
||||
rr := httptest.NewRecorder()
|
||||
|
||||
s3a.DeleteBucketHandler(rr, req)
|
||||
|
||||
assert.Equal(t, http.StatusConflict, rr.Code)
|
||||
assert.Contains(t, rr.Body.String(), "<Code>BucketNotEmpty</Code>")
|
||||
assert.Nil(t, f.deleteReq, "delete request must not have been sent to filer")
|
||||
}
|
||||
@@ -503,31 +503,56 @@ func (s3a *S3ApiServer) DeleteBucketHandler(w http.ResponseWriter, r *http.Reque
|
||||
s3err.WriteEmptyResponse(w, r, http.StatusNoContent)
|
||||
}
|
||||
|
||||
// bucketHasUserObjects checks whether a bucket contains any non-special entries.
|
||||
// Special entries (.uploads, *.versions) are internal to S3 and don't count as user objects.
|
||||
// bucketHasUserObjects checks whether a bucket contains any user objects.
|
||||
// Empty directories left behind by deleted objects and internal folders
|
||||
// (.uploads, *.versions) do not count as user objects.
|
||||
func (s3a *S3ApiServer) bucketHasUserObjects(bucket string) (bool, error) {
|
||||
bucketPath := s3a.option.BucketsPath + "/" + bucket
|
||||
startFrom := ""
|
||||
// Start with a small batch — most non-empty buckets have a real object early.
|
||||
// If we only find special entries, switch to larger batches to page through quickly.
|
||||
limit := uint32(10)
|
||||
for {
|
||||
entries, isLast, err := s3a.list(bucketPath, "", startFrom, false, limit)
|
||||
if err != nil {
|
||||
return false, err
|
||||
}
|
||||
for _, entry := range entries {
|
||||
if entry.Name != s3_constants.MultipartUploadsFolder &&
|
||||
!strings.HasSuffix(entry.Name, s3_constants.VersionsFolder) {
|
||||
return true, nil
|
||||
return s3a.dirHasUserObjects(s3a.option.BucketsPath + "/" + bucket)
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) dirHasUserObjects(root string) (bool, error) {
|
||||
dirs := []string{root}
|
||||
for len(dirs) > 0 {
|
||||
dir := dirs[len(dirs)-1]
|
||||
dirs = dirs[:len(dirs)-1]
|
||||
startFrom := ""
|
||||
// Start with a small batch — most non-empty buckets have a real object
|
||||
// early; switch to larger batches to page through quickly.
|
||||
limit := uint32(10)
|
||||
for {
|
||||
entries, isLast, err := s3a.list(dir, "", startFrom, false, limit)
|
||||
if err != nil {
|
||||
if isFilerNotFound(err) {
|
||||
break // the directory was deleted between listing and walking it
|
||||
}
|
||||
return false, err
|
||||
}
|
||||
startFrom = entry.Name
|
||||
for _, entry := range entries {
|
||||
startFrom = entry.Name
|
||||
if entry.Name == "" || entry.Name == "." || entry.Name == ".." || strings.Contains(entry.Name, "/") {
|
||||
continue
|
||||
}
|
||||
if !entry.IsDirectory {
|
||||
return true, nil
|
||||
}
|
||||
// An explicit directory object counts even under a reserved name.
|
||||
if entry.IsDirectoryKeyObject() {
|
||||
return true, nil
|
||||
}
|
||||
// Internal folders are skipped by object listing at every level,
|
||||
// so a directory with a reserved name never counts.
|
||||
if isReservedDirectoryName(entry.Name) {
|
||||
continue
|
||||
}
|
||||
dirs = append(dirs, dir+"/"+entry.Name)
|
||||
}
|
||||
if isLast || len(entries) == 0 {
|
||||
break
|
||||
}
|
||||
limit = 1000
|
||||
}
|
||||
if isLast {
|
||||
return false, nil
|
||||
}
|
||||
limit = 1000
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
|
||||
// hasObjectsWithActiveLocks checks if any objects in the bucket have active retention or legal hold
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
iamlib "github.com/seaweedfs/seaweedfs/weed/iam"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/integration"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
@@ -225,6 +226,8 @@ func (e *EmbeddedIamApi) writeIamErrorResponse(w http.ResponseWriter, r *http.Re
|
||||
s3err.WriteXMLResponse(w, r, http.StatusNotImplemented, errorResp)
|
||||
case iam.ErrCodeDeleteConflictException:
|
||||
s3err.WriteXMLResponse(w, r, http.StatusConflict, errorResp)
|
||||
case iam.ErrCodeUnmodifiableEntityException:
|
||||
s3err.WriteXMLResponse(w, r, http.StatusBadRequest, errorResp)
|
||||
default:
|
||||
s3err.WriteXMLResponse(w, r, http.StatusInternalServerError, internalErrorResponse)
|
||||
}
|
||||
@@ -644,6 +647,20 @@ func (e *EmbeddedIamApi) DeletePolicy(ctx context.Context, values url.Values) (*
|
||||
}
|
||||
}
|
||||
}
|
||||
// Roles attach policies by name too; see integration.RolesAttachingPolicy,
|
||||
// including why a role only in a peer's IAM config file is not seen here.
|
||||
if mgr := e.oidcIAMManager(); mgr != nil && mgr.GetRoleStore() != nil {
|
||||
roles, err := integration.RolesAttachingPolicy(ctx, mgr.GetRoleStore(), policyName)
|
||||
if err != nil {
|
||||
return resp, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
}
|
||||
if len(roles) > 0 {
|
||||
return resp, &iamError{
|
||||
Code: iam.ErrCodeDeleteConflictException,
|
||||
Error: fmt.Errorf("policy %s is attached to role %s", policyName, roles[0]),
|
||||
}
|
||||
}
|
||||
}
|
||||
if err := e.credentialManager.DeletePolicy(ctx, policyName); err != nil {
|
||||
return resp, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
}
|
||||
@@ -2582,7 +2599,10 @@ func (e *EmbeddedIamApi) AuthIam(f http.HandlerFunc, _ Action) http.HandlerFunc
|
||||
}
|
||||
|
||||
// ExecuteAction executes an IAM action with the given values.
|
||||
// If skipPersist is true, the changed configuration is not saved to the persistent store.
|
||||
// If skipPersist is true, the changed S3ApiConfiguration is not saved to the
|
||||
// persistent store. OIDC provider and role actions do not change that
|
||||
// configuration: they write to the IAM manager's own stores, whichever the
|
||||
// server was configured with, and skipPersist does not apply to them.
|
||||
// reqID is set on the response; if empty, a new request ID is generated.
|
||||
func (e *EmbeddedIamApi) ExecuteAction(ctx context.Context, values url.Values, skipPersist bool, reqID string) (iamlib.RequestIDSetter, *iamError) {
|
||||
if reqID == "" {
|
||||
@@ -2598,7 +2618,8 @@ func (e *EmbeddedIamApi) ExecuteAction(ctx context.Context, values url.Values, s
|
||||
case "ListUsers", "ListAccessKeys", "GetUser", "GetUserPolicy", "ListUserPolicies", "ListAttachedUserPolicies", "ListPolicies", "GetPolicy", "ListPolicyVersions", "GetPolicyVersion", "ListServiceAccounts", "GetServiceAccount",
|
||||
"GetGroup", "ListGroups", "ListAttachedGroupPolicies", "GetGroupPolicy", "ListGroupPolicies", "ListGroupsForUser",
|
||||
"ListUserTags",
|
||||
actionListOpenIDConnectProviders, actionGetOpenIDConnectProvider:
|
||||
actionListOpenIDConnectProviders, actionGetOpenIDConnectProvider,
|
||||
actionGetRole, actionListRoles, actionListAttachedRolePolicies:
|
||||
// Allowed read-only actions
|
||||
default:
|
||||
return nil, &iamError{Code: s3err.GetAPIError(s3err.ErrAccessDenied).Code, Error: fmt.Errorf("IAM write operations are disabled on this server")}
|
||||
@@ -2615,6 +2636,15 @@ func (e *EmbeddedIamApi) ExecuteAction(ctx context.Context, values url.Values, s
|
||||
return response, nil
|
||||
}
|
||||
|
||||
// Role actions operate on the IAM manager's role store, likewise.
|
||||
if response, iamErr, ok := e.dispatchRoleAction(ctx, values); ok {
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
response.SetRequestId(reqID)
|
||||
return response, nil
|
||||
}
|
||||
|
||||
s3cfg := &iam_pb.S3ApiConfiguration{}
|
||||
if err := e.GetS3ApiConfiguration(s3cfg); err != nil && !errors.Is(err, filer_pb.ErrNotFound) {
|
||||
return nil, &iamError{Code: s3err.GetAPIError(s3err.ErrInternalError).Code, Error: fmt.Errorf("failed to get s3 api configuration: %v", err)}
|
||||
|
||||
@@ -161,7 +161,7 @@ func (e *EmbeddedIamApi) deleteOpenIDConnectProvider(ctx context.Context, mgr *i
|
||||
return nil, iamErr
|
||||
}
|
||||
if err := mgr.DeleteOIDCProvider(ctx, arn); err != nil {
|
||||
return nil, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
return nil, oidcMutationError(err)
|
||||
}
|
||||
return &iamlib.DeleteOpenIDConnectProviderResponse{}, nil
|
||||
}
|
||||
@@ -176,10 +176,7 @@ func (e *EmbeddedIamApi) addClientIDToOpenIDConnectProvider(ctx context.Context,
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: errors.New("ClientID is required")}
|
||||
}
|
||||
if err := mgr.AddClientIDToOIDCProvider(ctx, arn, clientID); err != nil {
|
||||
if errors.Is(err, integration.ErrOIDCProviderNotFound) {
|
||||
return nil, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: err}
|
||||
}
|
||||
return nil, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
return nil, oidcMutationError(err)
|
||||
}
|
||||
return &iamlib.AddClientIDToOpenIDConnectProviderResponse{}, nil
|
||||
}
|
||||
@@ -194,10 +191,7 @@ func (e *EmbeddedIamApi) removeClientIDFromOpenIDConnectProvider(ctx context.Con
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: errors.New("ClientID is required")}
|
||||
}
|
||||
if err := mgr.RemoveClientIDFromOIDCProvider(ctx, arn, clientID); err != nil {
|
||||
if errors.Is(err, integration.ErrOIDCProviderNotFound) {
|
||||
return nil, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: err}
|
||||
}
|
||||
return nil, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
return nil, oidcMutationError(err)
|
||||
}
|
||||
return &iamlib.RemoveClientIDFromOpenIDConnectProviderResponse{}, nil
|
||||
}
|
||||
@@ -212,6 +206,9 @@ func (e *EmbeddedIamApi) updateOpenIDConnectProviderThumbprint(ctx context.Conte
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: errors.New("ThumbprintList must contain at least one entry")}
|
||||
}
|
||||
if err := mgr.UpdateOIDCProviderThumbprints(ctx, arn, thumbprints); err != nil {
|
||||
if errors.Is(err, integration.ErrOIDCProviderStatic) {
|
||||
return nil, oidcMutationError(err)
|
||||
}
|
||||
if errors.Is(err, integration.ErrOIDCProviderNotFound) {
|
||||
return nil, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: err}
|
||||
}
|
||||
@@ -230,10 +227,7 @@ func (e *EmbeddedIamApi) tagOpenIDConnectProvider(ctx context.Context, mgr *inte
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: errors.New("Tags must contain at least one Key/Value pair")}
|
||||
}
|
||||
if err := mgr.TagOIDCProvider(ctx, arn, tags); err != nil {
|
||||
if errors.Is(err, integration.ErrOIDCProviderNotFound) {
|
||||
return nil, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: err}
|
||||
}
|
||||
return nil, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
return nil, oidcMutationError(err)
|
||||
}
|
||||
return &iamlib.TagOpenIDConnectProviderResponse{}, nil
|
||||
}
|
||||
@@ -248,10 +242,7 @@ func (e *EmbeddedIamApi) untagOpenIDConnectProvider(ctx context.Context, mgr *in
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: errors.New("TagKeys must contain at least one entry")}
|
||||
}
|
||||
if err := mgr.UntagOIDCProvider(ctx, arn, keys); err != nil {
|
||||
if errors.Is(err, integration.ErrOIDCProviderNotFound) {
|
||||
return nil, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: err}
|
||||
}
|
||||
return nil, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
return nil, oidcMutationError(err)
|
||||
}
|
||||
return &iamlib.UntagOpenIDConnectProviderResponse{}, nil
|
||||
}
|
||||
@@ -339,3 +330,17 @@ func (e *EmbeddedIamApi) getOpenIDConnectProvider(ctx context.Context, mgr *inte
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
// oidcMutationError maps an IAMManager error from a provider change to its
|
||||
// IAM error code. A provider defined in the IAM config file is changed there,
|
||||
// not through the API.
|
||||
func oidcMutationError(err error) *iamError {
|
||||
switch {
|
||||
case errors.Is(err, integration.ErrOIDCProviderStatic):
|
||||
return &iamError{Code: iam.ErrCodeUnmodifiableEntityException, Error: err}
|
||||
case errors.Is(err, integration.ErrOIDCProviderNotFound):
|
||||
return &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: err}
|
||||
default:
|
||||
return &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,419 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go/service/iam"
|
||||
iamlib "github.com/seaweedfs/seaweedfs/weed/iam"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/integration"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/policy"
|
||||
)
|
||||
|
||||
// Role IAM actions handled by this file.
|
||||
const (
|
||||
actionCreateRole = "CreateRole"
|
||||
actionGetRole = "GetRole"
|
||||
actionListRoles = "ListRoles"
|
||||
actionDeleteRole = "DeleteRole"
|
||||
actionUpdateAssumeRolePolicy = "UpdateAssumeRolePolicy"
|
||||
actionAttachRolePolicy = "AttachRolePolicy"
|
||||
actionDetachRolePolicy = "DetachRolePolicy"
|
||||
actionListAttachedRolePolicies = "ListAttachedRolePolicies"
|
||||
)
|
||||
|
||||
// isRoleAction reports whether an action belongs to the role family.
|
||||
func isRoleAction(action string) bool {
|
||||
switch action {
|
||||
case actionCreateRole, actionGetRole, actionListRoles, actionDeleteRole,
|
||||
actionUpdateAssumeRolePolicy, actionAttachRolePolicy, actionDetachRolePolicy,
|
||||
actionListAttachedRolePolicies:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
// dispatchRoleAction handles the role IAM actions. Roles live in the IAM
|
||||
// manager's role store, not in S3ApiConfiguration, so like the OIDC provider
|
||||
// actions they are dispatched before the configuration load. The boolean
|
||||
// reports whether the action was recognised.
|
||||
func (e *EmbeddedIamApi) dispatchRoleAction(ctx context.Context, values url.Values) (iamlib.RequestIDSetter, *iamError, bool) {
|
||||
if !isRoleAction(values.Get("Action")) {
|
||||
return nil, nil, false
|
||||
}
|
||||
mgr := e.oidcIAMManager()
|
||||
if mgr == nil {
|
||||
return nil, &iamError{Code: iam.ErrCodeServiceFailureException, Error: errors.New("role store not configured: start the S3 server with an IAM config")}, true
|
||||
}
|
||||
|
||||
switch values.Get("Action") {
|
||||
case actionCreateRole:
|
||||
resp, err := e.createRole(ctx, mgr, values)
|
||||
return resp, err, true
|
||||
case actionGetRole:
|
||||
resp, err := e.getRole(ctx, mgr, values)
|
||||
return resp, err, true
|
||||
case actionListRoles:
|
||||
resp, err := e.listRoles(ctx, mgr)
|
||||
return resp, err, true
|
||||
case actionDeleteRole:
|
||||
resp, err := e.deleteRole(ctx, mgr, values)
|
||||
return resp, err, true
|
||||
case actionUpdateAssumeRolePolicy:
|
||||
resp, err := e.updateAssumeRolePolicy(ctx, mgr, values)
|
||||
return resp, err, true
|
||||
case actionAttachRolePolicy:
|
||||
resp, err := e.attachRolePolicy(ctx, mgr, values)
|
||||
return resp, err, true
|
||||
case actionDetachRolePolicy:
|
||||
resp, err := e.detachRolePolicy(ctx, mgr, values)
|
||||
return resp, err, true
|
||||
case actionListAttachedRolePolicies:
|
||||
resp, err := e.listAttachedRolePolicies(ctx, mgr, values)
|
||||
return resp, err, true
|
||||
}
|
||||
return nil, nil, false
|
||||
}
|
||||
|
||||
// parseTrustPolicy decodes and validates an AssumeRolePolicyDocument.
|
||||
func parseTrustPolicy(document string) (*policy.PolicyDocument, *iamError) {
|
||||
if strings.TrimSpace(document) == "" {
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: errors.New("AssumeRolePolicyDocument is required")}
|
||||
}
|
||||
var doc policy.PolicyDocument
|
||||
if err := json.Unmarshal([]byte(document), &doc); err != nil {
|
||||
return nil, &iamError{Code: iam.ErrCodeMalformedPolicyDocumentException, Error: fmt.Errorf("parse trust policy: %w", err)}
|
||||
}
|
||||
if err := policy.ValidateTrustPolicyDocument(&doc); err != nil {
|
||||
return nil, &iamError{Code: iam.ErrCodeMalformedPolicyDocumentException, Error: err}
|
||||
}
|
||||
return &doc, nil
|
||||
}
|
||||
|
||||
// requireRole loads the named role, mapping a missing role to NoSuchEntity.
|
||||
func requireRole(ctx context.Context, mgr *integration.IAMManager, values url.Values) (*integration.RoleDefinition, *iamError) {
|
||||
name := strings.TrimSpace(values.Get("RoleName"))
|
||||
if name == "" {
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: errors.New("RoleName is required")}
|
||||
}
|
||||
role, err := mgr.GetRole(ctx, name)
|
||||
if errors.Is(err, integration.ErrRoleNotFound) || (err == nil && role == nil) {
|
||||
return nil, &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf("role %s not found", name)}
|
||||
}
|
||||
if err != nil {
|
||||
return nil, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
}
|
||||
return role, nil
|
||||
}
|
||||
|
||||
// requireMutableRole is requireRole for actions that change or delete the
|
||||
// role. A role loaded from the IAM config file is reloaded from it at every
|
||||
// start, so a change made through the API would be silently reverted; it is
|
||||
// refused instead.
|
||||
func requireMutableRole(ctx context.Context, mgr *integration.IAMManager, values url.Values) (*integration.RoleDefinition, *iamError) {
|
||||
role, iamErr := requireRole(ctx, mgr, values)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
if role.Source == integration.RoleSourceStaticConfig {
|
||||
return nil, &iamError{Code: iam.ErrCodeUnmodifiableEntityException, Error: fmt.Errorf("role %s is defined in the IAM config file; change it there", role.RoleName)}
|
||||
}
|
||||
return role, nil
|
||||
}
|
||||
|
||||
// errRoleUpdateRefused aborts a RoleStore update whose refusal the handler
|
||||
// has already recorded as an iamError.
|
||||
var errRoleUpdateRefused = errors.New("role update refused")
|
||||
|
||||
// updateRole applies change to the named role through the role store's atomic
|
||||
// update, so a concurrent change on another server is neither lost nor
|
||||
// written over a delete. change sees the current role and returns an iamError
|
||||
// to refuse; a missing role is NoSuchEntity and a config-file role is
|
||||
// UnmodifiableEntity, as requireMutableRole reports them.
|
||||
func updateRole(ctx context.Context, mgr *integration.IAMManager, name string, change func(role *integration.RoleDefinition) *iamError) *iamError {
|
||||
var refused *iamError
|
||||
err := mgr.UpdateRole(ctx, name, func(current *integration.RoleDefinition) (*integration.RoleDefinition, error) {
|
||||
if current == nil {
|
||||
refused = &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf("role %s not found", name)}
|
||||
return nil, errRoleUpdateRefused
|
||||
}
|
||||
if refused = change(current); refused != nil {
|
||||
return nil, errRoleUpdateRefused
|
||||
}
|
||||
return current, nil
|
||||
})
|
||||
return roleWriteError(err, refused)
|
||||
}
|
||||
|
||||
// roleWriteError maps a role store write's outcome to the IAM error to
|
||||
// report: the handler's own refusal, else the store's error by kind. A write
|
||||
// that failed for another reason is a service failure, which clients retry.
|
||||
func roleWriteError(err error, refused *iamError) *iamError {
|
||||
switch {
|
||||
case err == nil:
|
||||
return nil
|
||||
case errors.Is(err, errRoleUpdateRefused) && refused != nil:
|
||||
return refused
|
||||
case errors.Is(err, integration.ErrRoleStatic):
|
||||
return &iamError{Code: iam.ErrCodeUnmodifiableEntityException, Error: fmt.Errorf("%w; change it there", err)}
|
||||
case errors.Is(err, integration.ErrRoleExists):
|
||||
return &iamError{Code: iam.ErrCodeEntityAlreadyExistsException, Error: err}
|
||||
default:
|
||||
return &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
}
|
||||
}
|
||||
|
||||
// roleID is the role's stored ID. A role stored before IDs were recorded has
|
||||
// none; it is reported with the ID StaticRoleID derives for it.
|
||||
func roleID(role *integration.RoleDefinition) string {
|
||||
if role.RoleId != "" {
|
||||
return role.RoleId
|
||||
}
|
||||
return integration.StaticRoleID(role)
|
||||
}
|
||||
|
||||
func toIAMRole(role *integration.RoleDefinition) iamlib.IAMRole {
|
||||
out := iamlib.IAMRole{
|
||||
Path: "/",
|
||||
RoleName: role.RoleName,
|
||||
RoleId: roleID(role),
|
||||
Arn: role.RoleArn,
|
||||
Description: role.Description,
|
||||
MaxSessionDuration: role.MaxSessionDuration,
|
||||
}
|
||||
if !role.CreatedAt.IsZero() {
|
||||
out.CreateDate = role.CreatedAt.UTC().Format(time.RFC3339)
|
||||
}
|
||||
if role.TrustPolicy != nil {
|
||||
if doc, err := json.Marshal(role.TrustPolicy); err == nil {
|
||||
// AWS returns the document URL-encoded.
|
||||
out.AssumeRolePolicyDocument = url.PathEscape(string(doc))
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
func (e *EmbeddedIamApi) createRole(ctx context.Context, mgr *integration.IAMManager, values url.Values) (*iamlib.CreateRoleResponse, *iamError) {
|
||||
name := strings.TrimSpace(values.Get("RoleName"))
|
||||
if name == "" {
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: errors.New("RoleName is required")}
|
||||
}
|
||||
if err := integration.ValidateRoleName(name); err != nil {
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: err}
|
||||
}
|
||||
if path := values.Get("Path"); path != "" && path != "/" {
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("role paths are not supported: %s", path)}
|
||||
}
|
||||
for key := range values {
|
||||
if strings.HasPrefix(key, "Tags.") {
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: errors.New("role tags are not supported")}
|
||||
}
|
||||
}
|
||||
// A config-file role is served beside the store, not from it, so the
|
||||
// store's create-if-absent cannot see it.
|
||||
existing, err := mgr.GetRole(ctx, name)
|
||||
if err == nil && existing != nil {
|
||||
return nil, &iamError{Code: iam.ErrCodeEntityAlreadyExistsException, Error: fmt.Errorf("role %s already exists", name)}
|
||||
}
|
||||
if err != nil && !errors.Is(err, integration.ErrRoleNotFound) {
|
||||
return nil, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
}
|
||||
trust, iamErr := parseTrustPolicy(values.Get("AssumeRolePolicyDocument"))
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
var maxSession int64
|
||||
if raw := values.Get("MaxSessionDuration"); raw != "" {
|
||||
n, err := strconv.ParseInt(raw, 10, 64)
|
||||
if err != nil {
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("MaxSessionDuration: %w", err)}
|
||||
}
|
||||
maxSession = n
|
||||
}
|
||||
|
||||
role := &integration.RoleDefinition{
|
||||
RoleName: name,
|
||||
TrustPolicy: trust,
|
||||
Description: values.Get("Description"),
|
||||
MaxSessionDuration: maxSession,
|
||||
CreatedAt: time.Now().UTC(),
|
||||
RoleId: integration.NewRoleID(),
|
||||
}
|
||||
// Validation first: only a bad request is InvalidInput. The write below
|
||||
// is created only if no role of this name exists by then, so of two
|
||||
// concurrent creates, one fails with EntityAlreadyExists.
|
||||
if err := integration.PrepareRoleDefinition(name, role); err != nil {
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: err}
|
||||
}
|
||||
err = mgr.UpdateRole(ctx, name, func(current *integration.RoleDefinition) (*integration.RoleDefinition, error) {
|
||||
if current != nil {
|
||||
return nil, fmt.Errorf("%w: %s", integration.ErrRoleExists, name)
|
||||
}
|
||||
return role, nil
|
||||
})
|
||||
if iamErr := roleWriteError(err, nil); iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
resp := &iamlib.CreateRoleResponse{}
|
||||
resp.CreateRoleResult.Role = toIAMRole(role)
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (e *EmbeddedIamApi) getRole(ctx context.Context, mgr *integration.IAMManager, values url.Values) (*iamlib.GetRoleResponse, *iamError) {
|
||||
role, iamErr := requireRole(ctx, mgr, values)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
resp := &iamlib.GetRoleResponse{}
|
||||
resp.GetRoleResult.Role = toIAMRole(role)
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (e *EmbeddedIamApi) listRoles(ctx context.Context, mgr *integration.IAMManager) (*iamlib.ListRolesResponse, *iamError) {
|
||||
roles, err := mgr.ListRoles(ctx)
|
||||
if err != nil {
|
||||
return nil, &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
}
|
||||
resp := &iamlib.ListRolesResponse{}
|
||||
resp.ListRolesResult.Roles = make([]*iamlib.IAMRole, 0, len(roles))
|
||||
for _, role := range roles {
|
||||
view := toIAMRole(role)
|
||||
resp.ListRolesResult.Roles = append(resp.ListRolesResult.Roles, &view)
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
|
||||
func (e *EmbeddedIamApi) deleteRole(ctx context.Context, mgr *integration.IAMManager, values url.Values) (*iamlib.DeleteRoleResponse, *iamError) {
|
||||
role, iamErr := requireMutableRole(ctx, mgr, values)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
// The delete is decided against the role as it is when deleted, in the
|
||||
// store's atomic update: a policy attached meanwhile on another server is
|
||||
// a DeleteConflict, as AWS reports a role with managed policies attached.
|
||||
var refused *iamError
|
||||
err := mgr.UpdateRole(ctx, role.RoleName, func(current *integration.RoleDefinition) (*integration.RoleDefinition, error) {
|
||||
if current == nil {
|
||||
refused = &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf("role %s not found", role.RoleName)}
|
||||
return nil, errRoleUpdateRefused
|
||||
}
|
||||
if len(current.AttachedPolicies) > 0 {
|
||||
refused = &iamError{Code: iam.ErrCodeDeleteConflictException, Error: fmt.Errorf("role %s has attached policies; detach them first", role.RoleName)}
|
||||
return nil, errRoleUpdateRefused
|
||||
}
|
||||
return nil, nil
|
||||
})
|
||||
if iamErr := roleWriteError(err, refused); iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
return &iamlib.DeleteRoleResponse{}, nil
|
||||
}
|
||||
|
||||
func (e *EmbeddedIamApi) updateAssumeRolePolicy(ctx context.Context, mgr *integration.IAMManager, values url.Values) (*iamlib.UpdateAssumeRolePolicyResponse, *iamError) {
|
||||
role, iamErr := requireMutableRole(ctx, mgr, values)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
trust, iamErr := parseTrustPolicy(values.Get("PolicyDocument"))
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
if iamErr := updateRole(ctx, mgr, role.RoleName, func(current *integration.RoleDefinition) *iamError {
|
||||
current.TrustPolicy = trust
|
||||
return nil
|
||||
}); iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
return &iamlib.UpdateAssumeRolePolicyResponse{}, nil
|
||||
}
|
||||
|
||||
// rolePolicyName resolves PolicyArn to the name of an existing managed policy.
|
||||
func (e *EmbeddedIamApi) rolePolicyName(ctx context.Context, values url.Values) (string, *iamError) {
|
||||
name, err := iamPolicyNameFromArn(values.Get("PolicyArn"))
|
||||
if err != nil {
|
||||
return "", &iamError{Code: iam.ErrCodeInvalidInputException, Error: err}
|
||||
}
|
||||
if e.credentialManager == nil {
|
||||
return "", &iamError{Code: iam.ErrCodeServiceFailureException, Error: errors.New("credential manager not configured")}
|
||||
}
|
||||
existing, err := e.credentialManager.GetPolicy(ctx, name)
|
||||
if err != nil {
|
||||
return "", &iamError{Code: iam.ErrCodeServiceFailureException, Error: err}
|
||||
}
|
||||
if existing == nil {
|
||||
return "", &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf("policy %s not found", name)}
|
||||
}
|
||||
return name, nil
|
||||
}
|
||||
|
||||
func (e *EmbeddedIamApi) attachRolePolicy(ctx context.Context, mgr *integration.IAMManager, values url.Values) (*iamlib.AttachRolePolicyResponse, *iamError) {
|
||||
role, iamErr := requireMutableRole(ctx, mgr, values)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
name, iamErr := e.rolePolicyName(ctx, values)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
if slices.Contains(role.AttachedPolicies, name) {
|
||||
return &iamlib.AttachRolePolicyResponse{}, nil
|
||||
}
|
||||
if iamErr := updateRole(ctx, mgr, role.RoleName, func(current *integration.RoleDefinition) *iamError {
|
||||
if slices.Contains(current.AttachedPolicies, name) {
|
||||
return nil
|
||||
}
|
||||
if len(current.AttachedPolicies) >= integration.MaxManagedPoliciesPerRole {
|
||||
return &iamError{Code: iam.ErrCodeLimitExceededException,
|
||||
Error: fmt.Errorf("cannot attach more than %d managed policies to role %s", integration.MaxManagedPoliciesPerRole, current.RoleName)}
|
||||
}
|
||||
current.AttachedPolicies = append(current.AttachedPolicies, name)
|
||||
return nil
|
||||
}); iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
return &iamlib.AttachRolePolicyResponse{}, nil
|
||||
}
|
||||
|
||||
func (e *EmbeddedIamApi) detachRolePolicy(ctx context.Context, mgr *integration.IAMManager, values url.Values) (*iamlib.DetachRolePolicyResponse, *iamError) {
|
||||
role, iamErr := requireMutableRole(ctx, mgr, values)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
name, err := iamPolicyNameFromArn(values.Get("PolicyArn"))
|
||||
if err != nil {
|
||||
return nil, &iamError{Code: iam.ErrCodeInvalidInputException, Error: err}
|
||||
}
|
||||
if iamErr := updateRole(ctx, mgr, role.RoleName, func(current *integration.RoleDefinition) *iamError {
|
||||
idx := slices.Index(current.AttachedPolicies, name)
|
||||
if idx < 0 {
|
||||
return &iamError{Code: iam.ErrCodeNoSuchEntityException, Error: fmt.Errorf("policy %s is not attached to role %s", name, current.RoleName)}
|
||||
}
|
||||
current.AttachedPolicies = slices.Delete(current.AttachedPolicies, idx, idx+1)
|
||||
return nil
|
||||
}); iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
return &iamlib.DetachRolePolicyResponse{}, nil
|
||||
}
|
||||
|
||||
func (e *EmbeddedIamApi) listAttachedRolePolicies(ctx context.Context, mgr *integration.IAMManager, values url.Values) (*iamlib.ListAttachedRolePoliciesResponse, *iamError) {
|
||||
role, iamErr := requireRole(ctx, mgr, values)
|
||||
if iamErr != nil {
|
||||
return nil, iamErr
|
||||
}
|
||||
resp := &iamlib.ListAttachedRolePoliciesResponse{}
|
||||
resp.ListAttachedRolePoliciesResult.AttachedPolicies = make([]*iamlib.IAMAttachedPolicy, 0, len(role.AttachedPolicies))
|
||||
for _, name := range role.AttachedPolicies {
|
||||
resp.ListAttachedRolePoliciesResult.AttachedPolicies = append(resp.ListAttachedRolePoliciesResult.AttachedPolicies,
|
||||
&iamlib.IAMAttachedPolicy{PolicyName: name, PolicyArn: iamPolicyArn(name)})
|
||||
}
|
||||
return resp, nil
|
||||
}
|
||||
@@ -2,6 +2,10 @@ package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"github.com/aws/aws-sdk-go/service/iam"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -394,3 +398,18 @@ func TestUpdateThumbprintAndTags(t *testing.T) {
|
||||
t.Fatalf("Tags should be empty after untag, got: %v", gr.Tags)
|
||||
}
|
||||
}
|
||||
|
||||
// A refusal to change a config-file provider reaches the client as AWS sends
|
||||
// it (400 UnmodifiableEntity), not as an internal error clients retry.
|
||||
func TestUnmodifiableEntityIsAClientError(t *testing.T) {
|
||||
api := NewEmbeddedIamApiForTest()
|
||||
rec := httptest.NewRecorder()
|
||||
api.writeIamErrorResponse(rec, httptest.NewRequest(http.MethodPost, "/", nil), "req-1",
|
||||
oidcMutationError(fmt.Errorf("%w: arn:aws:iam:::oidc-provider/static.example", integration.ErrOIDCProviderStatic)))
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("status = %d, want 400", rec.Code)
|
||||
}
|
||||
if code, _ := extractEmbeddedIamErrorCodeAndMessage(rec); code != iam.ErrCodeUnmodifiableEntityException {
|
||||
t.Fatalf("code = %q, want UnmodifiableEntity", code)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,340 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/aws/aws-sdk-go/service/iam"
|
||||
iamlib "github.com/seaweedfs/seaweedfs/weed/iam"
|
||||
"github.com/seaweedfs/seaweedfs/weed/iam/integration"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
const spiffeTrustPolicy = `{"Version":"2012-10-17","Statement":[{"Effect":"Allow",` +
|
||||
`"Principal":{"Federated":"https://oidc.example"},"Action":["sts:AssumeRoleWithWebIdentity"],` +
|
||||
`"Condition":{"StringEquals":{"oidc:sub":"spiffe://example.org/ns/app/sa/app"}}}]}`
|
||||
|
||||
func roleAction(t *testing.T, api *EmbeddedIamApiForTest, params map[string]string) (iamlib.RequestIDSetter, *iamError) {
|
||||
t.Helper()
|
||||
values := url.Values{}
|
||||
for k, v := range params {
|
||||
values.Set(k, v)
|
||||
}
|
||||
return api.ExecuteAction(context.Background(), values, true, "role-test")
|
||||
}
|
||||
|
||||
func requireIamCode(t *testing.T, iamErr *iamError, code string) {
|
||||
t.Helper()
|
||||
require.NotNil(t, iamErr, "expected %s", code)
|
||||
assert.Equal(t, code, iamErr.Code, "error: %v", iamErr.Error)
|
||||
}
|
||||
|
||||
func newRoleTestAPI(t *testing.T) (*EmbeddedIamApiForTest, *integration.IAMManager) {
|
||||
t.Helper()
|
||||
api, mgr := newOIDCTestAPI(t)
|
||||
doc := policy_engine.PolicyDocument{Version: "2012-10-17", Statement: []policy_engine.PolicyStatement{{
|
||||
Effect: policy_engine.PolicyEffectAllow,
|
||||
Action: policy_engine.NewStringOrStringSlice("s3:GetObject"),
|
||||
Resource: policy_engine.NewStringOrStringSlicePtr("arn:aws:s3:::bucket/*"),
|
||||
}}}
|
||||
require.NoError(t, api.credentialManager.CreatePolicy(context.Background(), "read-bucket", doc))
|
||||
return api, mgr
|
||||
}
|
||||
|
||||
func TestRoleLifecycle(t *testing.T) {
|
||||
api, mgr := newRoleTestAPI(t)
|
||||
|
||||
resp, iamErr := roleAction(t, api, map[string]string{
|
||||
"Action": actionCreateRole, "RoleName": "app", "AssumeRolePolicyDocument": spiffeTrustPolicy,
|
||||
"Description": "app runtime", "MaxSessionDuration": "3600",
|
||||
})
|
||||
require.Nil(t, iamErr)
|
||||
created := resp.(*iamlib.CreateRoleResponse).CreateRoleResult.Role
|
||||
assert.Equal(t, "arn:aws:iam::role/app", created.Arn)
|
||||
assert.NotEmpty(t, created.RoleId)
|
||||
assert.NotEmpty(t, created.CreateDate)
|
||||
decoded, err := url.PathUnescape(created.AssumeRolePolicyDocument)
|
||||
require.NoError(t, err)
|
||||
assert.Contains(t, decoded, "spiffe://example.org/ns/app/sa/app")
|
||||
|
||||
// The role is the one STS evaluates.
|
||||
stored, err := mgr.GetRole(context.Background(), "app")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "https://oidc.example", stored.TrustPolicy.Statement[0].Principal.(map[string]interface{})["Federated"])
|
||||
|
||||
_, iamErr = roleAction(t, api, map[string]string{"Action": actionAttachRolePolicy, "RoleName": "app", "PolicyArn": "arn:aws:iam:::policy/read-bucket"})
|
||||
require.Nil(t, iamErr)
|
||||
resp, iamErr = roleAction(t, api, map[string]string{"Action": actionListAttachedRolePolicies, "RoleName": "app"})
|
||||
require.Nil(t, iamErr)
|
||||
attached := resp.(*iamlib.ListAttachedRolePoliciesResponse).ListAttachedRolePoliciesResult.AttachedPolicies
|
||||
require.Len(t, attached, 1)
|
||||
assert.Equal(t, "read-bucket", attached[0].PolicyName)
|
||||
|
||||
_, iamErr = roleAction(t, api, map[string]string{"Action": actionDeleteRole, "RoleName": "app"})
|
||||
requireIamCode(t, iamErr, iam.ErrCodeDeleteConflictException)
|
||||
|
||||
_, iamErr = roleAction(t, api, map[string]string{"Action": actionDetachRolePolicy, "RoleName": "app", "PolicyArn": "arn:aws:iam:::policy/read-bucket"})
|
||||
require.Nil(t, iamErr)
|
||||
_, iamErr = roleAction(t, api, map[string]string{"Action": actionDeleteRole, "RoleName": "app"})
|
||||
require.Nil(t, iamErr)
|
||||
_, iamErr = roleAction(t, api, map[string]string{"Action": actionGetRole, "RoleName": "app"})
|
||||
requireIamCode(t, iamErr, iam.ErrCodeNoSuchEntityException)
|
||||
}
|
||||
|
||||
func TestUpdateAssumeRolePolicyReplacesTheTrustPolicy(t *testing.T) {
|
||||
api, mgr := newRoleTestAPI(t)
|
||||
_, iamErr := roleAction(t, api, map[string]string{"Action": actionCreateRole, "RoleName": "app", "AssumeRolePolicyDocument": spiffeTrustPolicy})
|
||||
require.Nil(t, iamErr)
|
||||
|
||||
updated := `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"Federated":"https://other.example"},"Action":["sts:AssumeRoleWithWebIdentity"]}]}`
|
||||
_, iamErr = roleAction(t, api, map[string]string{"Action": actionUpdateAssumeRolePolicy, "RoleName": "app", "PolicyDocument": updated})
|
||||
require.Nil(t, iamErr)
|
||||
stored, err := mgr.GetRole(context.Background(), "app")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "https://other.example", stored.TrustPolicy.Statement[0].Principal.(map[string]interface{})["Federated"])
|
||||
}
|
||||
|
||||
func TestRoleActionsRefuseWhatTheyCannotHonour(t *testing.T) {
|
||||
api, _ := newRoleTestAPI(t)
|
||||
_, iamErr := roleAction(t, api, map[string]string{"Action": actionCreateRole, "RoleName": "app", "AssumeRolePolicyDocument": spiffeTrustPolicy})
|
||||
require.Nil(t, iamErr)
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
params map[string]string
|
||||
code string
|
||||
}{
|
||||
{"duplicate", map[string]string{"Action": actionCreateRole, "RoleName": "app", "AssumeRolePolicyDocument": spiffeTrustPolicy}, iam.ErrCodeEntityAlreadyExistsException},
|
||||
{"no trust policy", map[string]string{"Action": actionCreateRole, "RoleName": "b"}, iam.ErrCodeInvalidInputException},
|
||||
{"malformed trust policy", map[string]string{"Action": actionCreateRole, "RoleName": "b", "AssumeRolePolicyDocument": "{"}, iam.ErrCodeMalformedPolicyDocumentException},
|
||||
{"path", map[string]string{"Action": actionCreateRole, "RoleName": "b", "Path": "/team/", "AssumeRolePolicyDocument": spiffeTrustPolicy}, iam.ErrCodeInvalidInputException},
|
||||
{"tags", map[string]string{"Action": actionCreateRole, "RoleName": "b", "Tags.member.1.Key": "k", "Tags.member.1.Value": "v", "AssumeRolePolicyDocument": spiffeTrustPolicy}, iam.ErrCodeInvalidInputException},
|
||||
{"session out of bounds", map[string]string{"Action": actionCreateRole, "RoleName": "b", "MaxSessionDuration": "60", "AssumeRolePolicyDocument": spiffeTrustPolicy}, iam.ErrCodeInvalidInputException},
|
||||
{"attach missing policy", map[string]string{"Action": actionAttachRolePolicy, "RoleName": "app", "PolicyArn": "arn:aws:iam:::policy/nope"}, iam.ErrCodeNoSuchEntityException},
|
||||
{"detach unattached", map[string]string{"Action": actionDetachRolePolicy, "RoleName": "app", "PolicyArn": "arn:aws:iam:::policy/read-bucket"}, iam.ErrCodeNoSuchEntityException},
|
||||
{"missing role", map[string]string{"Action": actionDeleteRole, "RoleName": "nope"}, iam.ErrCodeNoSuchEntityException},
|
||||
{"name leaving the role store", map[string]string{"Action": actionCreateRole, "RoleName": "../identities/admin", "AssumeRolePolicyDocument": spiffeTrustPolicy}, iam.ErrCodeInvalidInputException},
|
||||
{"name too long", map[string]string{"Action": actionCreateRole, "RoleName": strings.Repeat("a", 65), "AssumeRolePolicyDocument": spiffeTrustPolicy}, iam.ErrCodeInvalidInputException},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
_, iamErr := roleAction(t, api, tc.params)
|
||||
requireIamCode(t, iamErr, tc.code)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A role from the IAM config file is reloaded from it at every start, so an
|
||||
// API change to it would be silently reverted; it is refused instead.
|
||||
func TestConfigFileRolesAreUnmodifiable(t *testing.T) {
|
||||
api, mgr := newRoleTestAPI(t)
|
||||
trust, iamErr := parseTrustPolicy(spiffeTrustPolicy)
|
||||
require.Nil(t, iamErr)
|
||||
require.NoError(t, mgr.CreateRole(context.Background(), "", "from-file", &integration.RoleDefinition{
|
||||
RoleName: "from-file", TrustPolicy: trust, Source: integration.RoleSourceStaticConfig,
|
||||
}))
|
||||
|
||||
for _, params := range []map[string]string{
|
||||
{"Action": actionDeleteRole, "RoleName": "from-file"},
|
||||
{"Action": actionUpdateAssumeRolePolicy, "RoleName": "from-file", "PolicyDocument": spiffeTrustPolicy},
|
||||
{"Action": actionAttachRolePolicy, "RoleName": "from-file", "PolicyArn": "arn:aws:iam:::policy/read-bucket"},
|
||||
{"Action": actionDetachRolePolicy, "RoleName": "from-file", "PolicyArn": "arn:aws:iam:::policy/read-bucket"},
|
||||
} {
|
||||
t.Run(params["Action"], func(t *testing.T) {
|
||||
_, iamErr := roleAction(t, api, params)
|
||||
requireIamCode(t, iamErr, iam.ErrCodeUnmodifiableEntityException)
|
||||
})
|
||||
}
|
||||
_, iamErr = roleAction(t, api, map[string]string{"Action": actionGetRole, "RoleName": "from-file"})
|
||||
assert.Nil(t, iamErr, "reading a config-file role is allowed")
|
||||
}
|
||||
|
||||
func TestReadOnlyAllowsRoleReadsAndDeniesMutations(t *testing.T) {
|
||||
api, _ := newRoleTestAPI(t)
|
||||
_, iamErr := roleAction(t, api, map[string]string{"Action": actionCreateRole, "RoleName": "app", "AssumeRolePolicyDocument": spiffeTrustPolicy})
|
||||
require.Nil(t, iamErr)
|
||||
api.readOnly = true
|
||||
|
||||
for _, action := range []string{actionGetRole, actionListRoles, actionListAttachedRolePolicies} {
|
||||
_, iamErr := roleAction(t, api, map[string]string{"Action": action, "RoleName": "app"})
|
||||
assert.Nil(t, iamErr, "%s must be allowed in read-only mode", action)
|
||||
}
|
||||
for _, action := range []string{actionCreateRole, actionDeleteRole, actionUpdateAssumeRolePolicy, actionAttachRolePolicy, actionDetachRolePolicy} {
|
||||
_, iamErr := roleAction(t, api, map[string]string{"Action": action, "RoleName": "app"})
|
||||
assert.NotNil(t, iamErr, "%s must be denied in read-only mode", action)
|
||||
}
|
||||
}
|
||||
|
||||
// unreadableRoleStore fails every read the way an unreachable filer does.
|
||||
type unreadableRoleStore struct{ *integration.MemoryRoleStore }
|
||||
|
||||
func (unreadableRoleStore) GetRole(context.Context, string, string) (*integration.RoleDefinition, error) {
|
||||
return nil, errors.New("lookup role: filer unavailable")
|
||||
}
|
||||
|
||||
// An unreadable store is not an absent role: CreateRole must not write over a
|
||||
// role it could not see, and the reads must not report NoSuchEntity.
|
||||
func TestRoleActionsTreatAnUnreadableStoreAsAFailureNotAnAbsence(t *testing.T) {
|
||||
api, mgr := newRoleTestAPI(t)
|
||||
store := unreadableRoleStore{integration.NewMemoryRoleStore()}
|
||||
mgr.SetRoleStore(store)
|
||||
|
||||
_, iamErr := roleAction(t, api, map[string]string{"Action": actionCreateRole, "RoleName": "app", "AssumeRolePolicyDocument": spiffeTrustPolicy})
|
||||
requireIamCode(t, iamErr, iam.ErrCodeServiceFailureException)
|
||||
names, err := store.ListRoles(context.Background(), "")
|
||||
require.NoError(t, err)
|
||||
assert.Empty(t, names, "CreateRole wrote through a store it could not read")
|
||||
|
||||
_, iamErr = roleAction(t, api, map[string]string{"Action": actionGetRole, "RoleName": "app"})
|
||||
requireIamCode(t, iamErr, iam.ErrCodeServiceFailureException)
|
||||
}
|
||||
|
||||
// A policy is attached to a role by name, so deleting it while attached would
|
||||
// let a policy created later under that name take effect on the role. It is
|
||||
// refused, as for users and groups.
|
||||
func TestDeletePolicyAttachedToARoleIsAConflict(t *testing.T) {
|
||||
api, _ := newRoleTestAPI(t)
|
||||
// The test API replaces the credential store with mockConfig on the first
|
||||
// action that loads the configuration, so the policy has to be declared
|
||||
// there too.
|
||||
api.mockConfig.Policies = append(api.mockConfig.Policies, &iam_pb.Policy{
|
||||
Name: "read-bucket",
|
||||
Content: `{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":["s3:GetObject"],"Resource":["arn:aws:s3:::bucket/*"]}]}`,
|
||||
})
|
||||
_, iamErr := roleAction(t, api, map[string]string{"Action": actionCreateRole, "RoleName": "app", "AssumeRolePolicyDocument": spiffeTrustPolicy})
|
||||
require.Nil(t, iamErr)
|
||||
_, iamErr = roleAction(t, api, map[string]string{"Action": actionAttachRolePolicy, "RoleName": "app", "PolicyArn": "arn:aws:iam:::policy/read-bucket"})
|
||||
require.Nil(t, iamErr)
|
||||
|
||||
_, iamErr = roleAction(t, api, map[string]string{"Action": "DeletePolicy", "PolicyArn": "arn:aws:iam:::policy/read-bucket"})
|
||||
requireIamCode(t, iamErr, iam.ErrCodeDeleteConflictException)
|
||||
|
||||
_, iamErr = roleAction(t, api, map[string]string{"Action": actionDetachRolePolicy, "RoleName": "app", "PolicyArn": "arn:aws:iam:::policy/read-bucket"})
|
||||
require.Nil(t, iamErr)
|
||||
_, iamErr = roleAction(t, api, map[string]string{"Action": "DeletePolicy", "PolicyArn": "arn:aws:iam:::policy/read-bucket"})
|
||||
assert.Nil(t, iamErr, "a detached policy could not be deleted")
|
||||
}
|
||||
|
||||
func TestAttachRolePolicyStopsAtTheRoleQuota(t *testing.T) {
|
||||
api, _ := newRoleTestAPI(t)
|
||||
_, iamErr := roleAction(t, api, map[string]string{"Action": actionCreateRole, "RoleName": "app", "AssumeRolePolicyDocument": spiffeTrustPolicy})
|
||||
require.Nil(t, iamErr)
|
||||
doc := policy_engine.PolicyDocument{Version: "2012-10-17", Statement: []policy_engine.PolicyStatement{{
|
||||
Effect: policy_engine.PolicyEffectAllow, Action: policy_engine.NewStringOrStringSlice("s3:GetObject"),
|
||||
Resource: policy_engine.NewStringOrStringSlicePtr("arn:aws:s3:::bucket/*"),
|
||||
}}}
|
||||
for i := 0; i <= integration.MaxManagedPoliciesPerRole; i++ {
|
||||
name := fmt.Sprintf("p%d", i)
|
||||
require.NoError(t, api.credentialManager.CreatePolicy(context.Background(), name, doc))
|
||||
_, iamErr = roleAction(t, api, map[string]string{"Action": actionAttachRolePolicy, "RoleName": "app", "PolicyArn": "arn:aws:iam:::policy/" + name})
|
||||
if i < integration.MaxManagedPoliciesPerRole {
|
||||
require.Nil(t, iamErr, "attach %d", i)
|
||||
}
|
||||
}
|
||||
requireIamCode(t, iamErr, iam.ErrCodeLimitExceededException)
|
||||
}
|
||||
|
||||
// A role without a creation time omits CreateDate rather than sending it
|
||||
// empty, which clients cannot parse.
|
||||
func TestRoleWithoutACreationTimeOmitsCreateDate(t *testing.T) {
|
||||
out, err := xml.Marshal(toIAMRole(&integration.RoleDefinition{RoleName: "r", RoleArn: "arn:aws:iam::role/r"}))
|
||||
require.NoError(t, err)
|
||||
assert.NotContains(t, string(out), "CreateDate")
|
||||
}
|
||||
|
||||
// Roles take no tags, so any tag parameter is refused rather than dropped.
|
||||
func TestCreateRoleRefusesEveryTagParameter(t *testing.T) {
|
||||
api, _ := newRoleTestAPI(t)
|
||||
for _, key := range []string{"Tags.member.1.Key", "Tags.member.2.Key", "Tags.member.1.Value"} {
|
||||
_, iamErr := roleAction(t, api, map[string]string{
|
||||
"Action": actionCreateRole, "RoleName": "app", "AssumeRolePolicyDocument": spiffeTrustPolicy, key: "x",
|
||||
})
|
||||
requireIamCode(t, iamErr, iam.ErrCodeInvalidInputException)
|
||||
}
|
||||
}
|
||||
|
||||
// unwritableRoleStore fails every write the way an unreachable filer does.
|
||||
type unwritableRoleStore struct{ *integration.MemoryRoleStore }
|
||||
|
||||
func (unwritableRoleStore) UpdateRole(context.Context, string, string, integration.RoleUpdate) error {
|
||||
return errors.New("store role: filer unavailable")
|
||||
}
|
||||
|
||||
// A store that cannot be written is a service failure, which clients retry;
|
||||
// only a bad request is InvalidInput.
|
||||
func TestCreateRoleReportsAFailedWriteAsAServiceFailure(t *testing.T) {
|
||||
api, mgr := newRoleTestAPI(t)
|
||||
mgr.SetRoleStore(unwritableRoleStore{integration.NewMemoryRoleStore()})
|
||||
|
||||
_, iamErr := roleAction(t, api, map[string]string{"Action": actionCreateRole, "RoleName": "app", "AssumeRolePolicyDocument": spiffeTrustPolicy})
|
||||
requireIamCode(t, iamErr, iam.ErrCodeServiceFailureException)
|
||||
|
||||
_, iamErr = roleAction(t, api, map[string]string{
|
||||
"Action": actionCreateRole, "RoleName": "app", "AssumeRolePolicyDocument": spiffeTrustPolicy, "MaxSessionDuration": "60",
|
||||
})
|
||||
requireIamCode(t, iamErr, iam.ErrCodeInvalidInputException)
|
||||
}
|
||||
|
||||
// racingRoleStore reports every role absent to plain reads while the store
|
||||
// holds them: the view of a server whose create raced another server's.
|
||||
type racingRoleStore struct{ *integration.MemoryRoleStore }
|
||||
|
||||
func (racingRoleStore) GetRole(_ context.Context, _ string, name string) (*integration.RoleDefinition, error) {
|
||||
return nil, fmt.Errorf("%w: %s", integration.ErrRoleNotFound, name)
|
||||
}
|
||||
|
||||
// Of two creates of one name, the second is told the role exists; it does
|
||||
// not replace the first role.
|
||||
func TestCreateRoleRacingAnotherCreateIsEntityAlreadyExists(t *testing.T) {
|
||||
api, mgr := newRoleTestAPI(t)
|
||||
store := racingRoleStore{integration.NewMemoryRoleStore()}
|
||||
require.NoError(t, store.StoreRole(context.Background(), "", "app", &integration.RoleDefinition{RoleName: "app", RoleId: "AROA-FIRST"}))
|
||||
mgr.SetRoleStore(store)
|
||||
|
||||
_, iamErr := roleAction(t, api, map[string]string{"Action": actionCreateRole, "RoleName": "app", "AssumeRolePolicyDocument": spiffeTrustPolicy})
|
||||
requireIamCode(t, iamErr, iam.ErrCodeEntityAlreadyExistsException)
|
||||
role, err := store.MemoryRoleStore.GetRole(context.Background(), "", "app")
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "AROA-FIRST", role.RoleId, "the second create replaced the first role")
|
||||
}
|
||||
|
||||
// vanishingRoleStore lists a role that is gone by the time it is read.
|
||||
type vanishingRoleStore struct{ *integration.MemoryRoleStore }
|
||||
|
||||
func (s vanishingRoleStore) ListRoles(ctx context.Context, filerAddress string) ([]string, error) {
|
||||
names, err := s.MemoryRoleStore.ListRoles(ctx, filerAddress)
|
||||
return append(names, "deleted-meanwhile"), err
|
||||
}
|
||||
|
||||
func TestListRolesSkipsARoleDeletedWhileListing(t *testing.T) {
|
||||
api, mgr := newRoleTestAPI(t)
|
||||
mgr.SetRoleStore(vanishingRoleStore{integration.NewMemoryRoleStore()})
|
||||
_, iamErr := roleAction(t, api, map[string]string{"Action": actionCreateRole, "RoleName": "app", "AssumeRolePolicyDocument": spiffeTrustPolicy})
|
||||
require.Nil(t, iamErr)
|
||||
|
||||
resp, iamErr := roleAction(t, api, map[string]string{"Action": actionListRoles})
|
||||
require.Nil(t, iamErr)
|
||||
roles := resp.(*iamlib.ListRolesResponse).ListRolesResult.Roles
|
||||
require.Len(t, roles, 1)
|
||||
assert.Equal(t, "app", roles[0].RoleName)
|
||||
}
|
||||
|
||||
// Peer role changes are watched in the role store's own directory.
|
||||
func TestRoleChangesAreWatchedInTheRoleStoresDirectory(t *testing.T) {
|
||||
api, mgr := newRoleTestAPI(t)
|
||||
s3a := &S3ApiServer{iam: api.iam}
|
||||
assert.Equal(t, rolesDir, s3a.roleStoreDir(), "a memory store falls back to the default directory")
|
||||
|
||||
store, err := integration.NewGenericCachedRoleStore(map[string]interface{}{"basePath": "/custom/roles"}, func() string { return "localhost:8888" })
|
||||
require.NoError(t, err)
|
||||
mgr.SetRoleStore(store)
|
||||
assert.Equal(t, "/custom/roles", s3a.roleStoreDir())
|
||||
}
|
||||
@@ -1103,6 +1103,7 @@ func (s3a *S3ApiServer) streamFromVolumeServers(w http.ResponseWriter, r *http.R
|
||||
tStreamPrep := time.Now()
|
||||
chunkViews := filer.ViewFromVisibleIntervals(visibleIntervals, offset, size)
|
||||
reader := filer.NewChunkReaderAtFromClient(ctx, s3a.readerCache, chunkViews, totalSize, filer.DefaultPrefetchCount)
|
||||
defer reader.ReleaseStream()
|
||||
streamPrepTime = time.Since(tStreamPrep)
|
||||
|
||||
// A cached chunk whose volume server is down, or whose needle was evicted and
|
||||
|
||||
@@ -29,10 +29,8 @@ type GetObjectAttributesResponse struct {
|
||||
|
||||
// ObjectAttributesChecksum holds checksum info for GetObjectAttributes.
|
||||
type ObjectAttributesChecksum struct {
|
||||
ChecksumCRC32 string `xml:"ChecksumCRC32,omitempty"`
|
||||
ChecksumCRC32C string `xml:"ChecksumCRC32C,omitempty"`
|
||||
ChecksumSHA1 string `xml:"ChecksumSHA1,omitempty"`
|
||||
ChecksumSHA256 string `xml:"ChecksumSHA256,omitempty"`
|
||||
ChecksumResult
|
||||
ChecksumType string `xml:"ChecksumType,omitempty"`
|
||||
}
|
||||
|
||||
// ObjectAttributesParts holds parts info for GetObjectAttributes.
|
||||
@@ -77,6 +75,24 @@ func validateObjectAttributes(attrs map[string]struct{}) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// objectAttributesChecksum returns the additional checksum that PutObject or
|
||||
// CompleteMultipartUpload stored with the object, or nil if it has none.
|
||||
func objectAttributesChecksum(entry *filer_pb.Entry) *ObjectAttributesChecksum {
|
||||
if entry == nil || entry.Extended == nil {
|
||||
return nil
|
||||
}
|
||||
value := string(entry.Extended[s3_constants.ExtChecksumValue])
|
||||
if value == "" {
|
||||
return nil
|
||||
}
|
||||
checksum := &ObjectAttributesChecksum{ChecksumType: string(entry.Extended[s3_constants.ExtChecksumType])}
|
||||
checksum.SetChecksum(string(entry.Extended[s3_constants.ExtChecksumAlgorithm]), value)
|
||||
if checksum.ChecksumResult == (ChecksumResult{}) {
|
||||
return nil
|
||||
}
|
||||
return checksum
|
||||
}
|
||||
|
||||
func (s3a *S3ApiServer) GetObjectAttributesHandler(w http.ResponseWriter, r *http.Request) {
|
||||
bucket, object := s3_constants.GetBucketAndObject(r)
|
||||
glog.V(3).Infof("GetObjectAttributesHandler %s %s", bucket, object)
|
||||
@@ -245,10 +261,9 @@ func (s3a *S3ApiServer) GetObjectAttributesHandler(w http.ResponseWriter, r *htt
|
||||
resp.StorageClass = storageClass
|
||||
}
|
||||
|
||||
// Checksum: accepted in validation so clients don't get a 400, but SeaweedFS
|
||||
// does not yet store S3 checksums (CRC32, CRC32C, SHA1, SHA256), so
|
||||
// resp.Checksum is intentionally left nil. When checksum storage is added,
|
||||
// populate resp.Checksum here.
|
||||
if _, ok := requestedAttrs["Checksum"]; ok {
|
||||
resp.Checksum = objectAttributesChecksum(entry)
|
||||
}
|
||||
|
||||
if _, ok := requestedAttrs["ObjectSize"]; ok {
|
||||
var size int64
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
package s3api
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/s3_constants"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestObjectAttributesChecksum verifies that GetObjectAttributes reports the
|
||||
// checksum that PutObject or CompleteMultipartUpload stored with the object
|
||||
func TestObjectAttributesChecksum(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
extended map[string][]byte
|
||||
want *ObjectAttributesChecksum
|
||||
}{
|
||||
{
|
||||
name: "PutObject with SHA256",
|
||||
extended: map[string][]byte{
|
||||
s3_constants.ExtChecksumAlgorithm: []byte(s3_constants.AmzChecksumSHA256),
|
||||
s3_constants.ExtChecksumValue: []byte("arcu6553sHVAiX4MjW0j7I7vD4w6R+Gz9Ok0Q9lTa+0="),
|
||||
},
|
||||
want: &ObjectAttributesChecksum{
|
||||
ChecksumResult: ChecksumResult{ChecksumSHA256: "arcu6553sHVAiX4MjW0j7I7vD4w6R+Gz9Ok0Q9lTa+0="},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "multipart upload with a composite CRC32C",
|
||||
extended: map[string][]byte{
|
||||
s3_constants.ExtChecksumAlgorithm: []byte(s3_constants.AmzChecksumCRC32C),
|
||||
s3_constants.ExtChecksumValue: []byte("x3Y2bw==-3"),
|
||||
s3_constants.ExtChecksumType: []byte("COMPOSITE"),
|
||||
},
|
||||
want: &ObjectAttributesChecksum{
|
||||
ChecksumResult: ChecksumResult{ChecksumCRC32C: "x3Y2bw==-3"},
|
||||
ChecksumType: "COMPOSITE",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "multipart upload with a full object CRC64NVME",
|
||||
extended: map[string][]byte{
|
||||
s3_constants.ExtChecksumAlgorithm: []byte(s3_constants.AmzChecksumCRC64NVME),
|
||||
s3_constants.ExtChecksumValue: []byte("AAAAAAAAAAA="),
|
||||
s3_constants.ExtChecksumType: []byte("FULL_OBJECT"),
|
||||
},
|
||||
want: &ObjectAttributesChecksum{
|
||||
ChecksumResult: ChecksumResult{ChecksumCRC64NVME: "AAAAAAAAAAA="},
|
||||
ChecksumType: "FULL_OBJECT",
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "no checksum",
|
||||
extended: map[string][]byte{s3_constants.ExtETagKey: []byte("d41d8cd98f00b204e9800998ecf8427e")},
|
||||
},
|
||||
{
|
||||
name: "unknown algorithm",
|
||||
extended: map[string][]byte{
|
||||
s3_constants.ExtChecksumAlgorithm: []byte("X-Amz-Checksum-Md5"),
|
||||
s3_constants.ExtChecksumValue: []byte("1B2M2Y8AsgTpgAmY7PhCfg=="),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
assert.Equal(t, tc.want, objectAttributesChecksum(&filer_pb.Entry{Extended: tc.extended}))
|
||||
})
|
||||
}
|
||||
assert.Nil(t, objectAttributesChecksum(&filer_pb.Entry{}))
|
||||
}
|
||||
|
||||
// TestGetObjectAttributesChecksumXML verifies the Checksum element's layout
|
||||
func TestGetObjectAttributesChecksumXML(t *testing.T) {
|
||||
resp := GetObjectAttributesResponse{
|
||||
Checksum: &ObjectAttributesChecksum{
|
||||
ChecksumResult: ChecksumResult{ChecksumCRC32: "NhCmhg=="},
|
||||
ChecksumType: "FULL_OBJECT",
|
||||
},
|
||||
}
|
||||
out, err := xml.Marshal(resp)
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, "<GetObjectAttributesResponse><Checksum><ChecksumCRC32>NhCmhg==</ChecksumCRC32>"+
|
||||
"<ChecksumType>FULL_OBJECT</ChecksumType></Checksum></GetObjectAttributesResponse>", string(out))
|
||||
}
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -792,6 +793,19 @@ type CopyPartResult struct {
|
||||
ChecksumResult
|
||||
}
|
||||
|
||||
// MarshalXML writes LastModified in the S3 timestamp format (see xsdDateTime)
|
||||
// instead of encoding/xml's RFC 3339 with trimmed fractional seconds.
|
||||
func (r CopyPartResult) MarshalXML(e *xml.Encoder, start xml.StartElement) error {
|
||||
type T CopyPartResult
|
||||
var layout struct {
|
||||
*T
|
||||
LastModified xsdDateTime `xml:"LastModified"`
|
||||
}
|
||||
layout.T = (*T)(&r)
|
||||
layout.LastModified = xsdDateTime(r.LastModified)
|
||||
return e.EncodeElement(layout, start)
|
||||
}
|
||||
|
||||
func buildCopyPartResult(etag string, lastModified time.Time, metadata SSEResponseMetadata) CopyPartResult {
|
||||
result := CopyPartResult{
|
||||
ETag: etag,
|
||||
@@ -1183,7 +1197,11 @@ func processMetadataBytes(reqHeader http.Header, existing map[string][]byte, rep
|
||||
}
|
||||
}
|
||||
for _, h := range copyReplaceSystemHeaders {
|
||||
if v := reqHeader.Get(h); v != "" {
|
||||
v := reqHeader.Get(h)
|
||||
if h == "Content-Encoding" {
|
||||
v = storedContentEncoding(reqHeader.Values(h))
|
||||
}
|
||||
if v != "" {
|
||||
metadata[h] = []byte(v)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -813,6 +813,19 @@ func markerSortsBeforePrefix(prefix, marker string) bool {
|
||||
return !strings.HasPrefix(marker, prefix) && marker < prefix
|
||||
}
|
||||
|
||||
// markerSortsPastPrefix reports whether marker lies beyond the last key the
|
||||
// prefix can match. A marker that diverges from the prefix at a larger byte
|
||||
// is after every key under it, so the listing is empty no matter where the
|
||||
// walk would resume.
|
||||
func markerSortsPastPrefix(prefix, marker string) bool {
|
||||
prefix = strings.TrimLeft(prefix, "/")
|
||||
marker = strings.TrimLeft(marker, "/")
|
||||
if marker == "" || prefix == "" {
|
||||
return false
|
||||
}
|
||||
return !strings.HasPrefix(marker, prefix) && marker > prefix
|
||||
}
|
||||
|
||||
// the prefix and marker may be in different directories
|
||||
// normalizePrefixMarker ensures the prefix and marker both starts from the same directory.
|
||||
// prefixEndsOnDelimiter tells the walk that the prefix names one directory, whose own key
|
||||
@@ -912,6 +925,13 @@ func (s3a *S3ApiServer) doListFilerEntries(ctx context.Context, client filer_pb.
|
||||
return // Don't set isTruncated here - let caller decide based on whether more entries exist
|
||||
}
|
||||
|
||||
// A marker past the prefix's range leaves nothing under the prefix to
|
||||
// resume at, and descending into the marker's own directory below would
|
||||
// drop the prefix filter entirely.
|
||||
if markerSortsPastPrefix(prefix, marker) {
|
||||
return
|
||||
}
|
||||
|
||||
if strings.Contains(marker, "/") {
|
||||
subDir, subMarker := toParentAndDescendants(marker)
|
||||
// println("doListFilerEntries dir", dir+"/"+subDir, "subMarker", subMarker)
|
||||
|
||||
@@ -36,6 +36,75 @@ func Test_markerSortsBeforePrefix(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// A marker that sorts past the prefix leaves no key under the prefix to resume
|
||||
// at, so the listing is empty instead of continuing into later prefixes.
|
||||
func Test_markerSortsPastPrefix(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
prefix string
|
||||
marker string
|
||||
want bool
|
||||
}{
|
||||
{"marker is a later directory", "b/", "c/", true},
|
||||
{"marker is a later key without a slash", "b/", "c", true},
|
||||
{"marker shares the parent dir but sorts past", "data/a", "data/b", true},
|
||||
{"marker diverges after the prefix", "b/", "b0/x", true},
|
||||
{"leading slashes are ignored on both sides", "/b/", "/c/", true},
|
||||
{"empty marker is in range", "b/", "", false},
|
||||
{"empty prefix: every key is in scope", "", "c/", false},
|
||||
{"marker under the prefix resumes inside it", "b/", "b/allowed-1", false},
|
||||
{"marker equal to the prefix stands", "b/", "b/", false},
|
||||
{"partial name prefix: marker under the match set stands", "parent", "parentDir/data/0e", false},
|
||||
{"marker before the prefix is not past it", "b/", "a/", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
assert.Equal(t, tt.want, markerSortsPastPrefix(tt.prefix, tt.marker), "markerSortsPastPrefix(%q, %q)", tt.prefix, tt.marker)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestListWithMarkerPastPrefix walks the listing the way listFilerEntries does
|
||||
// for a start position past the requested prefix. normalizePrefixMarker hands
|
||||
// such a marker through at the bucket root, where the walk's marker descent
|
||||
// would otherwise drop the prefix filter and continue into a later prefix.
|
||||
func TestListWithMarkerPastPrefix(t *testing.T) {
|
||||
client := &testFilerClient{
|
||||
entriesByDir: map[string][]*filer_pb.Entry{
|
||||
"/buckets/test": {newDir("a"), newDir("b"), newDir("c")},
|
||||
"/buckets/test/b": {{Name: "allowed-1", Attributes: &filer_pb.FuseAttributes{}}},
|
||||
"/buckets/test/c": {{Name: "other-2", Attributes: &filer_pb.FuseAttributes{}}},
|
||||
"/buckets/test/c/z": {{Name: "deep", Attributes: &filer_pb.FuseAttributes{}}},
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
marker string
|
||||
want []string
|
||||
}{
|
||||
{"marker is a later directory", "c/", nil},
|
||||
{"marker is a deeper path in a later directory", "c/z", nil},
|
||||
{"marker is a later bare key", "c", nil},
|
||||
{"marker inside the prefix resumes normally", "b/", []string{"allowed-1"}},
|
||||
} {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
requestDir, entryPrefix, entryMarker, prefixEndsOnDelimiter := normalizePrefixMarker("b/", tt.marker)
|
||||
dir := "/buckets/test"
|
||||
if requestDir != "" {
|
||||
dir += "/" + requestDir
|
||||
}
|
||||
seen := listedNames(t, client, listDirectoryRequest{
|
||||
dir: dir,
|
||||
prefix: entryPrefix,
|
||||
marker: entryMarker,
|
||||
bucket: "test",
|
||||
}, &ListingCursor{maxKeys: 1000, prefixEndsOnDelimiter: prefixEndsOnDelimiter})
|
||||
assert.Equal(t, tt.want, seen)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// A marker ending on the delimiter is trimmed to a shorter cutoff for the walk, which no
|
||||
// longer excludes the key the client named, so that key is skipped as it streams.
|
||||
func Test_excludedMarkerKey(t *testing.T) {
|
||||
|
||||
Loaded 100 of 147 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user