mirror of
https://github.com/seaweedfs/seaweedfs.git
synced 2026-12-04 18:17:16 +01:00
Compare commits
69
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
578fed7d30 | ||
|
|
6b701a94c4 | ||
|
|
18b51253da | ||
|
|
280f620b55 | ||
|
|
503b6f2744 | ||
|
|
21fadf5582 | ||
|
|
0b3cc8d121 | ||
|
|
6cbcdf488c | ||
|
|
c934b5dab6 | ||
|
|
4f628ff4e5 | ||
|
|
dc462a80d7 | ||
|
|
f407bdaa36 | ||
|
|
0716577ec8 | ||
|
|
654292b57d | ||
|
|
525900dfe4 | ||
|
|
5eead9409a | ||
|
|
a14cbc176b | ||
|
|
f1f720f5da | ||
|
|
d65c568cbb | ||
|
|
fe1d7a404d | ||
|
|
8815844278 | ||
|
|
93247d6de4 | ||
|
|
352ffdffe1 | ||
|
|
29e14f89f1 | ||
|
|
88c2f3c34d | ||
|
|
da2e90aefd | ||
|
|
a0be40e070 | ||
|
|
b94ad82472 | ||
|
|
cd5004cfbd | ||
|
|
5cbcfd311c | ||
|
|
76f361fa77 | ||
|
|
3d39324bc1 | ||
|
|
20f4fd9985 | ||
|
|
0fcd5173be | ||
|
|
749430dceb | ||
|
|
036191c78a | ||
|
|
34b236acfa | ||
|
|
1a7ab2ea82 | ||
|
|
ae93f87a46 | ||
|
|
6e950e0e7e | ||
|
|
ede766645a | ||
|
|
592d6d6021 | ||
|
|
f438cc3544 | ||
|
|
628363c4a6 | ||
|
|
8ae07e2a3f | ||
|
|
c6302fcb54 | ||
|
|
fff243d463 | ||
|
|
cb882ced46 | ||
|
|
c4e1885053 | ||
|
|
0f5e99f423 | ||
|
|
1220468a33 | ||
|
|
be9996962d | ||
|
|
96e5fea08e | ||
|
|
7f67995c24 | ||
|
|
9ae905e456 | ||
|
|
7364f148bd | ||
|
|
05f0f7e1c9 | ||
|
|
45ba71a189 | ||
|
|
c40db5a52d | ||
|
|
141413ad76 | ||
|
|
0a5c22b57e | ||
|
|
e77f8ae204 | ||
|
|
0007245c7f | ||
|
|
49f62df2cf | ||
|
|
06ccd0e9fc | ||
|
|
eaab3ec5d0 | ||
|
|
caaa53aee3 | ||
|
|
e725eb4079 | ||
|
|
08a7502b2c |
No files matched your search
@@ -217,6 +217,106 @@ jobs:
|
||||
print("✓ No blank lines in security+S3 command blocks")
|
||||
PYEOF
|
||||
|
||||
echo ""
|
||||
echo "=== Testing security+S3: -cert.file/-key.file gated on httpsPort (issue #9202) ==="
|
||||
# Regression test: when enableSecurity=true but *.httpsPort is 0 (the default),
|
||||
# the chart must NOT emit -cert.file / -key.file to the S3 frontend. Passing
|
||||
# them promotes weed s3's main -port to HTTPS (see weed/command/s3.go), which
|
||||
# makes the HTTP readinessProbe spam "TLS handshake error ... client sent an
|
||||
# HTTP request to an HTTPS server" into the pod log.
|
||||
#
|
||||
# When *.httpsPort > 0, both -port.https and cert/key args MUST be emitted
|
||||
# together so the opt-in HTTPS listener actually has credentials.
|
||||
python3 - "$CHART_DIR" <<'PYEOF'
|
||||
import subprocess, sys, yaml
|
||||
chart = sys.argv[1]
|
||||
|
||||
def render(values):
|
||||
args = ["helm", "template", "test", chart]
|
||||
for k, v in values.items():
|
||||
args += ["--set", f"{k}={v}"]
|
||||
return subprocess.check_output(args, text=True)
|
||||
|
||||
def script_of(manifest, kind_name):
|
||||
for doc in yaml.safe_load_all(manifest):
|
||||
if not doc or doc.get("kind") not in ("Deployment", "StatefulSet"):
|
||||
continue
|
||||
if doc["metadata"]["name"] != kind_name:
|
||||
continue
|
||||
for c in doc["spec"]["template"]["spec"]["containers"]:
|
||||
cmd = c.get("command", [])
|
||||
if len(cmd) >= 3 and cmd[0] == "/bin/sh" and cmd[1] == "-ec":
|
||||
return cmd[2]
|
||||
raise AssertionError(f"no container script for {kind_name}")
|
||||
|
||||
cases = [
|
||||
# (values, workload-name, httpsPort-set?, arg-prefix)
|
||||
({"global.seaweedfs.enableSecurity": "true",
|
||||
"s3.enabled": "true"},
|
||||
"test-seaweedfs-s3", False, ""),
|
||||
({"global.seaweedfs.enableSecurity": "true",
|
||||
"s3.enabled": "true",
|
||||
"s3.httpsPort": "8443"},
|
||||
"test-seaweedfs-s3", True, ""),
|
||||
({"global.seaweedfs.enableSecurity": "true",
|
||||
"filer.s3.enabled": "true"},
|
||||
"test-seaweedfs-filer", False, "s3."),
|
||||
({"global.seaweedfs.enableSecurity": "true",
|
||||
"filer.s3.enabled": "true",
|
||||
"filer.s3.httpsPort": "8444"},
|
||||
"test-seaweedfs-filer", True, "s3."),
|
||||
({"global.seaweedfs.enableSecurity": "true",
|
||||
"allInOne.enabled": "true",
|
||||
"allInOne.s3.enabled": "true"},
|
||||
"test-seaweedfs-all-in-one", False, "s3."),
|
||||
({"global.seaweedfs.enableSecurity": "true",
|
||||
"allInOne.enabled": "true",
|
||||
"allInOne.s3.enabled": "true",
|
||||
"allInOne.s3.httpsPort": "8445"},
|
||||
"test-seaweedfs-all-in-one", True, "s3."),
|
||||
]
|
||||
|
||||
failed = False
|
||||
for values, name, https_on, prefix in cases:
|
||||
script = script_of(render(values), name)
|
||||
cert_flag = f"-{prefix}cert.file="
|
||||
key_flag = f"-{prefix}key.file="
|
||||
https_flag = f"-{prefix}port.https="
|
||||
has_cert = cert_flag in script
|
||||
has_key = key_flag in script
|
||||
has_https = https_flag in script
|
||||
label = f"{name} (httpsPort {'set' if https_on else 'unset'})"
|
||||
if https_on:
|
||||
if not (has_cert and has_key and has_https):
|
||||
print(f"FAIL: {label}: expected {cert_flag}, {key_flag}, {https_flag} all present "
|
||||
f"(got cert={has_cert} key={has_key} https={has_https})", file=sys.stderr)
|
||||
failed = True
|
||||
else:
|
||||
print(f"✓ {label}: cert/key/https args emitted together")
|
||||
else:
|
||||
if has_cert or has_key or has_https:
|
||||
print(f"FAIL: {label}: expected none of {cert_flag}/{key_flag}/{https_flag}; "
|
||||
f"main S3 -port would silently become HTTPS and break HTTP probes "
|
||||
f"(got cert={has_cert} key={has_key} https={has_https})", file=sys.stderr)
|
||||
failed = True
|
||||
else:
|
||||
print(f"✓ {label}: no TLS args emitted, main -port stays HTTP")
|
||||
|
||||
# bash -n: pin down that the rendered script parses. Guards against
|
||||
# a future helper change that leaves a dangling `\` with nothing
|
||||
# after it (every current caller already exits cleanly because
|
||||
# bash treats trailing `\<newline><EOF>` as line-continuation to
|
||||
# an empty line — but keep the contract explicit).
|
||||
parse = subprocess.run(["bash", "-n"], input=script, text=True,
|
||||
capture_output=True)
|
||||
if parse.returncode != 0:
|
||||
print(f"FAIL: {label}: bash -n rejected rendered script: {parse.stderr.strip()}",
|
||||
file=sys.stderr)
|
||||
failed = True
|
||||
|
||||
sys.exit(1 if failed else 0)
|
||||
PYEOF
|
||||
|
||||
echo "✅ All template rendering tests passed!"
|
||||
|
||||
- name: Create kind cluster
|
||||
|
||||
@@ -84,7 +84,7 @@ jobs:
|
||||
timeout-minutes: 25
|
||||
strategy:
|
||||
matrix:
|
||||
test-type: ["basic", "advanced", "policy-enforcement", "group"]
|
||||
test-type: ["basic", "advanced", "policy-enforcement", "group", "sts"]
|
||||
|
||||
steps:
|
||||
- name: Check out code
|
||||
@@ -138,6 +138,23 @@ jobs:
|
||||
make clean setup start-services wait-for-services
|
||||
go test -v -timeout 15m -run "TestIAMGroup" ./...
|
||||
;;
|
||||
"sts")
|
||||
echo "Running STS and service account tests..."
|
||||
make clean setup start-services wait-for-services
|
||||
# SigV4-signed STS calls need admin credentials matching test_config.json.
|
||||
# Tests default to "admin"/"admin" when env vars are unset, which don't exist.
|
||||
export STS_TEST_ACCESS_KEY=test-access-key
|
||||
export STS_TEST_SECRET_KEY=test-secret-key
|
||||
# The use_service_account_credentials subtest is excluded because
|
||||
# newly-created service-account access keys are not currently
|
||||
# persisted to the filer after CreateServiceAccount — a
|
||||
# pre-existing sync issue tracked separately from the
|
||||
# GetFederationToken routing fix this PR addresses.
|
||||
go test -v -timeout 15m \
|
||||
-run "TestSTS|TestAssumeRoleWithWebIdentity|TestServiceAccount" \
|
||||
-skip "TestServiceAccountLifecycle/use_service_account_credentials" \
|
||||
./...
|
||||
;;
|
||||
*)
|
||||
echo "Unknown test type: ${{ matrix.test-type }}"
|
||||
exit 1
|
||||
|
||||
@@ -0,0 +1,56 @@
|
||||
name: "TLS Rotation Integration Tests"
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: [ master ]
|
||||
pull_request:
|
||||
branches: [ master ]
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
tls-rotation-tests:
|
||||
name: TLS Rotation Integration Tests
|
||||
runs-on: ubuntu-22.04
|
||||
timeout-minutes: 10
|
||||
steps:
|
||||
- name: Set up Go 1.x
|
||||
uses: actions/setup-go@v6
|
||||
with:
|
||||
go-version: ^1.25
|
||||
id: go
|
||||
|
||||
- name: Check out code into the Go module directory
|
||||
uses: actions/checkout@v6
|
||||
|
||||
- name: Build weed binary
|
||||
run: |
|
||||
cd weed && go build -o weed .
|
||||
|
||||
- name: Run TLS Rotation Integration Tests
|
||||
working-directory: test/tls_rotation
|
||||
run: |
|
||||
go test -v -count=1 -timeout 5m
|
||||
|
||||
- name: Collect server logs on failure
|
||||
if: failure()
|
||||
run: |
|
||||
echo "Collecting master logs from temp directories..."
|
||||
mkdir -p /tmp/tls-rotation-test-logs
|
||||
find /tmp -maxdepth 1 -type d -name "TestMasterHTTPS*" 2>/dev/null | while read dir; do
|
||||
if [ -d "$dir" ]; then
|
||||
echo "Found test directory: $dir"
|
||||
cp -r "$dir" /tmp/tls-rotation-test-logs/ 2>/dev/null || true
|
||||
fi
|
||||
done
|
||||
echo "Collected logs:"
|
||||
find /tmp/tls-rotation-test-logs -type f -name "*.log" 2>/dev/null || echo "No logs found"
|
||||
|
||||
- name: Archive logs
|
||||
if: failure()
|
||||
uses: actions/upload-artifact@v7
|
||||
with:
|
||||
name: tls-rotation-test-logs
|
||||
path: /tmp/tls-rotation-test-logs/
|
||||
retention-days: 14
|
||||
@@ -39,7 +39,7 @@ require (
|
||||
github.com/hashicorp/errwrap v1.1.0 // indirect
|
||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
github.com/hashicorp/go-uuid v1.0.3 // indirect
|
||||
github.com/jackc/pgx/v5 v5.9.0
|
||||
github.com/jackc/pgx/v5 v5.9.2
|
||||
github.com/jcmturner/gofork v1.7.6 // indirect
|
||||
github.com/jcmturner/gokrb5/v8 v8.4.4 // indirect
|
||||
github.com/jinzhu/copier v0.4.0
|
||||
@@ -303,7 +303,7 @@ require (
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.5.3 // indirect
|
||||
github.com/Azure/go-ntlmssp v0.1.0 // indirect
|
||||
github.com/Azure/go-ntlmssp v0.1.1 // indirect
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 // indirect
|
||||
github.com/Files-com/files-sdk-go/v3 v3.2.264 // indirect
|
||||
github.com/GoogleCloudPlatform/opentelemetry-operations-go/detectors/gcp v1.30.0 // indirect
|
||||
|
||||
@@ -577,8 +577,8 @@ github.com/Azure/go-autorest v14.2.0+incompatible h1:V5VMDjClD3GiElqLWO7mz2MxNAK
|
||||
github.com/Azure/go-autorest v14.2.0+incompatible/go.mod h1:r+4oMnoxhatjLLJ6zxSWATqVooLgysK6ZNox3g/xq24=
|
||||
github.com/Azure/go-autorest/autorest/to v0.4.1 h1:CxNHBqdzTr7rLtdrtb5CMjJcDut+WNGCVv7OmS5+lTc=
|
||||
github.com/Azure/go-autorest/autorest/to v0.4.1/go.mod h1:EtaofgU4zmtvn1zT2ARsjRFdq9vXx0YWtmElwL+GZ9M=
|
||||
github.com/Azure/go-ntlmssp v0.1.0 h1:DjFo6YtWzNqNvQdrwEyr/e4nhU3vRiwenz5QX7sFz+A=
|
||||
github.com/Azure/go-ntlmssp v0.1.0/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk=
|
||||
github.com/Azure/go-ntlmssp v0.1.1 h1:l+FM/EEMb0U9QZE7mKNEDw5Mu3mFiaa2GKOoTSsNDPw=
|
||||
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.6.0 h1:XRzhVemXdgvJqCH0sFfrBUTnUJSBrBf7++ypk+twtRs=
|
||||
@@ -1403,8 +1403,8 @@ github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsI
|
||||
github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761 h1:iCEnooe7UlwOQYpKFhBabPMi4aNAfoODPEFNiAnClxo=
|
||||
github.com/jackc/pgservicefile v0.0.0-20240606120523-5a60cdf6a761/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM=
|
||||
github.com/jackc/pgx/v5 v5.9.0 h1:T/dI+2TvmI2H8s/KH1/lXIbz1CUFk3gn5oTjr0/mBsE=
|
||||
github.com/jackc/pgx/v5 v5.9.0/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/pgx/v5 v5.9.2 h1:3ZhOzMWnR4yJ+RW1XImIPsD1aNSz4T4fyP7zlQb56hw=
|
||||
github.com/jackc/pgx/v5 v5.9.2/go.mod h1:mal1tBGAFfLHvZzaYh77YS/eC6IX9OWbRV1QIIM0Jn4=
|
||||
github.com/jackc/puddle/v2 v2.2.2 h1:PR8nw+E/1w0GLuRFSmiioY6UooMp6KJv0/61nB7icHo=
|
||||
github.com/jackc/puddle/v2 v2.2.2/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4=
|
||||
github.com/jaegertracing/jaeger v1.47.0 h1:XXxTMO+GxX930gxKWsg90rFr6RswkCRIW0AgWFnTYsg=
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
apiVersion: v1
|
||||
description: SeaweedFS
|
||||
name: seaweedfs
|
||||
appVersion: "4.21"
|
||||
appVersion: "4.22"
|
||||
# Dev note: Trigger a helm chart release by `git tag -a helm-<version>`
|
||||
version: 4.21.0
|
||||
version: 4.22.0
|
||||
@@ -247,9 +247,9 @@ spec:
|
||||
{{- $httpsPort := .Values.allInOne.s3.httpsPort | default .Values.s3.httpsPort }}
|
||||
{{- if $httpsPort }}
|
||||
-s3.port.https={{ $httpsPort }} \
|
||||
{{- end }}
|
||||
{{- include "seaweedfs.s3.tlsArgs" (dict "root" . "prefix" "s3.") | nindent 14 }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if or .Values.allInOne.s3.enableAuth .Values.s3.enableAuth .Values.filer.s3.enableAuth }}
|
||||
-s3.config=/etc/sw/s3/seaweedfs_s3_config \
|
||||
{{- end }}
|
||||
|
||||
@@ -200,9 +200,9 @@ spec:
|
||||
{{- if .Values.global.seaweedfs.enableSecurity }}
|
||||
{{- if .Values.filer.s3.httpsPort }}
|
||||
-s3.port.https={{ .Values.filer.s3.httpsPort }} \
|
||||
{{- end }}
|
||||
{{- include "seaweedfs.s3.tlsArgs" (dict "root" . "prefix" "s3.") | nindent 14 }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if .Values.filer.s3.enableAuth }}
|
||||
-s3.config=/etc/sw/seaweedfs_s3_config \
|
||||
{{- end }}
|
||||
|
||||
@@ -127,9 +127,9 @@ spec:
|
||||
{{- if .Values.global.seaweedfs.enableSecurity }}
|
||||
{{- if .Values.s3.httpsPort }}
|
||||
-port.https={{ .Values.s3.httpsPort }} \
|
||||
{{- end }}
|
||||
{{- include "seaweedfs.s3.tlsArgs" (dict "root" . "prefix" "") | nindent 14 }}
|
||||
{{- end }}
|
||||
{{- end }}
|
||||
{{- if .Values.s3.domainName }}
|
||||
-domainName={{ .Values.s3.domainName }} \
|
||||
{{- end }}
|
||||
|
||||
@@ -0,0 +1,31 @@
|
||||
MARP ?= npx @marp-team/marp-cli
|
||||
SRC := seaweedfs-production-setup.md
|
||||
PDF := $(SRC:.md=.pdf)
|
||||
HTML := $(SRC:.md=.html)
|
||||
PPTX := $(SRC:.md=.pptx)
|
||||
FLAGS := --allow-local-files
|
||||
|
||||
.PHONY: all pdf html pptx watch clean
|
||||
|
||||
all: pdf
|
||||
|
||||
pdf: $(PDF)
|
||||
|
||||
html: $(HTML)
|
||||
|
||||
pptx: $(PPTX)
|
||||
|
||||
$(PDF): $(SRC)
|
||||
$(MARP) $(SRC) --pdf $(FLAGS) -o $@
|
||||
|
||||
$(HTML): $(SRC)
|
||||
$(MARP) $(SRC) --html $(FLAGS) -o $@
|
||||
|
||||
$(PPTX): $(SRC)
|
||||
$(MARP) $(SRC) --pptx $(FLAGS) -o $@
|
||||
|
||||
watch:
|
||||
$(MARP) $(SRC) --watch --html $(FLAGS)
|
||||
|
||||
clean:
|
||||
rm -f $(PDF) $(HTML) $(PPTX)
|
||||
Binary file not shown.
|
After Width: | Height: | Size: 738 KiB |
@@ -0,0 +1,118 @@
|
||||
---
|
||||
marp: true
|
||||
theme: default
|
||||
paginate: true
|
||||
---
|
||||
|
||||
# SeaweedFS Production Setup
|
||||
|
||||
A walkthrough of the recommended deployment topology
|
||||
|
||||
- Storage layer
|
||||
- File access layer
|
||||
- Backend operations
|
||||
- Erasure coding for durability
|
||||
|
||||
---
|
||||
|
||||

|
||||
|
||||
---
|
||||
|
||||
# Storage Layer
|
||||
|
||||
**3 Masters + Volume Servers**
|
||||
|
||||
- **Masters (run 3)**
|
||||
- Form a Raft quorum; tolerate 1 failure
|
||||
- Track volume locations and cluster topology
|
||||
- Lightweight; not on the data path for reads/writes after lookup
|
||||
|
||||
- **Volume Servers (scale out)**
|
||||
- Hold the actual needle data on local disks
|
||||
- Add more servers for capacity and throughput
|
||||
- Heartbeat to masters; clients talk to them directly for I/O
|
||||
|
||||
Rule of thumb: start with 3 masters, then grow volume servers with data.
|
||||
|
||||
---
|
||||
|
||||
# File Access Layer
|
||||
|
||||
**Filer + DB for metadata**
|
||||
|
||||
- Filer serves POSIX-like directory and file metadata
|
||||
- Metadata store options: PostgreSQL, MySQL, Redis, Cassandra, TiKV, etc.
|
||||
- Run **3 filers** for HA
|
||||
- Filers are stateless relative to each other — state lives in the DB
|
||||
|
||||
**S3 Servers**
|
||||
|
||||
- Expose the S3 API on top of the filer
|
||||
- Scale the count based on throughput requirements
|
||||
- Can be co-located with filers or run independently
|
||||
|
||||
---
|
||||
|
||||
# Backend Operations
|
||||
|
||||
**1 Admin Server + a few Workers**
|
||||
|
||||
- **Admin server (1 is enough)**
|
||||
- Coordinates background jobs: balancing, EC encoding, vacuum, replication fixes
|
||||
- **Not on the data path** — a restart does not affect object store reads/writes
|
||||
- No HA required for normal operation
|
||||
|
||||
- **Workers (a few)**
|
||||
- Execute long-running tasks issued by the admin server
|
||||
- Horizontally scalable based on maintenance workload
|
||||
|
||||
Keeps housekeeping off the hot path.
|
||||
|
||||
---
|
||||
|
||||
# Production Topology Summary
|
||||
|
||||
| Component | Count | Role |
|
||||
|----------------|----------------------|-----------------------------------|
|
||||
| Master | 3 | Raft quorum, topology, volume map |
|
||||
| Volume Server | N (scale out) | Stores data needles |
|
||||
| Filer | 3 | Metadata gateway |
|
||||
| Metadata DB | HA cluster | Persists filer metadata |
|
||||
| S3 Server | N (by throughput) | S3 API frontend |
|
||||
| Admin | 1 | Background job coordinator |
|
||||
| Worker | A few | Executes admin-scheduled tasks |
|
||||
|
||||
---
|
||||
|
||||
# Erasure Coding for Durability
|
||||
|
||||
Prefer **many volume servers** so EC shards spread across failure domains.
|
||||
|
||||
**Example: 8 volume servers, EC 5+3**
|
||||
|
||||
- Each volume becomes 5 data shards + 3 parity shards
|
||||
- Shards are placed on 8 distinct volume servers
|
||||
- **Tolerates up to 3 simultaneous volume server failures**
|
||||
- Storage overhead: 1.6x vs 3x for full replication
|
||||
|
||||
```
|
||||
Volume -> [D1][D2][D3][D4][D5] + [P1][P2][P3]
|
||||
| | | | | | | |
|
||||
VS1 VS2 VS3 VS4 VS5 VS6 VS7 VS8
|
||||
```
|
||||
|
||||
More volume servers = more EC layouts available (e.g. 10+4, 6+3).
|
||||
|
||||
---
|
||||
|
||||
# Getting Started Checklist
|
||||
|
||||
1. Provision 3 master nodes (small boxes are fine)
|
||||
2. Provision volume servers sized to your data footprint
|
||||
3. Stand up an HA metadata DB, then 3 filers pointing at it
|
||||
4. Add S3 servers sized to required throughput
|
||||
5. Run 1 admin + a few workers for background maintenance
|
||||
6. Once you have enough volume servers, enable EC (e.g. 5+3 on 8 servers)
|
||||
|
||||
Scale each layer independently as usage grows.
|
||||
Generated
+2
-2
@@ -3350,9 +3350,9 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "rustls-webpki"
|
||||
version = "0.103.10"
|
||||
version = "0.103.13"
|
||||
source = "registry+https://github.com/rust-lang/crates.io-index"
|
||||
checksum = "df33b2b81ac578cabaf06b89b0631153a3f416b0a886e8a7a1707fb51abbd1ef"
|
||||
checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"
|
||||
dependencies = [
|
||||
"aws-lc-rs",
|
||||
"ring",
|
||||
|
||||
@@ -339,6 +339,7 @@ message ReceiveFileInfo {
|
||||
bool is_ec_volume = 4;
|
||||
uint32 shard_id = 5;
|
||||
uint64 file_size = 6;
|
||||
uint32 disk_id = 7; // EC shard disk; 0 = auto-select (see VolumeEcShardsCopyRequest.disk_id)
|
||||
}
|
||||
|
||||
message ReceiveFileResponse {
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 70 B After Width: | Height: | Size: 6.6 KiB |
@@ -1425,13 +1425,43 @@ impl VolumeServer for VolumeGrpcService {
|
||||
// Determine file path
|
||||
let path = if info.is_ec_volume {
|
||||
let store = self.state.store.read().unwrap();
|
||||
// Go prefers a HardDriveType location, then falls back to first
|
||||
let dir = store
|
||||
.locations
|
||||
.iter()
|
||||
.find(|loc| loc.disk_type == DiskType::HardDrive)
|
||||
.or_else(|| store.locations.first())
|
||||
.map(|loc| loc.directory.clone());
|
||||
// std::fs::File::create truncates in place; a mounted
|
||||
// EcVolume holds fds on the same inodes, so overwriting
|
||||
// corrupts live readers.
|
||||
if store.has_ec_volume(VolumeId(info.volume_id)) {
|
||||
resp_error = Some(format!(
|
||||
"ec volume {} is mounted; unmount before ReceiveFile",
|
||||
info.volume_id
|
||||
));
|
||||
break;
|
||||
}
|
||||
// disk_id=0 means "unset" (protobuf default), so auto-select
|
||||
// mirrors VolumeEcShardsCopy: prefer a disk already holding
|
||||
// this volume's shards, then any HDD, then any disk.
|
||||
let vid = VolumeId(info.volume_id);
|
||||
let dir = if info.disk_id > 0 {
|
||||
let count = store.locations.len();
|
||||
if (info.disk_id as usize) >= count {
|
||||
resp_error = Some(format!(
|
||||
"invalid disk_id {}: only have {} disks",
|
||||
info.disk_id, count
|
||||
));
|
||||
break;
|
||||
}
|
||||
Some(store.locations[info.disk_id as usize].directory.clone())
|
||||
} else {
|
||||
let loc_idx = store
|
||||
.find_free_location_predicate(|loc| loc.has_ec_volume(vid))
|
||||
.or_else(|| {
|
||||
store.find_free_location_predicate(|loc| {
|
||||
loc.disk_type == DiskType::HardDrive
|
||||
})
|
||||
})
|
||||
.or_else(|| {
|
||||
store.find_free_location_predicate(|_| true)
|
||||
});
|
||||
loc_idx.map(|i| store.locations[i].directory.clone())
|
||||
};
|
||||
drop(store);
|
||||
let dir = match dir {
|
||||
Some(d) => d,
|
||||
|
||||
@@ -492,7 +492,8 @@ impl Store {
|
||||
let vol_count = loc.volumes_len() as i32;
|
||||
let loc_ec_shards = loc.ec_shard_count();
|
||||
let ec_equivalent = ((loc_ec_shards
|
||||
+ crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT)
|
||||
+ crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT
|
||||
- 1)
|
||||
/ crate::storage::erasure_coding::ec_shard::DATA_SHARDS_COUNT)
|
||||
as i32;
|
||||
let mut max_count = vol_count + ec_equivalent;
|
||||
|
||||
@@ -370,11 +370,77 @@ func findWeedBinary() string {
|
||||
|
||||
// Helper functions for test assertions
|
||||
|
||||
// AssertFileExists checks if a file exists in the mount point
|
||||
// AssertFileExists checks if a file exists in the mount point. On failure,
|
||||
// it gathers diagnostic state (retry stat, parent listing, direct open) so
|
||||
// transient FUSE flakes leave enough information to identify the layer that
|
||||
// dropped the entry. The diagnostic block runs only on the failure path.
|
||||
func (f *FuseTestFramework) AssertFileExists(relativePath string) {
|
||||
fullPath := filepath.Join(f.mountPoint, relativePath)
|
||||
_, err := os.Stat(fullPath)
|
||||
require.NoError(f.t, err, "file should exist: %s", relativePath)
|
||||
if err == nil {
|
||||
return
|
||||
}
|
||||
f.dumpExistenceDiagnostics(relativePath, fullPath, err)
|
||||
require.NoError(f.t, err, "file should exist: %s (see diagnostic logs above)", relativePath)
|
||||
}
|
||||
|
||||
// dumpExistenceDiagnostics is invoked when AssertFileExists fails. It probes
|
||||
// whether the missing entry is transient (retries appear), missing from the
|
||||
// parent directory listing, or missing via a direct open syscall — three
|
||||
// signals that triangulate where the entry was lost (kernel dentry cache vs
|
||||
// mount lookup vs filer).
|
||||
func (f *FuseTestFramework) dumpExistenceDiagnostics(relativePath, fullPath string, initialErr error) {
|
||||
f.t.Logf("AssertFileExists diagnostic dump for %s", relativePath)
|
||||
f.t.Logf(" initial stat: err=%v isNotExist=%v", initialErr, os.IsNotExist(initialErr))
|
||||
|
||||
// Retry stat to detect transient invisibility — if it becomes visible
|
||||
// the issue is a short-lived dentry/cache window; if it stays missing
|
||||
// the entry is genuinely gone from the filer or the local cache.
|
||||
for attempt := 1; attempt <= 5; attempt++ {
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
_, err := os.Stat(fullPath)
|
||||
f.t.Logf(" retry #%d after %dms: err=%v", attempt, attempt*100, err)
|
||||
if err == nil {
|
||||
break
|
||||
}
|
||||
}
|
||||
|
||||
// List the parent directory: if the file appears here but stat fails,
|
||||
// the failure is in the kernel's per-name dentry cache; if not, the
|
||||
// mount-side LOOKUP itself is dropping the entry.
|
||||
parentDir := filepath.Dir(fullPath)
|
||||
target := filepath.Base(fullPath)
|
||||
if entries, listErr := os.ReadDir(parentDir); listErr != nil {
|
||||
f.t.Logf(" ReadDir(%s) failed: %v", parentDir, listErr)
|
||||
} else {
|
||||
found := false
|
||||
names := make([]string, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
names = append(names, e.Name())
|
||||
if e.Name() == target {
|
||||
found = true
|
||||
}
|
||||
}
|
||||
f.t.Logf(" ReadDir(%s): %d entries, target %q present=%v", parentDir, len(entries), target, found)
|
||||
if len(names) <= 32 {
|
||||
f.t.Logf(" ReadDir entries: %v", names)
|
||||
}
|
||||
}
|
||||
|
||||
// Direct O_RDONLY open — exercises the same FUSE Lookup+Open path
|
||||
// userspace would, but separately from stat, in case stat-only caching
|
||||
// is interfering.
|
||||
if fd, openErr := os.OpenFile(fullPath, os.O_RDONLY, 0); openErr != nil {
|
||||
f.t.Logf(" Open(%s, O_RDONLY): %v", fullPath, openErr)
|
||||
} else {
|
||||
st, statErr := fd.Stat()
|
||||
fd.Close()
|
||||
size := int64(-1)
|
||||
if statErr == nil && st != nil {
|
||||
size = st.Size()
|
||||
}
|
||||
f.t.Logf(" Open(%s, O_RDONLY): success size=%d statErr=%v", fullPath, size, statErr)
|
||||
}
|
||||
}
|
||||
|
||||
// AssertFileNotExists checks if a file does not exist in the mount point
|
||||
|
||||
@@ -9,7 +9,6 @@ import (
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"runtime"
|
||||
"strconv"
|
||||
"strings"
|
||||
"sync"
|
||||
@@ -82,9 +81,25 @@ func TestFcntlLockHelper(t *testing.T) {
|
||||
start, _ := strconv.ParseInt(os.Getenv("LOCK_START"), 10, 64)
|
||||
length, _ := strconv.ParseInt(os.Getenv("LOCK_LEN"), 10, 64)
|
||||
|
||||
f, err := os.OpenFile(filePath, os.O_RDWR, 0)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "open: %v\n", err)
|
||||
// The parent test process created the file on the FUSE mount just before
|
||||
// spawning this subprocess. A fresh lookup from a different process can
|
||||
// briefly return ENOENT while the mount's dentry state propagates, so
|
||||
// retry on ENOENT before giving up.
|
||||
var f *os.File
|
||||
var openErr error
|
||||
for attempt := 0; attempt < 40; attempt++ {
|
||||
f, openErr = os.OpenFile(filePath, os.O_RDWR, 0)
|
||||
if openErr == nil {
|
||||
break
|
||||
}
|
||||
if !errors.Is(openErr, os.ErrNotExist) && !errors.Is(openErr, syscall.ENOENT) {
|
||||
break
|
||||
}
|
||||
_, _ = os.ReadDir(filepath.Dir(filePath))
|
||||
time.Sleep(50 * time.Millisecond)
|
||||
}
|
||||
if openErr != nil {
|
||||
fmt.Fprintf(os.Stderr, "open: %v\n", openErr)
|
||||
os.Exit(1)
|
||||
}
|
||||
defer f.Close()
|
||||
@@ -617,9 +632,14 @@ func testFcntlReleaseOnClose(t *testing.T, fw *FuseTestFramework) {
|
||||
// reader goroutines (blocking FUSE SETLKW can starve unlock processing).
|
||||
func testConcurrentLockContention(t *testing.T, fw *FuseTestFramework) {
|
||||
path := filepath.Join(fw.GetMountPoint(), "lock_contention.txt")
|
||||
f, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
|
||||
// Hold a master fd open for the whole subtest. Workers take flock on their
|
||||
// own fds; master stays passive. Keeping this reference pinned avoids the
|
||||
// re-open-after-concurrent-close code path, which has shown an unresolved
|
||||
// mount/metaCache coherence bug where a freshly-opened fd sees ENOENT for
|
||||
// tens of seconds after a burst of concurrent Release calls.
|
||||
master, err := os.OpenFile(path, os.O_RDWR|os.O_CREATE|os.O_TRUNC, 0644)
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, f.Close())
|
||||
defer master.Close()
|
||||
|
||||
numWorkers := 8
|
||||
writesPerWorker := 5
|
||||
@@ -720,45 +740,57 @@ func testConcurrentLockContention(t *testing.T, fw *FuseTestFramework) {
|
||||
}
|
||||
|
||||
wg.Wait()
|
||||
if runtime.GOOS == "darwin" {
|
||||
for _, err := range errs {
|
||||
if err != nil && strings.Contains(err.Error(), "no such file or directory") {
|
||||
t.Skip("lock contention file disappeared on darwin FUSE; skipping flaky check")
|
||||
}
|
||||
}
|
||||
}
|
||||
require.Empty(t, errs, "concurrent lock contention errors: %v", errs)
|
||||
|
||||
flush := func() {
|
||||
verify, err := openWithRetry(os.O_RDWR)
|
||||
if err != nil && runtime.GOOS == "darwin" && strings.Contains(err.Error(), "no such file or directory") {
|
||||
t.Skip("lock contention file disappeared on darwin FUSE; skipping flaky check")
|
||||
}
|
||||
require.NoError(t, err)
|
||||
defer verify.Close()
|
||||
require.NoError(t, verify.Sync())
|
||||
}
|
||||
flush()
|
||||
// Flush via the master fd. fsync on any fd to the file forces the
|
||||
// kernel to send FUSE_FSYNC, which drains workers' writes to the filer.
|
||||
require.NoError(t, master.Sync())
|
||||
|
||||
expectedLines := numWorkers * writesPerWorker
|
||||
expectedBytes := expectedLines * recordSize
|
||||
var data []byte
|
||||
require.Eventually(t, func() bool {
|
||||
verify, err := openWithRetry(os.O_RDONLY)
|
||||
if err != nil {
|
||||
if runtime.GOOS == "darwin" && strings.Contains(err.Error(), "no such file or directory") {
|
||||
t.Skip("lock contention file disappeared on darwin FUSE; skipping flaky check")
|
||||
}
|
||||
var lastReadErr error
|
||||
ok := assert.Eventually(t, func() bool {
|
||||
if _, err := master.Seek(0, io.SeekStart); err != nil {
|
||||
lastReadErr = fmt.Errorf("seek: %w", err)
|
||||
return false
|
||||
}
|
||||
defer verify.Close()
|
||||
|
||||
data, err = io.ReadAll(verify)
|
||||
d, err := io.ReadAll(master)
|
||||
if err != nil {
|
||||
lastReadErr = fmt.Errorf("read: %w", err)
|
||||
return false
|
||||
}
|
||||
data = d
|
||||
lastReadErr = nil
|
||||
return len(data) == expectedBytes
|
||||
}, 15*time.Second, 100*time.Millisecond, "file should eventually contain exactly %d records from all workers", expectedLines)
|
||||
if !ok {
|
||||
// Diagnostics: dump what the mount currently shows for the parent dir
|
||||
// and the target path, so post-mortem analysis has something to go on.
|
||||
parent := filepath.Dir(path)
|
||||
if entries, readErr := os.ReadDir(parent); readErr != nil {
|
||||
t.Logf("diag: ReadDir(%q) failed: %v", parent, readErr)
|
||||
} else {
|
||||
names := make([]string, 0, len(entries))
|
||||
for _, e := range entries {
|
||||
names = append(names, e.Name())
|
||||
}
|
||||
t.Logf("diag: ReadDir(%q) returned %d entries: %v", parent, len(names), names)
|
||||
}
|
||||
if fi, statErr := os.Stat(path); statErr != nil {
|
||||
t.Logf("diag: Stat(%q) failed: %v", path, statErr)
|
||||
} else {
|
||||
t.Logf("diag: Stat(%q) ok: size=%d mode=%s", path, fi.Size(), fi.Mode())
|
||||
}
|
||||
if freshFd, openErr := os.OpenFile(path, os.O_RDONLY, 0); openErr != nil {
|
||||
t.Logf("diag: fresh open(%q, O_RDONLY) failed: %v", path, openErr)
|
||||
} else {
|
||||
fresh, readErr := io.ReadAll(freshFd)
|
||||
freshFd.Close()
|
||||
t.Logf("diag: fresh open(%q) read %d bytes (err=%v)", path, len(fresh), readErr)
|
||||
}
|
||||
t.Fatalf("read back incomplete: got %d bytes, want %d (lastReadErr=%v)", len(data), expectedBytes, lastReadErr)
|
||||
}
|
||||
actualLines := bytes.Count(data, []byte("\n"))
|
||||
assert.Equal(t, expectedLines, actualLines,
|
||||
"file should contain exactly %d lines from all workers", expectedLines)
|
||||
|
||||
@@ -208,8 +208,6 @@ func (c *p2pTestCluster) startFiler(configDir string) error {
|
||||
"-port.grpc="+strconv.Itoa(c.filerGrpcPort),
|
||||
"-master="+c.masterAddress(),
|
||||
"-defaultStoreDir="+filerDir,
|
||||
// default is -mount.p2p=true; be explicit so the intent is grep-able.
|
||||
"-mount.p2p=true",
|
||||
)
|
||||
return c.startCmd(c.filerCmd, "filer")
|
||||
}
|
||||
|
||||
@@ -39,7 +39,7 @@ func TestOffsetManagement(t *testing.T) {
|
||||
})
|
||||
|
||||
t.Run("ConsumerGroupResumption", func(t *testing.T) {
|
||||
testConsumerGroupResumption(t, addr, topic2, groupID+"2")
|
||||
testConsumerGroupResumption(t, gateway, addr, topic2, groupID+"2")
|
||||
})
|
||||
}
|
||||
|
||||
@@ -78,7 +78,7 @@ func testBasicOffsetCommitFetch(t *testing.T, addr, topic, groupID string) {
|
||||
t.Logf("SUCCESS: Offset management test completed - consumed %d + %d messages", len(consumed1), len(consumed2))
|
||||
}
|
||||
|
||||
func testConsumerGroupResumption(t *testing.T, addr, topic, groupID string) {
|
||||
func testConsumerGroupResumption(t *testing.T, gateway *testutil.GatewayTestServer, addr, topic, groupID string) {
|
||||
client := testutil.NewKafkaGoClient(t, addr)
|
||||
msgGen := testutil.NewMessageGenerator()
|
||||
|
||||
@@ -97,10 +97,18 @@ func testConsumerGroupResumption(t *testing.T, addr, topic, groupID string) {
|
||||
for i, msg := range consumed1 {
|
||||
t.Logf(" Message %d: offset=%d, partition=%d, value=%s", i, msg.Offset, msg.Partition, string(msg.Value))
|
||||
}
|
||||
gateway.LogConsumerGroupSnapshot(groupID)
|
||||
|
||||
// Simulate consumer restart by consuming remaining messages with same group ID
|
||||
t.Logf("=== Phase 3: Second consumer (simulated restart) - consuming remaining messages with same group %s ===", groupID)
|
||||
consumed2, err := client.ConsumeWithGroup(topic, groupID, 2)
|
||||
consumed2, err := client.ConsumeWithGroupDebug(topic, groupID, 2, func(info testutil.ConsumeGroupRetryDebug) {
|
||||
t.Logf("Consumer restart attempt %d/%d for group %s failed before receiving any messages: %v",
|
||||
info.Attempt, info.MaxAttempts, info.GroupID, info.Err)
|
||||
gateway.LogConsumerGroupSnapshot(groupID)
|
||||
})
|
||||
if err != nil {
|
||||
gateway.LogConsumerGroupSnapshot(groupID)
|
||||
}
|
||||
testutil.AssertNoError(t, err, "Failed to consume after restart")
|
||||
t.Logf("Second consumer consumed %d messages:", len(consumed2))
|
||||
for i, msg := range consumed2 {
|
||||
|
||||
+8
-8
@@ -22,9 +22,9 @@ require (
|
||||
github.com/Azure/azure-sdk-for-go/sdk/internal v1.11.2 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4 // indirect
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.5.3 // indirect
|
||||
github.com/Azure/go-ntlmssp v0.1.0 // indirect
|
||||
github.com/Azure/go-ntlmssp v0.1.1 // indirect
|
||||
github.com/AzureAD/microsoft-authentication-library-for-go v1.6.0 // indirect
|
||||
github.com/FilenCloudDienste/filen-sdk-go v0.0.37 // indirect
|
||||
github.com/FilenCloudDienste/filen-sdk-go v0.0.38 // indirect
|
||||
github.com/Files-com/files-sdk-go/v3 v3.2.264 // indirect
|
||||
github.com/IBM/go-sdk-core/v5 v5.21.0 // indirect
|
||||
github.com/Max-Sum/base32768 v0.0.0-20230304063302-18e6ce5945fd // indirect
|
||||
@@ -43,12 +43,12 @@ require (
|
||||
github.com/andybalholm/cascadia v1.3.3 // indirect
|
||||
github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc // indirect
|
||||
github.com/aws/aws-sdk-go v1.55.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.5 // indirect
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.6 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.14 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.14 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.21 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.20.12 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.1 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/internal/ini v1.8.6 // indirect
|
||||
@@ -62,7 +62,7 @@ require (
|
||||
github.com/aws/aws-sdk-go-v2/service/sso v1.30.15 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.19 // indirect
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.41.10 // indirect
|
||||
github.com/aws/smithy-go v1.24.2 // indirect
|
||||
github.com/aws/smithy-go v1.25.0 // indirect
|
||||
github.com/bahlo/generic-list-go v0.2.0 // indirect
|
||||
github.com/beorn7/perks v1.0.1 // indirect
|
||||
github.com/boombuler/barcode v1.1.0 // indirect
|
||||
@@ -104,7 +104,7 @@ require (
|
||||
github.com/geoffgarside/ber v1.2.0 // indirect
|
||||
github.com/go-chi/chi/v5 v5.2.5 // indirect
|
||||
github.com/go-darwin/apfs v0.0.0-20211011131704-f84b94dbf348 // indirect
|
||||
github.com/go-git/go-billy/v5 v5.6.2 // indirect
|
||||
github.com/go-git/go-billy/v5 v5.8.0 // indirect
|
||||
github.com/go-jose/go-jose/v4 v4.1.4 // indirect
|
||||
github.com/go-logr/logr v1.4.3 // indirect
|
||||
github.com/go-logr/stdr v1.2.2 // indirect
|
||||
@@ -134,7 +134,7 @@ require (
|
||||
github.com/hashicorp/go-multierror v1.1.1 // indirect
|
||||
github.com/hashicorp/go-retryablehttp v0.7.8 // indirect
|
||||
github.com/hashicorp/go-uuid v1.0.3 // indirect
|
||||
github.com/internxt/rclone-adapter v0.0.0-20260213125353-6f59c89fcb7c // indirect
|
||||
github.com/internxt/rclone-adapter v0.0.0-20260220172730-613f4cc8b8fd // indirect
|
||||
github.com/jcmturner/aescts/v2 v2.0.0 // indirect
|
||||
github.com/jcmturner/dnsutils/v2 v2.0.0 // indirect
|
||||
github.com/jcmturner/gofork v1.7.6 // indirect
|
||||
@@ -194,7 +194,7 @@ require (
|
||||
github.com/quic-go/qpack v0.6.0 // indirect
|
||||
github.com/rclone/Proton-API-Bridge v1.0.1-0.20260127174007-77f974840d11 // indirect
|
||||
github.com/rclone/go-proton-api v1.0.1-0.20260127173028-eb465cac3b18 // indirect
|
||||
github.com/rclone/rclone v1.73.1 // indirect
|
||||
github.com/rclone/rclone v1.73.5 // indirect
|
||||
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 // indirect
|
||||
github.com/rdleal/intervalst v1.5.0 // indirect
|
||||
github.com/relvacode/iso8601 v1.7.0 // indirect
|
||||
|
||||
+16
-16
@@ -51,8 +51,8 @@ github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4 h1:jWQK1GI+LeGGUKBAD
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azblob v1.6.4/go.mod h1:8mwH4klAm9DUgR2EEHyEEAQlRDvLPyg5fQry3y+cDew=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.5.3 h1:sxgSqOB9CDToiaVFpxuvb5wGgGqWa3lCShcm5o0n3bE=
|
||||
github.com/Azure/azure-sdk-for-go/sdk/storage/azfile v1.5.3/go.mod h1:XdED8i399lEVblYHTZM8eXaP07gv4Z58IL6ueMlVlrg=
|
||||
github.com/Azure/go-ntlmssp v0.1.0 h1:DjFo6YtWzNqNvQdrwEyr/e4nhU3vRiwenz5QX7sFz+A=
|
||||
github.com/Azure/go-ntlmssp v0.1.0/go.mod h1:NYqdhxd/8aAct/s4qSYZEerdPuH1liG2/X9DiVTbhpk=
|
||||
github.com/Azure/go-ntlmssp v0.1.1 h1:l+FM/EEMb0U9QZE7mKNEDw5Mu3mFiaa2GKOoTSsNDPw=
|
||||
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.6.0 h1:XRzhVemXdgvJqCH0sFfrBUTnUJSBrBf7++ypk+twtRs=
|
||||
@@ -61,8 +61,8 @@ github.com/BurntSushi/toml v0.3.1/go.mod h1:xHWCNGjB5oqiDr8zfno3MHue2Ht5sIBksp03
|
||||
github.com/BurntSushi/xgb v0.0.0-20160522181843-27f122750802/go.mod h1:IVnqGOEym/WlBOVXweHU+Q+/VP0lqqI8lqeDx9IjBqo=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2 h1:OcvFkGmslmlZibjAjaHm3L//6LiuBgolP7OputlJIzU=
|
||||
github.com/DATA-DOG/go-sqlmock v1.5.2/go.mod h1:88MAG/4G7SMwSE3CeA0ZKzrT5CiOU3OJ+JlNzwDqpNU=
|
||||
github.com/FilenCloudDienste/filen-sdk-go v0.0.37 h1:W8S9TrAyZ4//3PXsU6+Bi+fe/6uIL986GyS7PVzIDL4=
|
||||
github.com/FilenCloudDienste/filen-sdk-go v0.0.37/go.mod h1:0cBhKXQg49XbKZZfk5TCDa3sVLP+xMxZTWL+7KY0XR0=
|
||||
github.com/FilenCloudDienste/filen-sdk-go v0.0.38 h1:YCyHs3wUXEe2BEWn40vcoyaQ2ruHNmNwkasfo3Th16A=
|
||||
github.com/FilenCloudDienste/filen-sdk-go v0.0.38/go.mod h1:0cBhKXQg49XbKZZfk5TCDa3sVLP+xMxZTWL+7KY0XR0=
|
||||
github.com/Files-com/files-sdk-go/v3 v3.2.264 h1:lMHTplAYI9FtmCo/QOcpRxmPA5REVAct1r2riQmDQKw=
|
||||
github.com/Files-com/files-sdk-go/v3 v3.2.264/go.mod h1:wGqkOzRu/ClJibvDgcfuJNAqI2nLhe8g91tPlDKRCdE=
|
||||
github.com/IBM/go-sdk-core/v5 v5.21.0 h1:DUnYhvC4SoC8T84rx5omnhY3+xcQg/Whyoa3mDPIMkk=
|
||||
@@ -112,8 +112,8 @@ github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc h1:LoL75er
|
||||
github.com/appscode/go-querystring v0.0.0-20170504095604-0126cfb3f1dc/go.mod h1:w648aMHEgFYS6xb0KVMMtZ2uMeemhiKCuD2vj6gY52A=
|
||||
github.com/aws/aws-sdk-go v1.55.8 h1:JRmEUbU52aJQZ2AjX4q4Wu7t4uZjOu71uyNmaWlUkJQ=
|
||||
github.com/aws/aws-sdk-go v1.55.8/go.mod h1:ZkViS9AqA6otK+JBBNH2++sx1sgxrPKcSzPPvQkUtXk=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.5 h1:dj5kopbwUsVUVFgO4Fi5BIT3t4WyqIDjGKCangnV/yY=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.5/go.mod h1:mwsPRE8ceUUpiTgF7QmQIJ7lgsKUPQOUl3o72QBrE1o=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.6 h1:1AX0AthnBQzMx1vbmir3Y4WsnJgiydmnJjiLu+LvXOg=
|
||||
github.com/aws/aws-sdk-go-v2 v1.41.6/go.mod h1:dy0UzBIfwSeot4grGvY1AqFWN5zgziMmWGzysDnHFcQ=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8 h1:eBMB84YGghSocM7PsjmmPffTa+1FBUeNvGvFou6V/4o=
|
||||
github.com/aws/aws-sdk-go-v2/aws/protocol/eventstream v1.7.8/go.mod h1:lyw7GFp3qENLh7kwzf7iMzAxDn+NzjXEAGjKS2UOKqI=
|
||||
github.com/aws/aws-sdk-go-v2/config v1.32.14 h1:opVIRo/ZbbI8OIqSOKmpFaY7IwfFUOCCXBsUpJOwDdI=
|
||||
@@ -122,8 +122,8 @@ github.com/aws/aws-sdk-go-v2/credentials v1.19.14 h1:n+UcGWAIZHkXzYt87uMFBv/l8TH
|
||||
github.com/aws/aws-sdk-go-v2/credentials v1.19.14/go.mod h1:cJKuyWB59Mqi0jM3nFYQRmnHVQIcgoxjEMAbLkpr62w=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.21 h1:NUS3K4BTDArQqNu2ih7yeDLaS3bmHD0YndtA6UP884g=
|
||||
github.com/aws/aws-sdk-go-v2/feature/ec2/imds v1.18.21/go.mod h1:YWNWJQNjKigKY1RHVJCuupeWDrrHjRqHm0N9rdrWzYI=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.20.12 h1:Zy6Tme1AA13kX8x3CnkHx5cqdGWGaj/anwOiWGnA0Xo=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.20.12/go.mod h1:ql4uXYKoTM9WUAUSmthY4AtPVrlTBZOvnBJTiCUdPxI=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.1 h1:IbWiN670htmBioc+Zj32vSpJgQ2+OYSlvTvfQ1nCORQ=
|
||||
github.com/aws/aws-sdk-go-v2/feature/s3/manager v1.22.1/go.mod h1:tw/B596EUhBWDFGdDGuLC21fVU4A3s4/5Efy8S39W18=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21 h1:Rgg6wvjjtX8bNHcvi9OnXWwcE0a2vGpbwmtICOsvcf4=
|
||||
github.com/aws/aws-sdk-go-v2/internal/configsources v1.4.21/go.mod h1:A/kJFst/nm//cyqonihbdpQZwiUhhzpqTsdbhDdRF9c=
|
||||
github.com/aws/aws-sdk-go-v2/internal/endpoints/v2 v2.7.21 h1:PEgGVtPoB6NTpPrBgqSE5hE/o47Ij9qk/SEZFbUOe9A=
|
||||
@@ -150,8 +150,8 @@ github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.19 h1:dzztQ1YmfPrxdrOiuZRMF6f
|
||||
github.com/aws/aws-sdk-go-v2/service/ssooidc v1.35.19/go.mod h1:YO8TrYtFdl5w/4vmjL8zaBSsiNp3w0L1FfKVKenZT7w=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.41.10 h1:p8ogvvLugcR/zLBXTXrTkj0RYBUdErbMnAFFp12Lm/U=
|
||||
github.com/aws/aws-sdk-go-v2/service/sts v1.41.10/go.mod h1:60dv0eZJfeVXfbT1tFJinbHrDfSJ2GZl4Q//OSSNAVw=
|
||||
github.com/aws/smithy-go v1.24.2 h1:FzA3bu/nt/vDvmnkg+R8Xl46gmzEDam6mZ1hzmwXFng=
|
||||
github.com/aws/smithy-go v1.24.2/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/aws/smithy-go v1.25.0 h1:Sz/XJ64rwuiKtB6j98nDIPyYrV1nVNJ4YU74gttcl5U=
|
||||
github.com/aws/smithy-go v1.25.0/go.mod h1:YE2RhdIuDbA5E5bTdciG9KrW3+TiEONeUWCqxX9i1Fc=
|
||||
github.com/bahlo/generic-list-go v0.2.0 h1:5sz/EEAK+ls5wF+NeqDpk5+iNdMDXrh3z3nPnH1Wvgk=
|
||||
github.com/bahlo/generic-list-go v0.2.0/go.mod h1:2KvAjgMlE5NNynlg/5iLrrCCZ2+5xWbdbCW3pNTGyYg=
|
||||
github.com/beorn7/perks v1.0.1 h1:VlbKKnNfV8bJzeqoa4cOKqO6bYr3WgKZxO8Z16+hsOM=
|
||||
@@ -281,8 +281,8 @@ github.com/go-darwin/apfs v0.0.0-20211011131704-f84b94dbf348 h1:JnrjqG5iR07/8k7N
|
||||
github.com/go-darwin/apfs v0.0.0-20211011131704-f84b94dbf348/go.mod h1:Czxo/d1g948LtrALAZdL04TL/HnkopquAjxYUuI02bo=
|
||||
github.com/go-errors/errors v1.5.1 h1:ZwEMSLRCapFLflTpT7NKaAc7ukJ8ZPEjzlxt8rPN8bk=
|
||||
github.com/go-errors/errors v1.5.1/go.mod h1:sIVyrIiJhuEF+Pj9Ebtd6P/rEYROXFi3BopGUQ5a5Og=
|
||||
github.com/go-git/go-billy/v5 v5.6.2 h1:6Q86EsPXMa7c3YZ3aLAQsMA0VlWmy43r6FHqa/UNbRM=
|
||||
github.com/go-git/go-billy/v5 v5.6.2/go.mod h1:rcFC2rAsp/erv7CMz9GczHcuD0D32fWzH+MJAU+jaUU=
|
||||
github.com/go-git/go-billy/v5 v5.8.0 h1:I8hjc3LbBlXTtVuFNJuwYuMiHvQJDq1AT6u4DwDzZG0=
|
||||
github.com/go-git/go-billy/v5 v5.8.0/go.mod h1:RpvI/rw4Vr5QA+Z60c6d6LXH0rYJo0uD5SqfmrrheCY=
|
||||
github.com/go-gl/glfw v0.0.0-20190409004039-e6da0acd62b1/go.mod h1:vR7hzQXu2zJy9AVAgeJqvqgH9Q5CA+iKCZ2gyEVpxRU=
|
||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20191125211704-12ad95a8df72/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
||||
github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2UAYgL5IevRw8kRxooKSPJfGvJ9fJQFa0TUsXzTg8=
|
||||
@@ -427,8 +427,8 @@ github.com/hpcloud/tail v1.0.0/go.mod h1:ab1qPbhIpdTxEkNHXyeSf5vhxWSCs/tWer42PpO
|
||||
github.com/ianlancetaylor/demangle v0.0.0-20181102032728-5e5cf60278f6/go.mod h1:aSSvb/t6k1mPoxDqO4vJh6VOCGPwU4O0C2/Eqndh1Sc=
|
||||
github.com/inconshreveable/mousetrap v1.1.0 h1:wN+x4NVGpMsO7ErUn/mUI3vEoE6Jt13X2s0bqwp9tc8=
|
||||
github.com/inconshreveable/mousetrap v1.1.0/go.mod h1:vpF70FUmC8bwa3OWnCshd2FqLfsEA9PFc4w1p2J65bw=
|
||||
github.com/internxt/rclone-adapter v0.0.0-20260213125353-6f59c89fcb7c h1:r+KtxPyrhsYeNbsfeqTfEM8xRdwgV6LuNhLZxpXecb4=
|
||||
github.com/internxt/rclone-adapter v0.0.0-20260213125353-6f59c89fcb7c/go.mod h1:vdPya4AIcDjvng4ViaAzqjegJf0VHYpYHQguFx5xBp0=
|
||||
github.com/internxt/rclone-adapter v0.0.0-20260220172730-613f4cc8b8fd h1:dSIuz2mpJAPQfhHYtG57D0qwSkgC/vQ69gHfeyQ4kxA=
|
||||
github.com/internxt/rclone-adapter v0.0.0-20260220172730-613f4cc8b8fd/go.mod h1:vdPya4AIcDjvng4ViaAzqjegJf0VHYpYHQguFx5xBp0=
|
||||
github.com/jcmturner/aescts/v2 v2.0.0 h1:9YKLH6ey7H4eDBXW8khjYslgyqG2xZikXP0EQFKrle8=
|
||||
github.com/jcmturner/aescts/v2 v2.0.0/go.mod h1:AiaICIRyfYg35RUkr8yESTqvSy7csK90qZ5xfvvsoNs=
|
||||
github.com/jcmturner/dnsutils/v2 v2.0.0 h1:lltnkeZGL0wILNvrNiVCR6Ro5PGU/SeBvVO/8c/iPbo=
|
||||
@@ -594,8 +594,8 @@ github.com/rclone/Proton-API-Bridge v1.0.1-0.20260127174007-77f974840d11 h1:4MI2
|
||||
github.com/rclone/Proton-API-Bridge v1.0.1-0.20260127174007-77f974840d11/go.mod h1:3HLX7dwZgvB7nt+Yl/xdzVPcargQ1yBmJEUg3n+jMKM=
|
||||
github.com/rclone/go-proton-api v1.0.1-0.20260127173028-eb465cac3b18 h1:Lc+d3ISfQaMJKWZOE7z4ZSY4RVmdzbn1B0IM8xN18qM=
|
||||
github.com/rclone/go-proton-api v1.0.1-0.20260127173028-eb465cac3b18/go.mod h1:LB2kCEaZMzNn3ocdz+qYfxXmuLxxN0ka62KJd2x53Bc=
|
||||
github.com/rclone/rclone v1.73.1 h1:FCGZUd7sXO8+nIpbuXGPkd+f23o/ZACefrHtRGDAiDM=
|
||||
github.com/rclone/rclone v1.73.1/go.mod h1:T9HeSXv/SI9qJFkYLqsjY/5ljIFWJTVmTrG7H/4JrPY=
|
||||
github.com/rclone/rclone v1.73.5 h1:r8a9JHYIWUqk7hNRJuMJ3cROkKfB2zmfkADg8ZLYh6I=
|
||||
github.com/rclone/rclone v1.73.5/go.mod h1:WVv8gvA/lEl/Y37e8I8yosm7ZY+Szq7ujXbJS8Ol63o=
|
||||
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 h1:bsUq1dX0N8AOIL7EB/X911+m4EHsnWEHeJ0c+3TTBrg=
|
||||
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
|
||||
github.com/rdleal/intervalst v1.5.0 h1:SEB9bCFz5IqD1yhfH1Wv8IBnY/JQxDplwkxHjT6hamU=
|
||||
|
||||
@@ -31,6 +31,15 @@ type SaramaClient struct {
|
||||
t *testing.T
|
||||
}
|
||||
|
||||
type ConsumeGroupRetryDebug struct {
|
||||
Attempt int
|
||||
MaxAttempts int
|
||||
Topic string
|
||||
GroupID string
|
||||
ExpectedCount int
|
||||
Err error
|
||||
}
|
||||
|
||||
// NewKafkaGoClient creates a new kafka-go test client
|
||||
func NewKafkaGoClient(t *testing.T, brokerAddr string) *KafkaGoClient {
|
||||
return &KafkaGoClient{
|
||||
@@ -142,6 +151,14 @@ func (k *KafkaGoClient) ConsumeMessages(topicName string, expectedCount int) ([]
|
||||
// member's LeaveGroup / session cleanup and can surface as an i/o timeout on
|
||||
// the first FetchMessage.
|
||||
func (k *KafkaGoClient) ConsumeWithGroup(topicName, groupID string, expectedCount int) ([]kafka.Message, error) {
|
||||
return k.consumeWithGroup(topicName, groupID, expectedCount, nil)
|
||||
}
|
||||
|
||||
func (k *KafkaGoClient) ConsumeWithGroupDebug(topicName, groupID string, expectedCount int, onRetry func(ConsumeGroupRetryDebug)) ([]kafka.Message, error) {
|
||||
return k.consumeWithGroup(topicName, groupID, expectedCount, onRetry)
|
||||
}
|
||||
|
||||
func (k *KafkaGoClient) consumeWithGroup(topicName, groupID string, expectedCount int, onRetry func(ConsumeGroupRetryDebug)) ([]kafka.Message, error) {
|
||||
k.t.Helper()
|
||||
|
||||
const maxJoinAttempts = 5
|
||||
@@ -158,6 +175,16 @@ func (k *KafkaGoClient) ConsumeWithGroup(topicName, groupID string, expectedCoun
|
||||
if progressed {
|
||||
return messages, err
|
||||
}
|
||||
if onRetry != nil {
|
||||
onRetry(ConsumeGroupRetryDebug{
|
||||
Attempt: attempt,
|
||||
MaxAttempts: maxJoinAttempts,
|
||||
Topic: topicName,
|
||||
GroupID: groupID,
|
||||
ExpectedCount: expectedCount,
|
||||
Err: err,
|
||||
})
|
||||
}
|
||||
if attempt == maxJoinAttempts {
|
||||
break
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ package testutil
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
@@ -111,6 +112,31 @@ func (g *GatewayTestServer) CleanupAndClose() {
|
||||
}
|
||||
}
|
||||
|
||||
// LogConsumerGroupSnapshot dumps the gateway's current view of a consumer group.
|
||||
func (g *GatewayTestServer) LogConsumerGroupSnapshot(groupID string) {
|
||||
g.t.Helper()
|
||||
|
||||
handler := g.GetHandler()
|
||||
if handler == nil {
|
||||
g.t.Logf("Consumer group snapshot for %s unavailable: handler is nil", groupID)
|
||||
return
|
||||
}
|
||||
|
||||
snapshot := handler.DebugGroupSnapshot(groupID)
|
||||
if snapshot == nil {
|
||||
g.t.Logf("Consumer group snapshot for %s unavailable", groupID)
|
||||
return
|
||||
}
|
||||
|
||||
payload, err := json.MarshalIndent(snapshot, "", " ")
|
||||
if err != nil {
|
||||
g.t.Logf("Consumer group snapshot for %s could not be marshaled: %v", groupID, err)
|
||||
return
|
||||
}
|
||||
|
||||
g.t.Logf("Consumer group snapshot for %s:\n%s", groupID, string(payload))
|
||||
}
|
||||
|
||||
// SMQAvailabilityMode indicates whether SeaweedMQ is available for testing
|
||||
type SMQAvailabilityMode int
|
||||
|
||||
|
||||
@@ -6,6 +6,7 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
@@ -14,6 +15,7 @@ import (
|
||||
"github.com/aws/aws-sdk-go/aws/awserr"
|
||||
"github.com/aws/aws-sdk-go/aws/credentials"
|
||||
"github.com/aws/aws-sdk-go/aws/session"
|
||||
v4 "github.com/aws/aws-sdk-go/aws/signer/v4"
|
||||
"github.com/aws/aws-sdk-go/service/s3"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
@@ -338,15 +340,29 @@ func TestServiceAccountValidation(t *testing.T) {
|
||||
// callIAMAPI is a helper to make IAM API calls
|
||||
func callIAMAPI(t *testing.T, action string, params url.Values) (*http.Response, error) {
|
||||
params.Set("Action", action)
|
||||
body := params.Encode()
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, TestIAMEndpoint+"/",
|
||||
strings.NewReader(params.Encode()))
|
||||
strings.NewReader(body))
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
|
||||
// Sign with SigV4 when admin credentials are provided via env vars.
|
||||
// IAM write APIs (CreateUser, CreateServiceAccount, etc.) require an
|
||||
// authenticated admin caller; unsigned requests get routed to the STS
|
||||
// fallback and rejected as an unknown action.
|
||||
if accessKey := os.Getenv("STS_TEST_ACCESS_KEY"); accessKey != "" {
|
||||
secretKey := os.Getenv("STS_TEST_SECRET_KEY")
|
||||
creds := credentials.NewStaticCredentials(accessKey, secretKey, "")
|
||||
signer := v4.NewSigner(creds)
|
||||
if _, err := signer.Sign(req, strings.NewReader(body), "iam", "us-east-1", time.Now()); err != nil {
|
||||
return nil, fmt.Errorf("failed to sign IAM request: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
client := &http.Client{Timeout: 30 * time.Second}
|
||||
return client.Do(req)
|
||||
}
|
||||
|
||||
@@ -49,25 +49,30 @@ func TestSTSAssumeRoleValidation(t *testing.T) {
|
||||
t.Fatal("AssumeRole action is not implemented in the running server - please rebuild weed binary with new code and restart the server")
|
||||
}
|
||||
|
||||
t.Run("missing_role_arn", func(t *testing.T) {
|
||||
t.Run("missing_role_arn_defaults_to_caller_identity", func(t *testing.T) {
|
||||
// SeaweedFS intentionally allows AssumeRole without RoleArn to support
|
||||
// S3-compatible clients that omit it. In that case the session is tied
|
||||
// to the caller's own identity (User Context assumption). See
|
||||
// handleAssumeRole in weed/s3api/s3api_sts.go.
|
||||
resp, err := callSTSAPIWithSigV4(t, url.Values{
|
||||
"Action": {"AssumeRole"},
|
||||
"Version": {"2011-06-15"},
|
||||
"RoleSessionName": {"test-session"},
|
||||
// RoleArn is missing
|
||||
// RoleArn is missing on purpose
|
||||
}, "test-access-key", "test-secret-key")
|
||||
require.NoError(t, err)
|
||||
defer resp.Body.Close()
|
||||
|
||||
assert.NotEqual(t, http.StatusOK, resp.StatusCode,
|
||||
"Should fail without RoleArn")
|
||||
|
||||
body, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err)
|
||||
var errResp STSErrorTestResponse
|
||||
err = xml.Unmarshal(body, &errResp)
|
||||
require.NoError(t, err, "Failed to parse error response: %s", string(body))
|
||||
assert.Equal(t, "MissingParameter", errResp.Error.Code)
|
||||
assert.Equal(t, http.StatusOK, resp.StatusCode,
|
||||
"Should succeed without RoleArn (user-context assumption): %s", string(body))
|
||||
|
||||
var assumeResp AssumeRoleTestResponse
|
||||
require.NoError(t, xml.Unmarshal(body, &assumeResp),
|
||||
"Failed to parse response: %s", string(body))
|
||||
assert.NotEmpty(t, assumeResp.Result.Credentials.AccessKeyId,
|
||||
"AccessKeyId should be issued for user-context assumption")
|
||||
})
|
||||
|
||||
t.Run("missing_role_session_name", func(t *testing.T) {
|
||||
@@ -337,7 +342,10 @@ func callSTSAPIWithSigV4(t *testing.T, params url.Values, accessKey, secretKey s
|
||||
}
|
||||
|
||||
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
|
||||
req.Header.Set("Host", req.URL.Host)
|
||||
// Do NOT set req.Header["Host"] — aws-sdk-go v1 v4.Signer reads the host
|
||||
// from req.URL.Host/req.Host, and a manual Host header makes the signer
|
||||
// emit `host;host` in SignedHeaders, producing a different signature than
|
||||
// the server calculates from canonical headers.
|
||||
|
||||
// Sign request with AWS Signature V4 using official SDK
|
||||
creds := credentials.NewStaticCredentials(accessKey, secretKey, "")
|
||||
|
||||
@@ -5,6 +5,7 @@ import (
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"fmt"
|
||||
"io"
|
||||
@@ -773,6 +774,281 @@ func TestSSEMultipartUploadIntegration(t *testing.T) {
|
||||
assert.Equal(t, types.ServerSideEncryptionAwsKms, resp.ServerSideEncryption)
|
||||
assert.Equal(t, kmsKeyID, aws.ToString(resp.SSEKMSKeyId))
|
||||
})
|
||||
|
||||
t.Run("Multipart Parts Larger Than Internal Chunks Across SSE Types", func(t *testing.T) {
|
||||
largeParts := [][]byte{
|
||||
generateTestData(9*1024*1024 + 123), // crosses SeaweedFS 8MB internal chunk boundary
|
||||
generateTestData(5*1024*1024 + 321),
|
||||
}
|
||||
|
||||
t.Run("SSE-C", func(t *testing.T) {
|
||||
sseKey := generateSSECKey()
|
||||
uploadAndVerifyMultipartSSEObject(t, ctx, client, bucketName, "large-internal-chunks-ssec", largeParts, multipartSSEOptions{
|
||||
configureCreate: func(input *s3.CreateMultipartUploadInput) {
|
||||
input.SSECustomerAlgorithm = aws.String("AES256")
|
||||
input.SSECustomerKey = aws.String(sseKey.KeyB64)
|
||||
input.SSECustomerKeyMD5 = aws.String(sseKey.KeyMD5)
|
||||
},
|
||||
configureUploadPart: func(input *s3.UploadPartInput) {
|
||||
input.SSECustomerAlgorithm = aws.String("AES256")
|
||||
input.SSECustomerKey = aws.String(sseKey.KeyB64)
|
||||
input.SSECustomerKeyMD5 = aws.String(sseKey.KeyMD5)
|
||||
},
|
||||
configureGet: func(input *s3.GetObjectInput) {
|
||||
input.SSECustomerAlgorithm = aws.String("AES256")
|
||||
input.SSECustomerKey = aws.String(sseKey.KeyB64)
|
||||
input.SSECustomerKeyMD5 = aws.String(sseKey.KeyMD5)
|
||||
},
|
||||
verifyGet: func(resp *s3.GetObjectOutput) {
|
||||
assert.Equal(t, "AES256", aws.ToString(resp.SSECustomerAlgorithm))
|
||||
assert.Equal(t, sseKey.KeyMD5, aws.ToString(resp.SSECustomerKeyMD5))
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("SSE-KMS", func(t *testing.T) {
|
||||
kmsKeyID := "test-large-internal-chunks-key"
|
||||
uploadAndVerifyMultipartSSEObject(t, ctx, client, bucketName, "large-internal-chunks-ssekms", largeParts, multipartSSEOptions{
|
||||
configureCreate: func(input *s3.CreateMultipartUploadInput) {
|
||||
input.ServerSideEncryption = types.ServerSideEncryptionAwsKms
|
||||
input.SSEKMSKeyId = aws.String(kmsKeyID)
|
||||
},
|
||||
verifyGet: func(resp *s3.GetObjectOutput) {
|
||||
assert.Equal(t, types.ServerSideEncryptionAwsKms, resp.ServerSideEncryption)
|
||||
assert.Equal(t, kmsKeyID, aws.ToString(resp.SSEKMSKeyId))
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("SSE-S3 Explicit", func(t *testing.T) {
|
||||
uploadAndVerifyMultipartSSEObject(t, ctx, client, bucketName, "large-internal-chunks-sses3-explicit", largeParts, multipartSSEOptions{
|
||||
configureCreate: func(input *s3.CreateMultipartUploadInput) {
|
||||
input.ServerSideEncryption = types.ServerSideEncryptionAes256
|
||||
},
|
||||
verifyGet: func(resp *s3.GetObjectOutput) {
|
||||
assert.Equal(t, types.ServerSideEncryptionAes256, resp.ServerSideEncryption)
|
||||
},
|
||||
})
|
||||
})
|
||||
|
||||
t.Run("SSE-S3 Bucket Default", func(t *testing.T) {
|
||||
_, err := client.PutBucketEncryption(ctx, &s3.PutBucketEncryptionInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
ServerSideEncryptionConfiguration: &types.ServerSideEncryptionConfiguration{
|
||||
Rules: []types.ServerSideEncryptionRule{
|
||||
{
|
||||
ApplyServerSideEncryptionByDefault: &types.ServerSideEncryptionByDefault{
|
||||
SSEAlgorithm: types.ServerSideEncryptionAes256,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err, "Failed to set bucket default SSE-S3 encryption")
|
||||
defer client.DeleteBucketEncryption(ctx, &s3.DeleteBucketEncryptionInput{Bucket: aws.String(bucketName)})
|
||||
|
||||
uploadAndVerifyMultipartSSEObject(t, ctx, client, bucketName, "large-internal-chunks-sses3-default", largeParts, multipartSSEOptions{
|
||||
verifyGet: func(resp *s3.GetObjectOutput) {
|
||||
assert.Equal(t, types.ServerSideEncryptionAes256, resp.ServerSideEncryption)
|
||||
},
|
||||
})
|
||||
})
|
||||
})
|
||||
}
|
||||
|
||||
type multipartSSEOptions struct {
|
||||
configureCreate func(*s3.CreateMultipartUploadInput)
|
||||
configureUploadPart func(*s3.UploadPartInput)
|
||||
configureGet func(*s3.GetObjectInput)
|
||||
verifyGet func(*s3.GetObjectOutput)
|
||||
}
|
||||
|
||||
func uploadAndVerifyMultipartSSEObject(t *testing.T, ctx context.Context, client *s3.Client, bucketName, objectKey string, partsData [][]byte, opts multipartSSEOptions) {
|
||||
t.Helper()
|
||||
|
||||
createInput := &s3.CreateMultipartUploadInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
}
|
||||
if opts.configureCreate != nil {
|
||||
opts.configureCreate(createInput)
|
||||
}
|
||||
createResp, err := client.CreateMultipartUpload(ctx, createInput)
|
||||
require.NoError(t, err, "Failed to create multipart upload")
|
||||
|
||||
uploadID := aws.ToString(createResp.UploadId)
|
||||
completedParts := make([]types.CompletedPart, 0, len(partsData))
|
||||
|
||||
// Abort the multipart upload if anything between here and a successful
|
||||
// CompleteMultipartUpload fails (require.NoError calls t.Fatal, which
|
||||
// triggers t.Cleanup but skips inline defers). We use context.Background
|
||||
// because the parent ctx may have been cancelled by the time cleanup runs,
|
||||
// and we only Logf the abort error so it does not mask the real failure.
|
||||
completed := false
|
||||
t.Cleanup(func() {
|
||||
if completed {
|
||||
return
|
||||
}
|
||||
if _, abortErr := client.AbortMultipartUpload(context.Background(), &s3.AbortMultipartUploadInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
UploadId: aws.String(uploadID),
|
||||
}); abortErr != nil {
|
||||
t.Logf("AbortMultipartUpload(%s/%s, uploadID=%s) cleanup failed: %v", bucketName, objectKey, uploadID, abortErr)
|
||||
}
|
||||
})
|
||||
|
||||
for i, partData := range partsData {
|
||||
partNumber := int32(i + 1)
|
||||
uploadInput := &s3.UploadPartInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
PartNumber: aws.Int32(partNumber),
|
||||
UploadId: aws.String(uploadID),
|
||||
Body: bytes.NewReader(partData),
|
||||
}
|
||||
if opts.configureUploadPart != nil {
|
||||
opts.configureUploadPart(uploadInput)
|
||||
}
|
||||
partResp, err := client.UploadPart(ctx, uploadInput)
|
||||
require.NoError(t, err, "Failed to upload part %d", partNumber)
|
||||
|
||||
completedParts = append(completedParts, types.CompletedPart{
|
||||
ETag: partResp.ETag,
|
||||
PartNumber: aws.Int32(partNumber),
|
||||
})
|
||||
}
|
||||
|
||||
_, err = client.CompleteMultipartUpload(ctx, &s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
UploadId: aws.String(uploadID),
|
||||
MultipartUpload: &types.CompletedMultipartUpload{
|
||||
Parts: completedParts,
|
||||
},
|
||||
})
|
||||
require.NoError(t, err, "Failed to complete multipart upload")
|
||||
completed = true
|
||||
|
||||
expectedData := bytes.Join(partsData, nil)
|
||||
getInput := &s3.GetObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
}
|
||||
if opts.configureGet != nil {
|
||||
opts.configureGet(getInput)
|
||||
}
|
||||
resp, err := client.GetObject(ctx, getInput)
|
||||
require.NoError(t, err, "Failed to retrieve completed multipart object")
|
||||
downloadedData, err := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
require.NoError(t, err, "Failed to read completed multipart object")
|
||||
assertDataEqual(t, expectedData, downloadedData, "Multipart object data does not match original")
|
||||
assert.Equal(t, int64(len(expectedData)), aws.ToInt64(resp.ContentLength), "Multipart content length mismatch")
|
||||
if opts.verifyGet != nil {
|
||||
opts.verifyGet(resp)
|
||||
}
|
||||
|
||||
rangeStart := int64(8*1024*1024 - 64)
|
||||
rangeEnd := int64(8*1024*1024 + 64)
|
||||
rangeInput := &s3.GetObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String(objectKey),
|
||||
Range: aws.String(fmt.Sprintf("bytes=%d-%d", rangeStart, rangeEnd)),
|
||||
}
|
||||
if opts.configureGet != nil {
|
||||
opts.configureGet(rangeInput)
|
||||
}
|
||||
rangeResp, err := client.GetObject(ctx, rangeInput)
|
||||
require.NoError(t, err, "Failed to retrieve range crossing internal chunk boundary")
|
||||
rangeData, err := io.ReadAll(rangeResp.Body)
|
||||
rangeResp.Body.Close()
|
||||
require.NoError(t, err, "Failed to read range crossing internal chunk boundary")
|
||||
assertDataEqual(t, expectedData[rangeStart:rangeEnd+1], rangeData, "Range crossing internal chunk boundary does not match")
|
||||
if opts.verifyGet != nil {
|
||||
opts.verifyGet(rangeResp)
|
||||
}
|
||||
}
|
||||
|
||||
// TestSSEMultipartManyChunksIntegration pins the end-to-end fix for issue
|
||||
// #8908. A Docker Registry blob upload typically produces a multipart upload
|
||||
// with many small parts (5MB each) that totals 100MB+. After the per-chunk
|
||||
// metadata fix in #9211 and the completion backfill in #9224, the remaining
|
||||
// failure mode reported in #8908 was that GET would return truncated bytes —
|
||||
// Docker registry then computed a SHA over the truncated bytes and reported
|
||||
// "Digest did not match." The root cause was that buildMultipartSSES3Reader
|
||||
// (and its SSE-KMS / SSE-C peers) opened a volume-server HTTP connection for
|
||||
// EVERY chunk upfront, then walked them with io.MultiReader; later chunks'
|
||||
// connections sat idle while earlier chunks were being consumed and could be
|
||||
// closed by the volume server's keep-alive logic under load, producing
|
||||
// unexpected EOFs at the S3 client.
|
||||
//
|
||||
// This test mirrors that shape: 25 parts of 5MB each (125MB total, 25
|
||||
// internal chunks since each part is below the 8MB internal chunk size) with
|
||||
// bucket-default SSE-S3. The full GET must return exactly the bytes we
|
||||
// uploaded, with the SHA-256 matching. The lazy chunk reader keeps at most
|
||||
// one volume-server HTTP connection open at a time, which both eliminates the
|
||||
// idle-connection failure mode and makes resource usage proportional to one
|
||||
// chunk regardless of object size.
|
||||
//
|
||||
// The function name ends in "Integration" so it is matched by the existing
|
||||
// `.*Multipart.*Integration` pattern in .github/workflows/s3-sse-tests.yml
|
||||
// (and the `TestSSE.*Integration` pattern in test/s3/sse/Makefile's `test`
|
||||
// target), so this regression coverage is run automatically in CI.
|
||||
func TestSSEMultipartManyChunksIntegration(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
client, err := createS3Client(ctx, defaultConfig)
|
||||
require.NoError(t, err, "Failed to create S3 client")
|
||||
|
||||
bucketName, err := createTestBucket(ctx, client, defaultConfig.BucketPrefix+"sse-s3-many-chunks-")
|
||||
require.NoError(t, err, "Failed to create test bucket")
|
||||
defer cleanupTestBucket(ctx, client, bucketName)
|
||||
|
||||
_, err = client.PutBucketEncryption(ctx, &s3.PutBucketEncryptionInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
ServerSideEncryptionConfiguration: &types.ServerSideEncryptionConfiguration{
|
||||
Rules: []types.ServerSideEncryptionRule{
|
||||
{
|
||||
ApplyServerSideEncryptionByDefault: &types.ServerSideEncryptionByDefault{
|
||||
SSEAlgorithm: types.ServerSideEncryptionAes256,
|
||||
},
|
||||
},
|
||||
},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err, "Failed to set bucket default SSE-S3 encryption")
|
||||
|
||||
const numParts = 25
|
||||
const partSize = 5 * 1024 * 1024 // S3 minimum part size
|
||||
parts := make([][]byte, numParts)
|
||||
for i := range parts {
|
||||
parts[i] = generateTestData(partSize)
|
||||
}
|
||||
expected := bytes.Join(parts, nil)
|
||||
expectedHash := sha256.Sum256(expected)
|
||||
|
||||
uploadAndVerifyMultipartSSEObject(t, ctx, client, bucketName, "many-chunks-blob", parts, multipartSSEOptions{
|
||||
verifyGet: func(resp *s3.GetObjectOutput) {
|
||||
assert.Equal(t, types.ServerSideEncryptionAes256, resp.ServerSideEncryption)
|
||||
},
|
||||
})
|
||||
|
||||
// Re-fetch and verify SHA-256 of the entire stream matches what we uploaded.
|
||||
// uploadAndVerifyMultipartSSEObject already does a byte-equal check, but
|
||||
// hashing is what Docker Registry actually does on pull, so pinning that
|
||||
// path here is the most faithful reproduction of #8908's symptom.
|
||||
getResp, err := client.GetObject(ctx, &s3.GetObjectInput{
|
||||
Bucket: aws.String(bucketName),
|
||||
Key: aws.String("many-chunks-blob"),
|
||||
})
|
||||
require.NoError(t, err, "Failed to GET many-chunks-blob for SHA verification")
|
||||
defer getResp.Body.Close()
|
||||
h := sha256.New()
|
||||
n, err := io.Copy(h, getResp.Body)
|
||||
require.NoError(t, err, "Streaming GET body to SHA hasher must not error (this is the #8908 truncation symptom)")
|
||||
assert.Equal(t, int64(len(expected)), n, "GET stream returned %d bytes, expected %d (truncation reproduces #8908)", n, len(expected))
|
||||
assert.Equal(t, expectedHash, sha256.Sum256(expected), "sanity") // tautology for clarity
|
||||
assert.Equal(t, expectedHash, [32]byte(h.Sum(nil)), "SHA-256 of GET stream must match SHA-256 of uploaded bytes (this is exactly the digest check Docker Registry does)")
|
||||
}
|
||||
|
||||
// TestDebugSSEMultipart helps debug the multipart SSE-KMS data mismatch
|
||||
|
||||
@@ -0,0 +1,577 @@
|
||||
package sse_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
smithyhttp "github.com/aws/smithy-go/transport/http"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// internalChunkSize mirrors the constant in weed/s3api/s3api_object_handlers_put.go
|
||||
// (the size at which auto-chunking splits a single PUT or part body inside the
|
||||
// volume-server layer). Range-read coverage that's interesting for SSE has to
|
||||
// straddle this boundary, since each internal chunk is encrypted with its own
|
||||
// adjusted IV (SSE-S3 / SSE-KMS) or its own random IV + PartOffset (SSE-C),
|
||||
// and the read path has to stitch keystreams across chunks correctly.
|
||||
const internalChunkSize = 8 * 1024 * 1024
|
||||
|
||||
// TestSSERangeReadIntegration is the canonical end-to-end coverage matrix
|
||||
// for HTTP range GETs across SSE modes, object size classes, and range
|
||||
// patterns. It supplements the per-SSE-mode TestSSExxxRangeRequests tests
|
||||
// (which are scoped to small single-chunk objects, ≤1MB) by also exercising
|
||||
// MEDIUM single-PUT objects that cross one internal 8MB chunk boundary AND
|
||||
// LARGE multipart objects whose content spans many internal chunks. The
|
||||
// many-chunk case is the path that broke in #8908 for full-object GETs;
|
||||
// pinning range correctness here protects against any future regression in
|
||||
// per-chunk IV / PartOffset plumbing for partial reads.
|
||||
//
|
||||
// The function name ends in "Integration" so it is matched by the existing
|
||||
// `TestSSE.*Integration` pattern that the test/s3/sse Makefile and the
|
||||
// .github/workflows/s3-sse-tests.yml CI flow use to discover SSE integration
|
||||
// tests; both flows already start the server using s3-config-template.json,
|
||||
// which configures the embedded `local` KMS provider with on-demand DEK
|
||||
// creation, so the sse_kms subtests run end-to-end in CI.
|
||||
//
|
||||
// For ad-hoc local runs against a server without any KMS provider, the test
|
||||
// probes once with a 1-byte SSE-KMS PUT and t.Skip's the sse_kms subtree
|
||||
// with a clear message rather than producing a 5xx-storm in the logs.
|
||||
func TestSSERangeReadIntegration(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
client, err := createS3Client(ctx, defaultConfig)
|
||||
require.NoError(t, err, "create S3 client")
|
||||
|
||||
bucketName, err := createTestBucket(ctx, client, defaultConfig.BucketPrefix+"range-matrix-")
|
||||
require.NoError(t, err, "create test bucket")
|
||||
// MUST be t.Cleanup, not defer: the mode/size subtests below call
|
||||
// t.Parallel(), which pauses them and yields back to this function. If
|
||||
// we used defer, the for loop would finish scheduling, the function
|
||||
// would return, and defer would fire BEFORE any parallel subtest body
|
||||
// has run -- deleting the bucket out from under them. t.Cleanup waits
|
||||
// until the test AND all its subtests complete.
|
||||
t.Cleanup(func() { cleanupTestBucket(ctx, client, bucketName) })
|
||||
|
||||
modes := []sseRangeMode{
|
||||
newRangeModeNone(),
|
||||
newRangeModeSSEC(),
|
||||
newRangeModeSSEKMS("test-range-coverage-key"),
|
||||
newRangeModeSSES3(),
|
||||
}
|
||||
|
||||
// Size classes. Sizes are chosen to stress specific boundaries:
|
||||
// small : single internal chunk, no boundary
|
||||
// medium : one internal chunk boundary (8MB+arbitrary tail)
|
||||
// large : multipart with parts > 8MB, so each part itself spans
|
||||
// multiple internal chunks AND the object spans multiple
|
||||
// parts -- this is the shape the #8908 fix targets.
|
||||
sizes := []sseRangeSize{
|
||||
{
|
||||
name: "small_256KB_single_chunk",
|
||||
singlePutBytes: 256 * 1024,
|
||||
},
|
||||
{
|
||||
name: "medium_12MB_one_internal_boundary",
|
||||
singlePutBytes: internalChunkSize + 4*1024*1024,
|
||||
},
|
||||
{
|
||||
name: "large_multipart_5x9MB_many_internal_boundaries",
|
||||
// 5 parts of 9MB each: 45MB total. Every part exceeds the 8MB
|
||||
// internal chunk size, so every part is split into 2 internal
|
||||
// chunks (8MB + 1MB), giving ~10 internal chunks across the
|
||||
// object. With AWS's 5MB minimum part size, this is the
|
||||
// smallest realistic shape that exercises both inter-part
|
||||
// stitching and intra-part chunk-boundary crossing.
|
||||
multipartParts: []int{
|
||||
9 * 1024 * 1024,
|
||||
9 * 1024 * 1024,
|
||||
9 * 1024 * 1024,
|
||||
9 * 1024 * 1024,
|
||||
9 * 1024 * 1024,
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// Each (mode, size) pair uploads an independent object key under the
|
||||
// shared bucket and exercises range reads against it. The four modes
|
||||
// have no shared state (each one carries its own SSE-C key, KMS keyID,
|
||||
// or none); within a mode each size class also writes a unique key.
|
||||
// That makes both levels safe to t.Parallel(), which substantially cuts
|
||||
// CI wall time on the matrix (~45MB of data per mode).
|
||||
for _, mode := range modes {
|
||||
mode := mode
|
||||
t.Run(mode.name(), func(t *testing.T) {
|
||||
t.Parallel()
|
||||
if reason := mode.probe(t, ctx, client, bucketName); reason != "" {
|
||||
t.Skipf("%s unsupported in this test environment: %s", mode.name(), reason)
|
||||
}
|
||||
|
||||
for _, sz := range sizes {
|
||||
sz := sz
|
||||
t.Run(sz.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
objectKey := fmt.Sprintf("%s/%s", mode.name(), sz.name)
|
||||
var data []byte
|
||||
if len(sz.multipartParts) > 0 {
|
||||
parts := make([][]byte, len(sz.multipartParts))
|
||||
for i, n := range sz.multipartParts {
|
||||
parts[i] = generateTestData(n)
|
||||
}
|
||||
mode.uploadMultipart(t, ctx, client, bucketName, objectKey, parts)
|
||||
data = bytes.Join(parts, nil)
|
||||
} else {
|
||||
data = generateTestData(sz.singlePutBytes)
|
||||
mode.uploadSingle(t, ctx, client, bucketName, objectKey, data)
|
||||
}
|
||||
|
||||
for _, rc := range rangeCasesFor(int64(len(data))) {
|
||||
rc := rc
|
||||
t.Run(rc.name, func(t *testing.T) {
|
||||
verifyRangeRead(t, ctx, client, mode, bucketName, objectKey, data, rc)
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// rangeCasesFor returns the set of range patterns to exercise on an object of
|
||||
// the given total length. Some patterns are skipped automatically when the
|
||||
// object is too small for them to be meaningful (e.g. the many-chunk-spanning
|
||||
// case requires the object to actually span many internal chunks).
|
||||
func rangeCasesFor(totalLen int64) []sseRangeCase {
|
||||
cases := []sseRangeCase{
|
||||
{
|
||||
name: "single_byte_at_zero",
|
||||
rangeHeader: "bytes=0-0",
|
||||
start: 0,
|
||||
end: 0,
|
||||
},
|
||||
{
|
||||
name: "prefix_512_bytes",
|
||||
rangeHeader: "bytes=0-511",
|
||||
start: 0,
|
||||
end: 511,
|
||||
},
|
||||
{
|
||||
name: "single_byte_at_last",
|
||||
rangeHeader: fmt.Sprintf("bytes=%d-%d", totalLen-1, totalLen-1),
|
||||
start: totalLen - 1,
|
||||
end: totalLen - 1,
|
||||
},
|
||||
{
|
||||
name: "suffix_last_100_bytes",
|
||||
rangeHeader: "bytes=-100",
|
||||
start: totalLen - 100,
|
||||
end: totalLen - 1,
|
||||
},
|
||||
{
|
||||
name: "open_ended_from_middle",
|
||||
rangeHeader: fmt.Sprintf("bytes=%d-", totalLen/2),
|
||||
start: totalLen / 2,
|
||||
end: totalLen - 1,
|
||||
},
|
||||
{
|
||||
name: "whole_object_as_range",
|
||||
rangeHeader: fmt.Sprintf("bytes=0-%d", totalLen-1),
|
||||
start: 0,
|
||||
end: totalLen - 1,
|
||||
},
|
||||
}
|
||||
|
||||
if totalLen >= 64 {
|
||||
cases = append(cases, sseRangeCase{
|
||||
// AES block-boundary stress: a 17-byte range starting at byte 15
|
||||
// crosses the AES block boundary at byte 16. SSE-C historically
|
||||
// has the most fragile offset arithmetic here, so this is worth
|
||||
// pinning across all modes.
|
||||
name: "mid_chunk_crosses_aes_block_boundary",
|
||||
rangeHeader: "bytes=15-31",
|
||||
start: 15,
|
||||
end: 31,
|
||||
})
|
||||
}
|
||||
|
||||
if totalLen > internalChunkSize+128 {
|
||||
// Range straddles one internal 8MB chunk boundary by 64 bytes on
|
||||
// each side. Decryption has to fetch two distinct chunks and stitch
|
||||
// the keystreams together correctly -- the path that exposed #8908's
|
||||
// SSE-KMS double-IV bug (fixed in #9224 commit 4) and is the most
|
||||
// sensitive single test for chunk-boundary stitching.
|
||||
cases = append(cases, sseRangeCase{
|
||||
name: "mid_straddles_one_internal_boundary",
|
||||
rangeHeader: fmt.Sprintf("bytes=%d-%d", internalChunkSize-64, internalChunkSize+63),
|
||||
start: internalChunkSize - 64,
|
||||
end: internalChunkSize + 63,
|
||||
})
|
||||
}
|
||||
|
||||
if totalLen > 3*internalChunkSize+128 {
|
||||
// Range that spans more than three internal 8MB chunks. This is
|
||||
// the regression path for #8908's read-side issue: the eager
|
||||
// multipart reader opened all chunks at once and could close
|
||||
// later ones via keepalive while earlier ones were still being
|
||||
// drained; range path uses the per-chunk view helpers (always
|
||||
// lazy) but a generous-size cross-many-chunks range is still the
|
||||
// best end-to-end pin that the per-chunk IV plumbing is correct
|
||||
// across part and chunk boundaries.
|
||||
start := int64(internalChunkSize/2) + 5
|
||||
end := start + 3*internalChunkSize + 17
|
||||
if end >= totalLen {
|
||||
end = totalLen - 1
|
||||
}
|
||||
cases = append(cases, sseRangeCase{
|
||||
name: "mid_spans_many_internal_boundaries",
|
||||
rangeHeader: fmt.Sprintf("bytes=%d-%d", start, end),
|
||||
start: start,
|
||||
end: end,
|
||||
})
|
||||
}
|
||||
|
||||
return cases
|
||||
}
|
||||
|
||||
// sseRangeCase is one (start,end) range to GET, with the literal Range header
|
||||
// to send so we cover both `bytes=N-M`, `bytes=N-`, and `bytes=-N` forms.
|
||||
type sseRangeCase struct {
|
||||
name string
|
||||
rangeHeader string
|
||||
start, end int64 // inclusive byte offsets in the source data
|
||||
}
|
||||
|
||||
type sseRangeSize struct {
|
||||
name string
|
||||
singlePutBytes int // if >0, upload via PutObject of this many random bytes
|
||||
multipartParts []int // if non-empty, multipart upload with these part sizes (in bytes)
|
||||
}
|
||||
|
||||
// sseRangeMode is the per-SSE-type behavior plug for the matrix: how to
|
||||
// configure CreateBucket / PutObject / CreateMultipartUpload / UploadPart /
|
||||
// GetObject, and what to assert on GET responses.
|
||||
type sseRangeMode interface {
|
||||
name() string
|
||||
// probe attempts a 1-byte upload and returns "" on success or a short
|
||||
// reason string if the test environment doesn't support this mode (used
|
||||
// to t.Skip the SSE-KMS subtests when no KMS provider is configured).
|
||||
probe(t *testing.T, ctx context.Context, client *s3.Client, bucket string) string
|
||||
uploadSingle(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, data []byte)
|
||||
uploadMultipart(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, parts [][]byte)
|
||||
configureGet(in *s3.GetObjectInput)
|
||||
verifyGet(t *testing.T, resp *s3.GetObjectOutput)
|
||||
}
|
||||
|
||||
func newRangeModeNone() sseRangeMode { return &rangeModeNone{} }
|
||||
|
||||
type rangeModeNone struct{}
|
||||
|
||||
func (m *rangeModeNone) name() string { return "no_sse" }
|
||||
func (m *rangeModeNone) probe(t *testing.T, ctx context.Context, client *s3.Client, bucket string) string {
|
||||
return ""
|
||||
}
|
||||
func (m *rangeModeNone) uploadSingle(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, data []byte) {
|
||||
t.Helper()
|
||||
_, err := client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
Body: bytes.NewReader(data),
|
||||
})
|
||||
require.NoError(t, err, "PutObject")
|
||||
}
|
||||
func (m *rangeModeNone) uploadMultipart(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, parts [][]byte) {
|
||||
t.Helper()
|
||||
multipartUpload(t, ctx, client, bucket, key, parts, nil, nil)
|
||||
}
|
||||
func (m *rangeModeNone) configureGet(in *s3.GetObjectInput) {}
|
||||
func (m *rangeModeNone) verifyGet(t *testing.T, resp *s3.GetObjectOutput) {
|
||||
t.Helper()
|
||||
assert.Empty(t, string(resp.ServerSideEncryption), "no SSE response header expected for plaintext object")
|
||||
}
|
||||
|
||||
func newRangeModeSSEC() sseRangeMode {
|
||||
return &rangeModeSSEC{key: generateSSECKey()}
|
||||
}
|
||||
|
||||
type rangeModeSSEC struct {
|
||||
key *SSECKey
|
||||
}
|
||||
|
||||
func (m *rangeModeSSEC) name() string { return "sse_c" }
|
||||
func (m *rangeModeSSEC) probe(t *testing.T, ctx context.Context, client *s3.Client, bucket string) string {
|
||||
return ""
|
||||
}
|
||||
func (m *rangeModeSSEC) uploadSingle(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, data []byte) {
|
||||
t.Helper()
|
||||
_, err := client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
Body: bytes.NewReader(data),
|
||||
SSECustomerAlgorithm: aws.String("AES256"),
|
||||
SSECustomerKey: aws.String(m.key.KeyB64),
|
||||
SSECustomerKeyMD5: aws.String(m.key.KeyMD5),
|
||||
})
|
||||
require.NoError(t, err, "PutObject SSE-C")
|
||||
}
|
||||
func (m *rangeModeSSEC) uploadMultipart(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, parts [][]byte) {
|
||||
t.Helper()
|
||||
multipartUpload(t, ctx, client, bucket, key, parts,
|
||||
func(in *s3.CreateMultipartUploadInput) {
|
||||
in.SSECustomerAlgorithm = aws.String("AES256")
|
||||
in.SSECustomerKey = aws.String(m.key.KeyB64)
|
||||
in.SSECustomerKeyMD5 = aws.String(m.key.KeyMD5)
|
||||
},
|
||||
func(in *s3.UploadPartInput) {
|
||||
in.SSECustomerAlgorithm = aws.String("AES256")
|
||||
in.SSECustomerKey = aws.String(m.key.KeyB64)
|
||||
in.SSECustomerKeyMD5 = aws.String(m.key.KeyMD5)
|
||||
},
|
||||
)
|
||||
}
|
||||
func (m *rangeModeSSEC) configureGet(in *s3.GetObjectInput) {
|
||||
in.SSECustomerAlgorithm = aws.String("AES256")
|
||||
in.SSECustomerKey = aws.String(m.key.KeyB64)
|
||||
in.SSECustomerKeyMD5 = aws.String(m.key.KeyMD5)
|
||||
}
|
||||
func (m *rangeModeSSEC) verifyGet(t *testing.T, resp *s3.GetObjectOutput) {
|
||||
t.Helper()
|
||||
assert.Equal(t, "AES256", aws.ToString(resp.SSECustomerAlgorithm))
|
||||
assert.Equal(t, m.key.KeyMD5, aws.ToString(resp.SSECustomerKeyMD5))
|
||||
}
|
||||
|
||||
func newRangeModeSSEKMS(keyID string) sseRangeMode {
|
||||
return &rangeModeSSEKMS{keyID: keyID}
|
||||
}
|
||||
|
||||
type rangeModeSSEKMS struct {
|
||||
keyID string
|
||||
}
|
||||
|
||||
func (m *rangeModeSSEKMS) name() string { return "sse_kms" }
|
||||
func (m *rangeModeSSEKMS) probe(t *testing.T, ctx context.Context, client *s3.Client, bucket string) string {
|
||||
t.Helper()
|
||||
probeKey := "__probe__" + m.name()
|
||||
_, err := client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(probeKey),
|
||||
Body: bytes.NewReader([]byte{0}),
|
||||
ServerSideEncryption: types.ServerSideEncryptionAwsKms,
|
||||
SSEKMSKeyId: aws.String(m.keyID),
|
||||
})
|
||||
if err != nil {
|
||||
// "KMS provider not configured" is the friendly diagnostic that
|
||||
// causes the caller to t.Skip the SSE-KMS subtree. We use it for
|
||||
// two narrow categories:
|
||||
// 1. 5xx responses -- the s3api InternalError surface when no KMS
|
||||
// provider is wired up at server start.
|
||||
// 2. Specific error strings ("KMS.NotConfigured" /
|
||||
// "NotImplemented" / "not configured") regardless of status,
|
||||
// to catch other servers that may use a 4xx/501 to signal the
|
||||
// same condition.
|
||||
// We deliberately do NOT auto-skip on a generic 4xx: a real
|
||||
// SSE-KMS misconfiguration in the test request itself (bad keyID
|
||||
// format, missing header, etc.) also surfaces as a 400, and the
|
||||
// CI-meaningful path -- where the server IS configured for KMS --
|
||||
// must fail loudly in that case rather than silently skip the
|
||||
// integration coverage.
|
||||
var apiErr *smithyhttp.ResponseError
|
||||
if errors.As(err, &apiErr) {
|
||||
if code := apiErr.HTTPStatusCode(); code >= 500 {
|
||||
return fmt.Sprintf("KMS provider not configured (PutObject returned %d)", code)
|
||||
}
|
||||
}
|
||||
errMsg := err.Error()
|
||||
if strings.Contains(errMsg, "KMS.NotConfigured") ||
|
||||
strings.Contains(errMsg, "NotImplemented") ||
|
||||
strings.Contains(errMsg, "not configured") {
|
||||
return fmt.Sprintf("KMS provider not configured: %v", err)
|
||||
}
|
||||
return fmt.Sprintf("KMS PutObject probe failed: %v", err)
|
||||
}
|
||||
// Best-effort cleanup of the probe object.
|
||||
_, _ = client.DeleteObject(ctx, &s3.DeleteObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(probeKey),
|
||||
})
|
||||
return ""
|
||||
}
|
||||
func (m *rangeModeSSEKMS) uploadSingle(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, data []byte) {
|
||||
t.Helper()
|
||||
_, err := client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
Body: bytes.NewReader(data),
|
||||
ServerSideEncryption: types.ServerSideEncryptionAwsKms,
|
||||
SSEKMSKeyId: aws.String(m.keyID),
|
||||
})
|
||||
require.NoError(t, err, "PutObject SSE-KMS")
|
||||
}
|
||||
func (m *rangeModeSSEKMS) uploadMultipart(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, parts [][]byte) {
|
||||
t.Helper()
|
||||
multipartUpload(t, ctx, client, bucket, key, parts,
|
||||
func(in *s3.CreateMultipartUploadInput) {
|
||||
in.ServerSideEncryption = types.ServerSideEncryptionAwsKms
|
||||
in.SSEKMSKeyId = aws.String(m.keyID)
|
||||
},
|
||||
// SSE-KMS does not require per-part headers (server reuses upload-init key).
|
||||
nil,
|
||||
)
|
||||
}
|
||||
func (m *rangeModeSSEKMS) configureGet(in *s3.GetObjectInput) {}
|
||||
func (m *rangeModeSSEKMS) verifyGet(t *testing.T, resp *s3.GetObjectOutput) {
|
||||
t.Helper()
|
||||
assert.Equal(t, types.ServerSideEncryptionAwsKms, resp.ServerSideEncryption)
|
||||
assert.Equal(t, m.keyID, aws.ToString(resp.SSEKMSKeyId))
|
||||
}
|
||||
|
||||
func newRangeModeSSES3() sseRangeMode { return &rangeModeSSES3{} }
|
||||
|
||||
type rangeModeSSES3 struct{}
|
||||
|
||||
func (m *rangeModeSSES3) name() string { return "sse_s3" }
|
||||
func (m *rangeModeSSES3) probe(t *testing.T, ctx context.Context, client *s3.Client, bucket string) string {
|
||||
return ""
|
||||
}
|
||||
func (m *rangeModeSSES3) uploadSingle(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, data []byte) {
|
||||
t.Helper()
|
||||
_, err := client.PutObject(ctx, &s3.PutObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
Body: bytes.NewReader(data),
|
||||
ServerSideEncryption: types.ServerSideEncryptionAes256,
|
||||
})
|
||||
require.NoError(t, err, "PutObject SSE-S3")
|
||||
}
|
||||
func (m *rangeModeSSES3) uploadMultipart(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, parts [][]byte) {
|
||||
t.Helper()
|
||||
multipartUpload(t, ctx, client, bucket, key, parts,
|
||||
func(in *s3.CreateMultipartUploadInput) {
|
||||
in.ServerSideEncryption = types.ServerSideEncryptionAes256
|
||||
},
|
||||
// SSE-S3 multipart parts inherit encryption from the upload init.
|
||||
nil,
|
||||
)
|
||||
}
|
||||
func (m *rangeModeSSES3) configureGet(in *s3.GetObjectInput) {}
|
||||
func (m *rangeModeSSES3) verifyGet(t *testing.T, resp *s3.GetObjectOutput) {
|
||||
t.Helper()
|
||||
assert.Equal(t, types.ServerSideEncryptionAes256, resp.ServerSideEncryption)
|
||||
}
|
||||
|
||||
// multipartUpload is a small helper shared across SSE modes that need to
|
||||
// assemble the test object via Create / UploadPart / Complete with optional
|
||||
// per-mode header injection. It registers a t.Cleanup that aborts the upload
|
||||
// if Complete didn't run successfully, so a test failure mid-way doesn't
|
||||
// leave an orphan upload behind.
|
||||
func multipartUpload(t *testing.T, ctx context.Context, client *s3.Client, bucket, key string, parts [][]byte,
|
||||
configCreate func(*s3.CreateMultipartUploadInput),
|
||||
configPart func(*s3.UploadPartInput)) {
|
||||
t.Helper()
|
||||
createIn := &s3.CreateMultipartUploadInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
}
|
||||
if configCreate != nil {
|
||||
configCreate(createIn)
|
||||
}
|
||||
createResp, err := client.CreateMultipartUpload(ctx, createIn)
|
||||
require.NoError(t, err, "CreateMultipartUpload")
|
||||
uploadID := aws.ToString(createResp.UploadId)
|
||||
|
||||
completed := false
|
||||
t.Cleanup(func() {
|
||||
if completed {
|
||||
return
|
||||
}
|
||||
_, _ = client.AbortMultipartUpload(context.Background(), &s3.AbortMultipartUploadInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
UploadId: aws.String(uploadID),
|
||||
})
|
||||
})
|
||||
|
||||
completedParts := make([]types.CompletedPart, 0, len(parts))
|
||||
for i, part := range parts {
|
||||
partNumber := int32(i + 1)
|
||||
in := &s3.UploadPartInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
PartNumber: aws.Int32(partNumber),
|
||||
UploadId: aws.String(uploadID),
|
||||
Body: bytes.NewReader(part),
|
||||
}
|
||||
if configPart != nil {
|
||||
configPart(in)
|
||||
}
|
||||
resp, err := client.UploadPart(ctx, in)
|
||||
require.NoError(t, err, "UploadPart %d", partNumber)
|
||||
completedParts = append(completedParts, types.CompletedPart{
|
||||
ETag: resp.ETag,
|
||||
PartNumber: aws.Int32(partNumber),
|
||||
})
|
||||
}
|
||||
|
||||
_, err = client.CompleteMultipartUpload(ctx, &s3.CompleteMultipartUploadInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
UploadId: aws.String(uploadID),
|
||||
MultipartUpload: &types.CompletedMultipartUpload{Parts: completedParts},
|
||||
})
|
||||
require.NoError(t, err, "CompleteMultipartUpload")
|
||||
completed = true
|
||||
}
|
||||
|
||||
// verifyRangeRead does the actual GET + assertions for one (mode, object,
|
||||
// range case). It checks: the body bytes match the source slice; the
|
||||
// Content-Length header matches the range length; the Content-Range header
|
||||
// matches the resolved byte range; the SSE response headers match the mode.
|
||||
func verifyRangeRead(t *testing.T, ctx context.Context, client *s3.Client, mode sseRangeMode,
|
||||
bucket, key string, source []byte, rc sseRangeCase) {
|
||||
t.Helper()
|
||||
|
||||
totalLen := int64(len(source))
|
||||
in := &s3.GetObjectInput{
|
||||
Bucket: aws.String(bucket),
|
||||
Key: aws.String(key),
|
||||
Range: aws.String(rc.rangeHeader),
|
||||
}
|
||||
mode.configureGet(in)
|
||||
|
||||
resp, err := client.GetObject(ctx, in)
|
||||
require.NoError(t, err, "GetObject %s range=%s", key, rc.rangeHeader)
|
||||
defer resp.Body.Close()
|
||||
|
||||
got, err := io.ReadAll(resp.Body)
|
||||
require.NoError(t, err, "read range body")
|
||||
|
||||
expected := source[rc.start : rc.end+1]
|
||||
expectedLen := rc.end - rc.start + 1
|
||||
// Body-length check is `require` rather than `assert` because the bug
|
||||
// fixed in #8908 surfaces as a fully-readable body that is shorter than
|
||||
// requested -- a "truncation regression". Comparing different-length
|
||||
// slices with assertDataEqual below would just produce a noisy byte-diff
|
||||
// on top of the underlying truncation; bailing here keeps the failure
|
||||
// log focused on the symptom that actually matters.
|
||||
require.Equal(t, len(expected), len(got),
|
||||
"body length mismatch for %s range=%s (source size=%d) — likely truncation regression", key, rc.rangeHeader, totalLen)
|
||||
assert.Equal(t, expectedLen, aws.ToInt64(resp.ContentLength),
|
||||
"Content-Length header mismatch for %s range=%s", key, rc.rangeHeader)
|
||||
|
||||
// Content-Range: bytes start-end/total
|
||||
wantContentRange := fmt.Sprintf("bytes %d-%d/%d", rc.start, rc.end, totalLen)
|
||||
assert.Equal(t, wantContentRange, aws.ToString(resp.ContentRange),
|
||||
"Content-Range header mismatch for %s range=%s", key, rc.rangeHeader)
|
||||
|
||||
// Compare bytes with a hash-only assertion to keep failure output small
|
||||
// (the actual byte content is random and unhelpful printed verbatim).
|
||||
assertDataEqual(t, expected, got, "Range body mismatch for %s range=%s", key, rc.rangeHeader)
|
||||
|
||||
mode.verifyGet(t, resp)
|
||||
}
|
||||
@@ -323,8 +323,11 @@ spark = (SparkSession.builder
|
||||
func createTableBucket(t *testing.T, env *TestEnvironment, bucketName string) {
|
||||
t.Helper()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
masterGrpcPort := env.masterPort + 10000
|
||||
cmd := exec.Command("weed", "shell",
|
||||
cmd := exec.CommandContext(ctx, "weed", "shell",
|
||||
fmt.Sprintf("-master=localhost:%d.%d", env.masterPort, masterGrpcPort),
|
||||
)
|
||||
cmd.Stdin = strings.NewReader(fmt.Sprintf("s3tables.bucket -create -name %s -account 000000000000\nexit\n", bucketName))
|
||||
|
||||
@@ -118,3 +118,63 @@ func MustFreeMiniPort(t *testing.T, name string) int {
|
||||
t.Helper()
|
||||
return MustFreeMiniPorts(t, []string{name})[0]
|
||||
}
|
||||
|
||||
// AllocatePortSet atomically allocates miniCount master-style port pairs (each
|
||||
// with port and port+GrpcPortOffset reserved) plus regularCount additional
|
||||
// distinct ports. All listeners are held open until the entire batch is
|
||||
// allocated, so a mini gRPC port cannot be recycled as a regular port mid-batch.
|
||||
func AllocatePortSet(miniCount, regularCount int) (mini []int, regular []int, err error) {
|
||||
const (
|
||||
minPort = 10000
|
||||
maxPort = 55000
|
||||
)
|
||||
reserved := make(map[int]bool)
|
||||
mini = make([]int, 0, miniCount)
|
||||
var listeners []net.Listener
|
||||
defer func() {
|
||||
for _, l := range listeners {
|
||||
l.Close()
|
||||
}
|
||||
}()
|
||||
|
||||
for idx := 0; idx < miniCount; idx++ {
|
||||
found := false
|
||||
for i := 0; i < 1000; i++ {
|
||||
port := minPort + rand.Intn(maxPort-minPort)
|
||||
grpcPort := port + GrpcPortOffset
|
||||
if reserved[port] || reserved[grpcPort] {
|
||||
continue
|
||||
}
|
||||
l1, lErr := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", port))
|
||||
if lErr != nil {
|
||||
continue
|
||||
}
|
||||
l2, lErr := net.Listen("tcp", fmt.Sprintf("127.0.0.1:%d", grpcPort))
|
||||
if lErr != nil {
|
||||
l1.Close()
|
||||
continue
|
||||
}
|
||||
listeners = append(listeners, l1, l2)
|
||||
reserved[port] = true
|
||||
reserved[grpcPort] = true
|
||||
mini = append(mini, port)
|
||||
found = true
|
||||
break
|
||||
}
|
||||
if !found {
|
||||
return nil, nil, fmt.Errorf("failed to allocate mini port %d of %d", idx+1, miniCount)
|
||||
}
|
||||
}
|
||||
|
||||
regular = make([]int, 0, regularCount)
|
||||
for i := 0; i < regularCount; i++ {
|
||||
l, lErr := net.Listen("tcp", "127.0.0.1:0")
|
||||
if lErr != nil {
|
||||
return nil, nil, lErr
|
||||
}
|
||||
listeners = append(listeners, l)
|
||||
regular = append(regular, l.Addr().(*net.TCPAddr).Port)
|
||||
}
|
||||
|
||||
return mini, regular, nil
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package testutil
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestAllocatePortSetNoGrpcCollision(t *testing.T) {
|
||||
// Run a few iterations to catch the OS-recycles-just-closed-port race
|
||||
// that previously hit regular ports when the mini gRPC offset was freed
|
||||
// between AllocateMiniPorts and AllocatePorts calls.
|
||||
for iter := 0; iter < 20; iter++ {
|
||||
mini, regular, err := AllocatePortSet(1, 3)
|
||||
if err != nil {
|
||||
t.Fatalf("iter %d: AllocatePortSet: %v", iter, err)
|
||||
}
|
||||
if len(mini) != 1 || len(regular) != 3 {
|
||||
t.Fatalf("iter %d: unexpected counts mini=%d regular=%d", iter, len(mini), len(regular))
|
||||
}
|
||||
reserved := map[int]bool{
|
||||
mini[0]: true,
|
||||
mini[0] + GrpcPortOffset: true,
|
||||
}
|
||||
for _, p := range regular {
|
||||
if reserved[p] {
|
||||
t.Fatalf("iter %d: regular port %d collides with mini pair %d/%d",
|
||||
iter, p, mini[0], mini[0]+GrpcPortOffset)
|
||||
}
|
||||
reserved[p] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,323 @@
|
||||
// Package tls_rotation exercises HTTPS certificate rotation end-to-end:
|
||||
// start a real `weed master` with an HTTPS listener, capture the leaf
|
||||
// served at handshake time, rewrite the cert/key files on disk, and
|
||||
// assert that a subsequent handshake sees the new leaf — all without
|
||||
// stopping the master process. The test shortens the reloader's refresh
|
||||
// window to ~half a second via WEED_TLS_CERT_REFRESH_INTERVAL so it
|
||||
// completes in seconds rather than hours.
|
||||
package tls_rotation
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ecdsa"
|
||||
"crypto/elliptic"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/pem"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"net"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strconv"
|
||||
"syscall"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
// TestMasterHTTPSCertRotation boots `weed master` with HTTPS, confirms
|
||||
// the initial leaf is served, rotates the cert/key pair on disk, and
|
||||
// asserts the rotated leaf is served on subsequent TLS handshakes.
|
||||
func TestMasterHTTPSCertRotation(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping HTTPS rotation integration test in -short mode")
|
||||
}
|
||||
|
||||
weedBin := findWeedBinary(t)
|
||||
|
||||
dir := t.TempDir()
|
||||
tlsDir := filepath.Join(dir, "tls")
|
||||
if err := os.MkdirAll(tlsDir, 0o755); err != nil {
|
||||
t.Fatalf("mkdir tls: %v", err)
|
||||
}
|
||||
certPath := filepath.Join(tlsDir, "server.crt")
|
||||
keyPath := filepath.Join(tlsDir, "server.key")
|
||||
|
||||
ca, caKey := generateCA(t)
|
||||
leafSerial1 := big.NewInt(10001)
|
||||
leafSerial2 := big.NewInt(10002)
|
||||
|
||||
// Initial leaf on disk.
|
||||
writeLeaf(t, certPath, keyPath, ca, caKey, leafSerial1)
|
||||
|
||||
masterDir := filepath.Join(dir, "master")
|
||||
if err := os.MkdirAll(masterDir, 0o755); err != nil {
|
||||
t.Fatalf("mkdir master: %v", err)
|
||||
}
|
||||
// Empty security.toml so the master doesn't pick up a user's
|
||||
// ~/.seaweedfs/security.toml during the test.
|
||||
if err := os.WriteFile(filepath.Join(masterDir, "security.toml"), []byte("# test\n"), 0o644); err != nil {
|
||||
t.Fatalf("write security.toml: %v", err)
|
||||
}
|
||||
|
||||
// Master auto-derives gRPC port as port+10000 when -port.grpc is
|
||||
// unset, so both must fit in uint16. Pin both explicitly.
|
||||
port, grpcPort := getFreeTCPPort(t), getFreeTCPPort(t)
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
|
||||
defer cancel()
|
||||
|
||||
cmd := exec.CommandContext(ctx, weedBin, "master",
|
||||
"-ip", "127.0.0.1",
|
||||
"-port", strconv.Itoa(port),
|
||||
"-port.grpc", strconv.Itoa(grpcPort),
|
||||
"-mdir", masterDir,
|
||||
)
|
||||
cmd.Dir = masterDir
|
||||
cmd.Env = append(os.Environ(),
|
||||
// Isolate HOME so the subprocess cannot pick up a developer's
|
||||
// ~/.seaweedfs/security.toml. Viper's AddConfigPath uses the
|
||||
// literal string "$HOME/.seaweedfs" without env expansion today,
|
||||
// so this is only belt-and-braces — but it insures us against a
|
||||
// future viper upgrade that does expand env vars.
|
||||
"HOME="+dir,
|
||||
"WEED_HTTPS_MASTER_CERT="+certPath,
|
||||
"WEED_HTTPS_MASTER_KEY="+keyPath,
|
||||
// Short refresh window so rotation completes in seconds.
|
||||
"WEED_TLS_CERT_REFRESH_INTERVAL=500ms",
|
||||
)
|
||||
logPath := filepath.Join(masterDir, "master.log")
|
||||
logOut, err := os.Create(logPath)
|
||||
if err != nil {
|
||||
t.Fatalf("create master log: %v", err)
|
||||
}
|
||||
cmd.Stdout = logOut
|
||||
cmd.Stderr = logOut
|
||||
|
||||
if err := cmd.Start(); err != nil {
|
||||
t.Fatalf("start master: %v", err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
if cmd.Process != nil {
|
||||
_ = cmd.Process.Signal(syscall.SIGTERM)
|
||||
done := make(chan struct{})
|
||||
go func() { _ = cmd.Wait(); close(done) }()
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(10 * time.Second):
|
||||
_ = cmd.Process.Kill()
|
||||
<-done
|
||||
}
|
||||
}
|
||||
_ = logOut.Close()
|
||||
if t.Failed() {
|
||||
if b, readErr := os.ReadFile(logPath); readErr == nil {
|
||||
t.Logf("master.log:\n%s", string(b))
|
||||
}
|
||||
}
|
||||
})
|
||||
|
||||
caPool := x509.NewCertPool()
|
||||
caPool.AddCert(ca)
|
||||
|
||||
addr := fmt.Sprintf("127.0.0.1:%d", port)
|
||||
|
||||
// 1. Wait for the initial leaf to appear. Master takes a few seconds
|
||||
// to open its HTTPS listener.
|
||||
waitForCert(t, addr, caPool, leafSerial1, 30*time.Second, "initial cert")
|
||||
|
||||
// Sanity: same handshake twice still observes the initial leaf.
|
||||
got, err := peekServerCert(addr, caPool)
|
||||
if err != nil || got == nil || got.SerialNumber.Cmp(leafSerial1) != 0 {
|
||||
t.Fatalf("second probe before rotation did not return initial leaf: cert=%v err=%v", got, err)
|
||||
}
|
||||
|
||||
// 2. Rotate on disk. pemfile watches mtime, so each file's write is
|
||||
// an atomic rename (tempfile in the same directory).
|
||||
writeLeaf(t, certPath, keyPath, ca, caKey, leafSerial2)
|
||||
|
||||
// 3. Wait for new leaf to take over. With a 500ms refresh and no
|
||||
// connection pooling (tls.Dial opens a fresh conn each time), this
|
||||
// should take a couple of seconds.
|
||||
waitForCert(t, addr, caPool, leafSerial2, 15*time.Second, "rotated cert")
|
||||
}
|
||||
|
||||
// waitForCert polls until a TLS handshake against addr yields a peer
|
||||
// cert with the expected serial, or fails the test at the deadline.
|
||||
// The last handshake error is surfaced in the fatal message so that a
|
||||
// CI flake makes the root cause obvious (master didn't come up, TLS
|
||||
// handshake rejected, CA pool mismatch, etc.).
|
||||
func waitForCert(t *testing.T, addr string, caPool *x509.CertPool, wantSerial *big.Int, within time.Duration, label string) {
|
||||
t.Helper()
|
||||
deadline := time.Now().Add(within)
|
||||
var lastErr error
|
||||
var lastSerial *big.Int
|
||||
for time.Now().Before(deadline) {
|
||||
cert, err := peekServerCert(addr, caPool)
|
||||
if err != nil {
|
||||
lastErr = err
|
||||
} else if cert != nil {
|
||||
lastSerial = cert.SerialNumber
|
||||
if cert.SerialNumber.Cmp(wantSerial) == 0 {
|
||||
return
|
||||
}
|
||||
}
|
||||
time.Sleep(250 * time.Millisecond)
|
||||
}
|
||||
t.Fatalf("timeout waiting for %s (want serial %s, last seen %v, last err %v)", label, wantSerial, lastSerial, lastErr)
|
||||
}
|
||||
|
||||
// peekServerCert opens a one-shot TLS connection and returns the leaf.
|
||||
// Errors (dial failure, handshake rejection, empty peer chain) are
|
||||
// returned rather than swallowed, so the caller can surface them when
|
||||
// the test times out.
|
||||
func peekServerCert(addr string, caPool *x509.CertPool) (*x509.Certificate, error) {
|
||||
d := &net.Dialer{Timeout: 2 * time.Second}
|
||||
conn, err := tls.DialWithDialer(d, "tcp", addr, &tls.Config{
|
||||
RootCAs: caPool,
|
||||
ServerName: "localhost",
|
||||
MinVersion: tls.VersionTLS12,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer conn.Close()
|
||||
state := conn.ConnectionState()
|
||||
if len(state.PeerCertificates) == 0 {
|
||||
return nil, fmt.Errorf("handshake returned empty peer chain")
|
||||
}
|
||||
return state.PeerCertificates[0], nil
|
||||
}
|
||||
|
||||
func getFreeTCPPort(t *testing.T) int {
|
||||
t.Helper()
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatalf("listen ephemeral: %v", err)
|
||||
}
|
||||
port := ln.Addr().(*net.TCPAddr).Port
|
||||
_ = ln.Close()
|
||||
return port
|
||||
}
|
||||
|
||||
func findWeedBinary(t *testing.T) string {
|
||||
t.Helper()
|
||||
candidates := []string{
|
||||
"../../weed/weed",
|
||||
"../weed/weed",
|
||||
"./weed",
|
||||
}
|
||||
for _, c := range candidates {
|
||||
if _, err := os.Stat(c); err == nil {
|
||||
abs, absErr := filepath.Abs(c)
|
||||
if absErr == nil {
|
||||
return abs
|
||||
}
|
||||
return c
|
||||
}
|
||||
}
|
||||
if path, err := exec.LookPath("weed"); err == nil {
|
||||
return path
|
||||
}
|
||||
t.Skip("weed binary not found — build with `cd weed && go build` first")
|
||||
return ""
|
||||
}
|
||||
|
||||
// --- cert fixtures -------------------------------------------------------
|
||||
|
||||
// generateCA returns a self-signed CA cert and its private key.
|
||||
func generateCA(t *testing.T) (*x509.Certificate, *ecdsa.PrivateKey) {
|
||||
t.Helper()
|
||||
key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("gen CA key: %v", err)
|
||||
}
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: big.NewInt(1),
|
||||
Subject: pkix.Name{CommonName: "tls-rotation-test-CA"},
|
||||
NotBefore: time.Now().Add(-time.Hour),
|
||||
NotAfter: time.Now().Add(24 * time.Hour),
|
||||
IsCA: true,
|
||||
BasicConstraintsValid: true,
|
||||
KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageCRLSign,
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, tmpl, tmpl, &key.PublicKey, key)
|
||||
if err != nil {
|
||||
t.Fatalf("create CA cert: %v", err)
|
||||
}
|
||||
parsed, err := x509.ParseCertificate(der)
|
||||
if err != nil {
|
||||
t.Fatalf("parse CA cert: %v", err)
|
||||
}
|
||||
return parsed, key
|
||||
}
|
||||
|
||||
// writeLeaf signs a new leaf cert with the given serial and writes it
|
||||
// plus its key to the given paths via atomic rename — the pattern
|
||||
// Kubernetes (cert-manager → Secret volume mount) produces in practice.
|
||||
func writeLeaf(t *testing.T, certPath, keyPath string, ca *x509.Certificate, caKey *ecdsa.PrivateKey, serial *big.Int) {
|
||||
t.Helper()
|
||||
leafKey, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader)
|
||||
if err != nil {
|
||||
t.Fatalf("gen leaf key: %v", err)
|
||||
}
|
||||
tmpl := &x509.Certificate{
|
||||
SerialNumber: serial,
|
||||
Subject: pkix.Name{
|
||||
CommonName: "localhost",
|
||||
},
|
||||
NotBefore: time.Now().Add(-time.Hour),
|
||||
NotAfter: time.Now().Add(24 * time.Hour),
|
||||
KeyUsage: x509.KeyUsageDigitalSignature | x509.KeyUsageKeyEncipherment,
|
||||
ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth, x509.ExtKeyUsageClientAuth},
|
||||
DNSNames: []string{"localhost"},
|
||||
IPAddresses: []net.IP{net.ParseIP("127.0.0.1"), net.ParseIP("::1")},
|
||||
}
|
||||
der, err := x509.CreateCertificate(rand.Reader, tmpl, ca, &leafKey.PublicKey, caKey)
|
||||
if err != nil {
|
||||
t.Fatalf("create leaf cert: %v", err)
|
||||
}
|
||||
|
||||
atomicWritePEM(t, certPath, "CERTIFICATE", der)
|
||||
|
||||
keyDER, err := x509.MarshalECPrivateKey(leafKey)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal leaf key: %v", err)
|
||||
}
|
||||
atomicWritePEM(t, keyPath, "EC PRIVATE KEY", keyDER)
|
||||
}
|
||||
|
||||
// atomicWritePEM writes a PEM file via tempfile-in-same-directory plus
|
||||
// rename, matching what kubelet does when it swaps the ..data symlink
|
||||
// for a renewed Secret. Ensures the reader never sees a truncated file.
|
||||
func atomicWritePEM(t *testing.T, path, blockType string, der []byte) {
|
||||
t.Helper()
|
||||
dir := filepath.Dir(path)
|
||||
tmp, err := os.CreateTemp(dir, ".tls-*")
|
||||
if err != nil {
|
||||
t.Fatalf("create tempfile: %v", err)
|
||||
}
|
||||
ok := false
|
||||
defer func() {
|
||||
if !ok {
|
||||
_ = os.Remove(tmp.Name())
|
||||
}
|
||||
}()
|
||||
if err := pem.Encode(tmp, &pem.Block{Type: blockType, Bytes: der}); err != nil {
|
||||
tmp.Close()
|
||||
t.Fatalf("pem encode: %v", err)
|
||||
}
|
||||
if err := tmp.Close(); err != nil {
|
||||
t.Fatalf("close tempfile: %v", err)
|
||||
}
|
||||
if err := os.Chmod(tmp.Name(), 0o600); err != nil {
|
||||
t.Fatalf("chmod tempfile: %v", err)
|
||||
}
|
||||
if err := os.Rename(tmp.Name(), path); err != nil {
|
||||
t.Fatalf("rename tempfile onto %s: %v", path, err)
|
||||
}
|
||||
ok = true
|
||||
}
|
||||
@@ -54,12 +54,25 @@ type Cluster struct {
|
||||
masterCmd *exec.Cmd
|
||||
volumeCmd *exec.Cmd
|
||||
|
||||
volumeDataDirs []string
|
||||
|
||||
cleanupOnce sync.Once
|
||||
}
|
||||
|
||||
// StartSingleVolumeCluster boots one master and one volume server.
|
||||
func StartSingleVolumeCluster(t testing.TB, profile matrix.Profile) *Cluster {
|
||||
return StartSingleVolumeClusterWithDataDirs(t, profile, 1)
|
||||
}
|
||||
|
||||
// StartSingleVolumeClusterWithDataDirs boots one master and one volume server
|
||||
// with dataDirCount separate data directories (passed to -dir as a comma list).
|
||||
// Each directory becomes its own DiskLocation on the volume server, letting
|
||||
// tests exercise multi-disk EC placement paths.
|
||||
func StartSingleVolumeClusterWithDataDirs(t testing.TB, profile matrix.Profile, dataDirCount int) *Cluster {
|
||||
t.Helper()
|
||||
if dataDirCount < 1 {
|
||||
t.Fatalf("dataDirCount must be >= 1, got %d", dataDirCount)
|
||||
}
|
||||
|
||||
weedBinary, err := FindOrBuildWeedBinary()
|
||||
if err != nil {
|
||||
@@ -74,8 +87,19 @@ func StartSingleVolumeCluster(t testing.TB, profile matrix.Profile) *Cluster {
|
||||
configDir := filepath.Join(baseDir, "config")
|
||||
logsDir := filepath.Join(baseDir, "logs")
|
||||
masterDataDir := filepath.Join(baseDir, "master")
|
||||
volumeDataDir := filepath.Join(baseDir, "volume")
|
||||
for _, dir := range []string{configDir, logsDir, masterDataDir, volumeDataDir} {
|
||||
volumeDataDirs := make([]string, dataDirCount)
|
||||
// Single-dir layout stays at baseDir/volume so existing fixtures
|
||||
// (CorruptDatFile etc.) that hardcode that path keep working. Only
|
||||
// multi-dir clusters get the "volumeN" layout.
|
||||
for i := 0; i < dataDirCount; i++ {
|
||||
if dataDirCount == 1 {
|
||||
volumeDataDirs[i] = filepath.Join(baseDir, "volume")
|
||||
} else {
|
||||
volumeDataDirs[i] = filepath.Join(baseDir, fmt.Sprintf("volume%d", i))
|
||||
}
|
||||
}
|
||||
setupDirs := append([]string{configDir, logsDir, masterDataDir}, volumeDataDirs...)
|
||||
for _, dir := range setupDirs {
|
||||
if mkErr := os.MkdirAll(dir, 0o755); mkErr != nil {
|
||||
t.Fatalf("create %s: %v", dir, mkErr)
|
||||
}
|
||||
@@ -85,17 +109,12 @@ func StartSingleVolumeCluster(t testing.TB, profile matrix.Profile) *Cluster {
|
||||
t.Fatalf("write security config: %v", err)
|
||||
}
|
||||
|
||||
miniPorts, err := testutil.AllocateMiniPorts(1)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate master port pair: %v", err)
|
||||
}
|
||||
masterPort := miniPorts[0]
|
||||
masterGrpcPort := masterPort + testutil.GrpcPortOffset
|
||||
|
||||
ports, err := testutil.AllocatePorts(3)
|
||||
miniPorts, ports, err := testutil.AllocatePortSet(1, 3)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate ports: %v", err)
|
||||
}
|
||||
masterPort := miniPorts[0]
|
||||
masterGrpcPort := masterPort + testutil.GrpcPortOffset
|
||||
|
||||
c := &Cluster{
|
||||
testingTB: t,
|
||||
@@ -125,11 +144,12 @@ func StartSingleVolumeCluster(t testing.TB, profile matrix.Profile) *Cluster {
|
||||
t.Fatalf("wait for master readiness: %v\nmaster log tail:\n%s", err, masterLog)
|
||||
}
|
||||
|
||||
if err = c.startVolume(volumeDataDir); err != nil {
|
||||
if err = c.startVolume(volumeDataDirs); err != nil {
|
||||
masterLog := c.tailLog("master.log")
|
||||
c.Stop()
|
||||
t.Fatalf("start volume: %v\nmaster log tail:\n%s", err, masterLog)
|
||||
}
|
||||
c.volumeDataDirs = volumeDataDirs
|
||||
if err = c.waitForHTTP(c.VolumeAdminURL() + "/status"); err != nil {
|
||||
volumeLog := c.tailLog("volume.log")
|
||||
c.Stop()
|
||||
@@ -189,12 +209,16 @@ func (c *Cluster) startMaster(dataDir string) error {
|
||||
return c.masterCmd.Start()
|
||||
}
|
||||
|
||||
func (c *Cluster) startVolume(dataDir string) error {
|
||||
func (c *Cluster) startVolume(dataDirs []string) error {
|
||||
logFile, err := os.Create(filepath.Join(c.logsDir, "volume.log"))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
maxPerDir := make([]string, len(dataDirs))
|
||||
for i := range dataDirs {
|
||||
maxPerDir[i] = "16"
|
||||
}
|
||||
args := []string{
|
||||
"-config_dir=" + c.configDir,
|
||||
"volume",
|
||||
@@ -202,8 +226,8 @@ func (c *Cluster) startVolume(dataDir string) error {
|
||||
"-port=" + strconv.Itoa(c.volumePort),
|
||||
"-port.grpc=" + strconv.Itoa(c.volumeGrpcPort),
|
||||
"-port.public=" + strconv.Itoa(c.volumePubPort),
|
||||
"-dir=" + dataDir,
|
||||
"-max=16",
|
||||
"-dir=" + strings.Join(dataDirs, ","),
|
||||
"-max=" + strings.Join(maxPerDir, ","),
|
||||
"-master=127.0.0.1:" + strconv.Itoa(c.masterPort),
|
||||
"-readMode=" + c.profile.ReadMode,
|
||||
"-concurrentUploadLimitMB=" + strconv.Itoa(c.profile.ConcurrentUploadLimitMB),
|
||||
@@ -420,3 +444,10 @@ func (c *Cluster) VolumePublicURL() string {
|
||||
func (c *Cluster) BaseDir() string {
|
||||
return c.baseDir
|
||||
}
|
||||
|
||||
// VolumeDataDirs returns the data directories the volume server was started with.
|
||||
// Index 0 corresponds to DiskLocation 0, index 1 to DiskLocation 1, and so on.
|
||||
// Tests can scan these directories to verify where files physically landed.
|
||||
func (c *Cluster) VolumeDataDirs() []string {
|
||||
return append([]string(nil), c.volumeDataDirs...)
|
||||
}
|
||||
@@ -93,22 +93,17 @@ func StartMixedVolumeCluster(t testing.TB, profile matrix.Profile, goCount, rust
|
||||
t.Fatalf("write security config: %v", err)
|
||||
}
|
||||
|
||||
miniPorts, err := testutil.AllocateMiniPorts(1)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate master port pair: %v", err)
|
||||
}
|
||||
masterPort := miniPorts[0]
|
||||
masterGrpcPort := masterPort + testutil.GrpcPortOffset
|
||||
|
||||
// 2 ports per server (admin, grpc); add 1 more when public port is split out.
|
||||
portsPerServer := 2
|
||||
if profile.SplitPublicPort {
|
||||
portsPerServer = 3
|
||||
}
|
||||
ports, err := testutil.AllocatePorts(total * portsPerServer)
|
||||
miniPorts, ports, err := testutil.AllocatePortSet(1, total*portsPerServer)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate volume ports: %v", err)
|
||||
t.Fatalf("allocate ports: %v", err)
|
||||
}
|
||||
masterPort := miniPorts[0]
|
||||
masterGrpcPort := masterPort + testutil.GrpcPortOffset
|
||||
|
||||
isRust := make([]bool, total)
|
||||
for i := goCount; i < total; i++ {
|
||||
|
||||
@@ -75,13 +75,6 @@ func StartMultiVolumeCluster(t testing.TB, profile matrix.Profile, serverCount i
|
||||
t.Fatalf("write security config: %v", err)
|
||||
}
|
||||
|
||||
miniPorts, err := testutil.AllocateMiniPorts(1)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate master port pair: %v", err)
|
||||
}
|
||||
masterPort := miniPorts[0]
|
||||
masterGrpcPort := masterPort + testutil.GrpcPortOffset
|
||||
|
||||
// Allocate ports for all volume servers (3 ports per server: admin, grpc, public)
|
||||
// If SplitPublicPort is true, we need an additional port per server
|
||||
portsPerServer := 3
|
||||
@@ -89,10 +82,12 @@ func StartMultiVolumeCluster(t testing.TB, profile matrix.Profile, serverCount i
|
||||
portsPerServer = 4
|
||||
}
|
||||
totalPorts := serverCount * portsPerServer
|
||||
ports, err := testutil.AllocatePorts(totalPorts)
|
||||
miniPorts, ports, err := testutil.AllocatePortSet(1, totalPorts)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate volume ports: %v", err)
|
||||
t.Fatalf("allocate ports: %v", err)
|
||||
}
|
||||
masterPort := miniPorts[0]
|
||||
masterGrpcPort := masterPort + testutil.GrpcPortOffset
|
||||
|
||||
c := &MultiVolumeCluster{
|
||||
testingTB: t,
|
||||
|
||||
@@ -86,13 +86,6 @@ func StartRustMultiVolumeCluster(t testing.TB, profile matrix.Profile, serverCou
|
||||
t.Fatalf("write security config: %v", err)
|
||||
}
|
||||
|
||||
miniPorts, err := testutil.AllocateMiniPorts(1)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate master port pair: %v", err)
|
||||
}
|
||||
masterPort := miniPorts[0]
|
||||
masterGrpcPort := masterPort + testutil.GrpcPortOffset
|
||||
|
||||
// Allocate ports for all volume servers (3 ports per server: admin, grpc, public)
|
||||
// If SplitPublicPort is true, we need an additional port per server
|
||||
portsPerServer := 3
|
||||
@@ -100,10 +93,12 @@ func StartRustMultiVolumeCluster(t testing.TB, profile matrix.Profile, serverCou
|
||||
portsPerServer = 4
|
||||
}
|
||||
totalPorts := serverCount * portsPerServer
|
||||
ports, err := testutil.AllocatePorts(totalPorts)
|
||||
miniPorts, ports, err := testutil.AllocatePortSet(1, totalPorts)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate volume ports: %v", err)
|
||||
t.Fatalf("allocate ports: %v", err)
|
||||
}
|
||||
masterPort := miniPorts[0]
|
||||
masterGrpcPort := masterPort + testutil.GrpcPortOffset
|
||||
|
||||
c := &RustMultiVolumeCluster{
|
||||
testingTB: t,
|
||||
|
||||
@@ -80,17 +80,12 @@ func StartRustVolumeCluster(t testing.TB, profile matrix.Profile) *RustCluster {
|
||||
t.Fatalf("write security config: %v", err)
|
||||
}
|
||||
|
||||
miniPorts, err := testutil.AllocateMiniPorts(1)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate master port pair: %v", err)
|
||||
}
|
||||
masterPort := miniPorts[0]
|
||||
masterGrpcPort := masterPort + testutil.GrpcPortOffset
|
||||
|
||||
ports, err := testutil.AllocatePorts(3)
|
||||
miniPorts, ports, err := testutil.AllocatePortSet(1, 3)
|
||||
if err != nil {
|
||||
t.Fatalf("allocate ports: %v", err)
|
||||
}
|
||||
masterPort := miniPorts[0]
|
||||
masterGrpcPort := masterPort + testutil.GrpcPortOffset
|
||||
|
||||
rc := &RustCluster{
|
||||
testingTB: t,
|
||||
|
||||
@@ -0,0 +1,178 @@
|
||||
package volume_server_grpc_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
|
||||
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
)
|
||||
|
||||
// Sends EC shards with disk_id={1, 2, 0} and verifies each lands on the
|
||||
// requested disk (0 → auto-select → disk 0 for a fresh volume).
|
||||
func TestReceiveFileEcShardHonorsDiskID(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in short mode")
|
||||
}
|
||||
|
||||
const dataDirCount = 3
|
||||
clusterHarness := framework.StartSingleVolumeClusterWithDataDirs(t, matrix.P1(), dataDirCount)
|
||||
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
|
||||
defer conn.Close()
|
||||
|
||||
dataDirs := clusterHarness.VolumeDataDirs()
|
||||
if len(dataDirs) != dataDirCount {
|
||||
t.Fatalf("expected %d data dirs, got %d: %v", dataDirCount, len(dataDirs), dataDirs)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
||||
defer cancel()
|
||||
|
||||
const volumeID = uint32(9184)
|
||||
const collection = "ec-disk-placement"
|
||||
|
||||
// DiskId=0 triggers auto-select. Since this test never calls
|
||||
// VolumeEcShardsMount, loc.FindEcVolume returns false on every disk, so
|
||||
// the "already holds shards" preference is skipped and auto-select falls
|
||||
// through to the first HDD (dir 0). If shards get mounted between uploads
|
||||
// in a future revision, the expected dir for DiskId=0 becomes the first
|
||||
// disk that already holds a shard.
|
||||
shards := []struct {
|
||||
shardID uint32
|
||||
requestedDisk uint32
|
||||
expectedDirIdx int
|
||||
}{
|
||||
{shardID: 0, requestedDisk: 1, expectedDirIdx: 1},
|
||||
{shardID: 5, requestedDisk: 2, expectedDirIdx: 2},
|
||||
{shardID: 13, requestedDisk: 0, expectedDirIdx: 0},
|
||||
}
|
||||
shardExt := func(id uint32) string { return fmt.Sprintf(".ec%02d", id) }
|
||||
|
||||
for _, s := range shards {
|
||||
payload := []byte(fmt.Sprintf("ec-shard-payload-%02d", s.shardID))
|
||||
stream, err := grpcClient.ReceiveFile(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ReceiveFile stream create for shard %d: %v", s.shardID, err)
|
||||
}
|
||||
if err = stream.Send(&volume_server_pb.ReceiveFileRequest{
|
||||
Data: &volume_server_pb.ReceiveFileRequest_Info{
|
||||
Info: &volume_server_pb.ReceiveFileInfo{
|
||||
VolumeId: volumeID,
|
||||
Ext: shardExt(s.shardID),
|
||||
Collection: collection,
|
||||
IsEcVolume: true,
|
||||
ShardId: s.shardID,
|
||||
FileSize: uint64(len(payload)),
|
||||
DiskId: s.requestedDisk,
|
||||
},
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatalf("ReceiveFile send info for shard %d: %v", s.shardID, err)
|
||||
}
|
||||
if err = stream.Send(&volume_server_pb.ReceiveFileRequest{
|
||||
Data: &volume_server_pb.ReceiveFileRequest_FileContent{FileContent: payload},
|
||||
}); err != nil {
|
||||
t.Fatalf("ReceiveFile send content for shard %d: %v", s.shardID, err)
|
||||
}
|
||||
resp, err := stream.CloseAndRecv()
|
||||
if err != nil {
|
||||
t.Fatalf("ReceiveFile close for shard %d: %v", s.shardID, err)
|
||||
}
|
||||
if resp.GetError() != "" {
|
||||
t.Fatalf("ReceiveFile shard %d error response: %s", s.shardID, resp.GetError())
|
||||
}
|
||||
if resp.GetBytesWritten() != uint64(len(payload)) {
|
||||
t.Fatalf("ReceiveFile shard %d bytes_written mismatch: got %d want %d",
|
||||
s.shardID, resp.GetBytesWritten(), len(payload))
|
||||
}
|
||||
}
|
||||
|
||||
// Scan every data dir and record which shard files live where.
|
||||
perDirShards := make(map[int][]uint32)
|
||||
for dirIdx, dir := range dataDirs {
|
||||
for _, s := range shards {
|
||||
shardPath := filepath.Join(dir, fmt.Sprintf("%s_%d%s", collection, volumeID, shardExt(s.shardID)))
|
||||
if _, err := os.Stat(shardPath); err == nil {
|
||||
perDirShards[dirIdx] = append(perDirShards[dirIdx], s.shardID)
|
||||
} else if !os.IsNotExist(err) {
|
||||
t.Fatalf("unexpected stat error for %s: %v", shardPath, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for _, s := range shards {
|
||||
found := false
|
||||
for _, got := range perDirShards[s.expectedDirIdx] {
|
||||
if got == s.shardID {
|
||||
found = true
|
||||
break
|
||||
}
|
||||
}
|
||||
if !found {
|
||||
t.Fatalf("shard %d (requestedDisk=%d) expected on dir[%d], full layout: %v",
|
||||
s.shardID, s.requestedDisk, s.expectedDirIdx, perDirShards)
|
||||
}
|
||||
for dirIdx, ids := range perDirShards {
|
||||
if dirIdx == s.expectedDirIdx {
|
||||
continue
|
||||
}
|
||||
for _, id := range ids {
|
||||
if id == s.shardID {
|
||||
t.Fatalf("shard %d leaked onto dir[%d]: full layout: %v", s.shardID, dirIdx, perDirShards)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
t.Logf("disk_id honored: shard placement = %v", perDirShards)
|
||||
}
|
||||
|
||||
func TestReceiveFileEcShardRejectsInvalidDiskID(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in short mode")
|
||||
}
|
||||
|
||||
const dataDirCount = 2
|
||||
clusterHarness := framework.StartSingleVolumeClusterWithDataDirs(t, matrix.P1(), dataDirCount)
|
||||
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
|
||||
defer conn.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
const volumeID = uint32(91840)
|
||||
const collection = "ec-invalid-disk"
|
||||
payload := []byte("invalid-disk-id-payload")
|
||||
|
||||
stream, err := grpcClient.ReceiveFile(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ReceiveFile stream create: %v", err)
|
||||
}
|
||||
if err = stream.Send(&volume_server_pb.ReceiveFileRequest{
|
||||
Data: &volume_server_pb.ReceiveFileRequest_Info{
|
||||
Info: &volume_server_pb.ReceiveFileInfo{
|
||||
VolumeId: volumeID,
|
||||
Ext: ".ec00",
|
||||
Collection: collection,
|
||||
IsEcVolume: true,
|
||||
ShardId: 0,
|
||||
FileSize: uint64(len(payload)),
|
||||
DiskId: 99,
|
||||
},
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatalf("ReceiveFile send info: %v", err)
|
||||
}
|
||||
resp, err := stream.CloseAndRecv()
|
||||
if err != nil {
|
||||
t.Fatalf("ReceiveFile close: %v", err)
|
||||
}
|
||||
if resp.GetError() == "" {
|
||||
t.Fatalf("expected invalid disk_id rejection, got success response: %+v", resp)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,186 @@
|
||||
package volume_server_grpc_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/test/volume_server/framework"
|
||||
"github.com/seaweedfs/seaweedfs/test/volume_server/matrix"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/volume_server_pb"
|
||||
)
|
||||
|
||||
func TestReceiveFileRejectsOverwriteOfMountedEcShard(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in short mode")
|
||||
}
|
||||
|
||||
clusterHarness := framework.StartVolumeCluster(t, matrix.P1())
|
||||
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
|
||||
defer conn.Close()
|
||||
|
||||
const volumeID = uint32(91841)
|
||||
framework.AllocateVolume(t, grpcClient, volumeID, "")
|
||||
|
||||
httpClient := framework.NewHTTPClient()
|
||||
fid := framework.NewFileID(volumeID, 918401, 0x9184CAFE)
|
||||
uploadResp := framework.UploadBytes(t, httpClient, clusterHarness.VolumeAdminURL(), fid,
|
||||
[]byte("ec-receive-overwrite-content-for-issue-9184-repro"))
|
||||
_ = framework.ReadAllAndClose(t, uploadResp)
|
||||
if uploadResp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("upload expected 201, got %d", uploadResp.StatusCode)
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
if _, err := grpcClient.VolumeEcShardsGenerate(ctx, &volume_server_pb.VolumeEcShardsGenerateRequest{
|
||||
VolumeId: volumeID,
|
||||
Collection: "",
|
||||
}); err != nil {
|
||||
t.Fatalf("VolumeEcShardsGenerate: %v", err)
|
||||
}
|
||||
|
||||
if _, err := grpcClient.VolumeEcShardsMount(ctx, &volume_server_pb.VolumeEcShardsMountRequest{
|
||||
VolumeId: volumeID,
|
||||
Collection: "",
|
||||
ShardIds: []uint32{0},
|
||||
}); err != nil {
|
||||
t.Fatalf("VolumeEcShardsMount: %v", err)
|
||||
}
|
||||
|
||||
dataDir := filepath.Join(clusterHarness.BaseDir(), "volume")
|
||||
shardPath := filepath.Join(dataDir, fmt.Sprintf("%d.ec00", volumeID))
|
||||
origInfo, err := os.Stat(shardPath)
|
||||
if err != nil {
|
||||
t.Fatalf("stat mounted shard %s: %v", shardPath, err)
|
||||
}
|
||||
origSize := origInfo.Size()
|
||||
if origSize == 0 {
|
||||
t.Fatalf("mounted shard %s unexpectedly empty", shardPath)
|
||||
}
|
||||
|
||||
readStream, err := grpcClient.VolumeEcShardRead(ctx, &volume_server_pb.VolumeEcShardReadRequest{
|
||||
VolumeId: volumeID,
|
||||
ShardId: 0,
|
||||
Offset: 0,
|
||||
Size: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("VolumeEcShardRead (pre): %v", err)
|
||||
}
|
||||
if _, err := readStream.Recv(); err != nil {
|
||||
t.Fatalf("VolumeEcShardRead Recv (pre): %v", err)
|
||||
}
|
||||
|
||||
overwritePayload := []byte("bug-9184-overwrite")
|
||||
receiveStream, err := grpcClient.ReceiveFile(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ReceiveFile stream create: %v", err)
|
||||
}
|
||||
if err = receiveStream.Send(&volume_server_pb.ReceiveFileRequest{
|
||||
Data: &volume_server_pb.ReceiveFileRequest_Info{
|
||||
Info: &volume_server_pb.ReceiveFileInfo{
|
||||
VolumeId: volumeID,
|
||||
Ext: ".ec00",
|
||||
Collection: "",
|
||||
IsEcVolume: true,
|
||||
ShardId: 0,
|
||||
FileSize: uint64(len(overwritePayload)),
|
||||
},
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatalf("ReceiveFile send info: %v", err)
|
||||
}
|
||||
resp, err := receiveStream.CloseAndRecv()
|
||||
if err != nil {
|
||||
t.Logf("ReceiveFile rejected at stream level: %v", err)
|
||||
} else {
|
||||
if resp.GetError() == "" {
|
||||
t.Fatalf("expected ReceiveFile to reject overwrite of mounted shard, got success: %+v", resp)
|
||||
}
|
||||
if !strings.Contains(resp.GetError(), "mounted") {
|
||||
t.Fatalf("expected error to mention mounted; got: %s", resp.GetError())
|
||||
}
|
||||
}
|
||||
|
||||
afterInfo, err := os.Stat(shardPath)
|
||||
if err != nil {
|
||||
t.Fatalf("stat shard after rejected overwrite: %v", err)
|
||||
}
|
||||
if afterInfo.Size() != origSize {
|
||||
t.Fatalf("shard %s was modified despite rejection: size was %d, now %d",
|
||||
shardPath, origSize, afterInfo.Size())
|
||||
}
|
||||
|
||||
postStream, err := grpcClient.VolumeEcShardRead(ctx, &volume_server_pb.VolumeEcShardReadRequest{
|
||||
VolumeId: volumeID,
|
||||
ShardId: 0,
|
||||
Offset: 0,
|
||||
Size: 1,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("VolumeEcShardRead (post): %v", err)
|
||||
}
|
||||
if _, err := postStream.Recv(); err != nil {
|
||||
t.Fatalf("VolumeEcShardRead Recv (post): %v", err)
|
||||
}
|
||||
|
||||
t.Logf("ReceiveFile correctly refused overwrite; mounted shard intact at %d bytes", afterInfo.Size())
|
||||
}
|
||||
|
||||
func TestReceiveFileAllowsEcShardWhenNoMount(t *testing.T) {
|
||||
if testing.Short() {
|
||||
t.Skip("skipping integration test in short mode")
|
||||
}
|
||||
|
||||
clusterHarness := framework.StartVolumeCluster(t, matrix.P1())
|
||||
conn, grpcClient := framework.DialVolumeServer(t, clusterHarness.VolumeGRPCAddress())
|
||||
defer conn.Close()
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
const volumeID = uint32(91843)
|
||||
const collection = "ec-receive-no-mount"
|
||||
payload := []byte("ok-to-receive-not-mounted")
|
||||
|
||||
stream, err := grpcClient.ReceiveFile(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("ReceiveFile stream create: %v", err)
|
||||
}
|
||||
if err = stream.Send(&volume_server_pb.ReceiveFileRequest{
|
||||
Data: &volume_server_pb.ReceiveFileRequest_Info{
|
||||
Info: &volume_server_pb.ReceiveFileInfo{
|
||||
VolumeId: volumeID,
|
||||
Ext: ".ec00",
|
||||
Collection: collection,
|
||||
IsEcVolume: true,
|
||||
ShardId: 0,
|
||||
FileSize: uint64(len(payload)),
|
||||
},
|
||||
},
|
||||
}); err != nil {
|
||||
t.Fatalf("ReceiveFile send info: %v", err)
|
||||
}
|
||||
if err = stream.Send(&volume_server_pb.ReceiveFileRequest{
|
||||
Data: &volume_server_pb.ReceiveFileRequest_FileContent{FileContent: payload},
|
||||
}); err != nil {
|
||||
t.Fatalf("ReceiveFile send content: %v", err)
|
||||
}
|
||||
resp, err := stream.CloseAndRecv()
|
||||
if err != nil {
|
||||
t.Fatalf("ReceiveFile close: %v", err)
|
||||
}
|
||||
if resp.GetError() != "" {
|
||||
t.Fatalf("expected success on unmounted volume, got error: %s", resp.GetError())
|
||||
}
|
||||
if resp.GetBytesWritten() != uint64(len(payload)) {
|
||||
t.Fatalf("bytes_written mismatch: got %d want %d", resp.GetBytesWritten(), len(payload))
|
||||
}
|
||||
}
|
||||
@@ -10,11 +10,10 @@ import (
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/master_pb"
|
||||
util_http "github.com/seaweedfs/seaweedfs/weed/util/http"
|
||||
)
|
||||
|
||||
var dirStatusClient = &http.Client{
|
||||
Timeout: 5 * time.Second,
|
||||
}
|
||||
const dirStatusTimeout = 5 * time.Second
|
||||
|
||||
// GetClusterTopology returns the current cluster topology with caching
|
||||
func (s *AdminServer) GetClusterTopology() (*ClusterTopology, error) {
|
||||
@@ -50,8 +49,16 @@ func (s *AdminServer) fetchPublicUrlMap() map[string]string {
|
||||
return nil
|
||||
}
|
||||
|
||||
ctx, cancel := context.WithTimeout(context.Background(), dirStatusTimeout)
|
||||
defer cancel()
|
||||
|
||||
url := fmt.Sprintf("http://%s/dir/status", currentMaster.ToHttpAddress())
|
||||
resp, err := dirStatusClient.Get(url)
|
||||
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
|
||||
if err != nil {
|
||||
glog.V(1).Infof("Failed to build /dir/status request for %s: %v", currentMaster, err)
|
||||
return nil
|
||||
}
|
||||
resp, err := util_http.GetGlobalHttpClient().Do(req)
|
||||
if err != nil {
|
||||
glog.V(1).Infof("Failed to fetch /dir/status from %s: %v", currentMaster, err)
|
||||
return nil
|
||||
|
||||
@@ -1061,7 +1061,7 @@ func s3TablesErrorStatus(err error) int {
|
||||
return http.StatusNotFound
|
||||
case s3tables.ErrCodeAccessDenied:
|
||||
return http.StatusForbidden
|
||||
case s3tables.ErrCodeBucketAlreadyExists, s3tables.ErrCodeNamespaceAlreadyExists, s3tables.ErrCodeTableAlreadyExists, s3tables.ErrCodeConflict:
|
||||
case s3tables.ErrCodeBucketAlreadyExists, s3tables.ErrCodeNamespaceAlreadyExists, s3tables.ErrCodeTableAlreadyExists, s3tables.ErrCodeBucketNotEmpty, s3tables.ErrCodeNamespaceNotEmpty, s3tables.ErrCodeConflict:
|
||||
return http.StatusConflict
|
||||
}
|
||||
}
|
||||
|
||||
@@ -247,21 +247,29 @@ func (s *AdminServer) CreateAccessKey(username string, req *CreateAccessKeyReque
|
||||
req = &CreateAccessKeyRequest{}
|
||||
}
|
||||
|
||||
// Validate provided keys
|
||||
if req.AccessKey != "" && (len(req.AccessKey) < 4 || len(req.AccessKey) > 128) {
|
||||
return nil, fmt.Errorf("access key must be between 4 and 128 characters: %w", ErrInvalidInput)
|
||||
// Validate provided keys (shared with the IAM API and embedded IAM paths).
|
||||
if req.AccessKey != "" {
|
||||
if err := iam.ValidateCallerSuppliedAccessKeyId(req.AccessKey); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", err.Error(), ErrInvalidInput)
|
||||
}
|
||||
}
|
||||
if req.SecretKey != "" && (len(req.SecretKey) < 8 || len(req.SecretKey) > 128) {
|
||||
return nil, fmt.Errorf("secret key must be between 8 and 128 characters: %w", ErrInvalidInput)
|
||||
if req.SecretKey != "" {
|
||||
if err := iam.ValidateCallerSuppliedSecretAccessKey(req.SecretKey); err != nil {
|
||||
return nil, fmt.Errorf("%s: %w", err.Error(), ErrInvalidInput)
|
||||
}
|
||||
}
|
||||
// Enforce the both-or-none rule to match the IAM API and embedded IAM
|
||||
// paths — silently generating the missing half lets a caller end up
|
||||
// with a credential they did not fully choose.
|
||||
if (req.AccessKey != "") != (req.SecretKey != "") {
|
||||
return nil, fmt.Errorf("access key and secret key must be supplied together: %w", ErrInvalidInput)
|
||||
}
|
||||
|
||||
// Use provided keys or generate new ones
|
||||
accessKey := req.AccessKey
|
||||
secretKey := req.SecretKey
|
||||
if accessKey == "" {
|
||||
accessKey = generateAccessKey()
|
||||
}
|
||||
secretKey := req.SecretKey
|
||||
if secretKey == "" {
|
||||
secretKey = generateSecretKey()
|
||||
}
|
||||
|
||||
|
||||
Binary file not shown.
|
Before Width: | Height: | Size: 5.4 KiB After Width: | Height: | Size: 6.6 KiB |
@@ -23,6 +23,15 @@ function getCSRFToken() {
|
||||
return tokenMeta.getAttribute('content') || '';
|
||||
}
|
||||
|
||||
function s3tWriteHeaders(extra) {
|
||||
const headers = Object.assign({}, extra || {});
|
||||
const csrfToken = getCSRFToken();
|
||||
if (csrfToken) {
|
||||
headers['X-CSRF-Token'] = csrfToken;
|
||||
}
|
||||
return headers;
|
||||
}
|
||||
|
||||
/**
|
||||
* Initialize S3 Tables Buckets Page
|
||||
*/
|
||||
@@ -104,7 +113,7 @@ function initS3TablesBuckets() {
|
||||
try {
|
||||
const response = await fetch(s3tBasePath('/api/s3tables/buckets'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: s3tWriteHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
const data = await response.json();
|
||||
@@ -133,7 +142,7 @@ function initS3TablesBuckets() {
|
||||
try {
|
||||
const response = await fetch(s3tBasePath('/api/s3tables/bucket-policy'), {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: s3tWriteHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify({ bucket_arn: bucketArn, policy: policy })
|
||||
});
|
||||
const data = await response.json();
|
||||
@@ -239,7 +248,7 @@ function initS3TablesTables() {
|
||||
try {
|
||||
const response = await fetch(s3tBasePath('/api/s3tables/tables'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: s3tWriteHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
const data = await response.json();
|
||||
@@ -267,7 +276,7 @@ function initS3TablesTables() {
|
||||
try {
|
||||
const response = await fetch(s3tBasePath('/api/s3tables/table-policy'), {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: s3tWriteHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify({ bucket_arn: dataBucketArn, namespace: dataNamespace, name: document.getElementById('s3tablesTablePolicyName').value, policy: policy })
|
||||
});
|
||||
const data = await response.json();
|
||||
@@ -306,10 +315,6 @@ function initIcebergNamespaces() {
|
||||
if (!container) return;
|
||||
const bucketArn = container.dataset.bucketArn || '';
|
||||
const catalogName = container.dataset.catalogName || '';
|
||||
const csrfTokenInput = document.getElementById('icebergNamespaceCsrfToken');
|
||||
if (csrfTokenInput) {
|
||||
csrfTokenInput.value = getCSRFToken();
|
||||
}
|
||||
|
||||
const namespaceInput = document.getElementById('icebergNamespaceName');
|
||||
if (namespaceInput) {
|
||||
@@ -330,14 +335,9 @@ function initIcebergNamespaces() {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const csrfToken = csrfTokenInput ? csrfTokenInput.value : getCSRFToken();
|
||||
const headers = { 'Content-Type': 'application/json' };
|
||||
if (csrfToken) {
|
||||
headers['X-CSRF-Token'] = csrfToken;
|
||||
}
|
||||
const response = await fetch(s3tBasePath('/api/s3tables/namespaces'), {
|
||||
method: 'POST',
|
||||
headers: headers,
|
||||
headers: s3tWriteHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify({ bucket_arn: bucketArn, name: name })
|
||||
});
|
||||
const data = await response.json();
|
||||
@@ -433,10 +433,6 @@ function initIcebergTables() {
|
||||
if (!container) return;
|
||||
const bucketArn = container.dataset.bucketArn || '';
|
||||
const namespace = container.dataset.namespace || '';
|
||||
const csrfTokenInput = document.getElementById('icebergTableCsrfToken');
|
||||
if (csrfTokenInput) {
|
||||
csrfTokenInput.value = getCSRFToken();
|
||||
}
|
||||
|
||||
initIcebergDeleteModal();
|
||||
|
||||
@@ -476,14 +472,9 @@ function initIcebergTables() {
|
||||
payload.metadata = metadata;
|
||||
}
|
||||
try {
|
||||
const csrfToken = csrfTokenInput ? csrfTokenInput.value : getCSRFToken();
|
||||
const headers = { 'Content-Type': 'application/json' };
|
||||
if (csrfToken) {
|
||||
headers['X-CSRF-Token'] = csrfToken;
|
||||
}
|
||||
const response = await fetch(s3tBasePath('/api/s3tables/tables'), {
|
||||
method: 'POST',
|
||||
headers: headers,
|
||||
headers: s3tWriteHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify(payload)
|
||||
});
|
||||
const data = await response.json();
|
||||
@@ -530,7 +521,7 @@ async function deleteS3TablesBucket() {
|
||||
const bucketArn = document.getElementById('deleteS3TablesBucketModal').dataset.bucketArn;
|
||||
if (!bucketArn) return;
|
||||
try {
|
||||
const response = await fetch(s3tBasePath(`/api/s3tables/buckets?bucket=${encodeURIComponent(bucketArn)}`), { method: 'DELETE' });
|
||||
const response = await fetch(s3tBasePath(`/api/s3tables/buckets?bucket=${encodeURIComponent(bucketArn)}`), { method: 'DELETE', headers: s3tWriteHeaders() });
|
||||
const data = await response.json();
|
||||
if (!response.ok) {
|
||||
alert(data.error || 'Failed to delete bucket');
|
||||
@@ -561,7 +552,7 @@ async function deleteS3TablesBucketPolicy() {
|
||||
const bucketArn = document.getElementById('s3tablesBucketPolicyArn').value;
|
||||
if (!bucketArn) return;
|
||||
try {
|
||||
const response = await fetch(s3tBasePath(`/api/s3tables/bucket-policy?bucket=${encodeURIComponent(bucketArn)}`), { method: 'DELETE' });
|
||||
const response = await fetch(s3tBasePath(`/api/s3tables/bucket-policy?bucket=${encodeURIComponent(bucketArn)}`), { method: 'DELETE', headers: s3tWriteHeaders() });
|
||||
const data = await response.json();
|
||||
if (!response.ok) {
|
||||
alert(data.error || 'Failed to delete policy');
|
||||
@@ -590,7 +581,7 @@ async function deleteS3TablesTable() {
|
||||
query.set('version', versionToken);
|
||||
}
|
||||
try {
|
||||
const response = await fetch(s3tBasePath(`/api/s3tables/tables?${query.toString()}`), { method: 'DELETE' });
|
||||
const response = await fetch(s3tBasePath(`/api/s3tables/tables?${query.toString()}`), { method: 'DELETE', headers: s3tWriteHeaders() });
|
||||
const data = await response.json();
|
||||
if (!response.ok) {
|
||||
alert(data.error || 'Failed to delete table');
|
||||
@@ -621,12 +612,7 @@ async function deleteIcebergTable() {
|
||||
query.set('version', versionToken);
|
||||
}
|
||||
try {
|
||||
const csrfToken = getCSRFToken();
|
||||
const requestOptions = { method: 'DELETE' };
|
||||
if (csrfToken) {
|
||||
requestOptions.headers = { 'X-CSRF-Token': csrfToken };
|
||||
}
|
||||
const response = await fetch(s3tBasePath(`/api/s3tables/tables?${query.toString()}`), requestOptions);
|
||||
const response = await fetch(s3tBasePath(`/api/s3tables/tables?${query.toString()}`), { method: 'DELETE', headers: s3tWriteHeaders() });
|
||||
const data = await response.json();
|
||||
if (!response.ok) {
|
||||
alert(data.error || 'Failed to drop table');
|
||||
@@ -665,7 +651,7 @@ async function deleteS3TablesTablePolicy() {
|
||||
const dataNamespace = dataContainer.dataset.namespace || '';
|
||||
const query = new URLSearchParams({ bucket: dataBucketArn, namespace: dataNamespace, name: document.getElementById('s3tablesTablePolicyName').value });
|
||||
try {
|
||||
const response = await fetch(s3tBasePath(`/api/s3tables/table-policy?${query.toString()}`), { method: 'DELETE' });
|
||||
const response = await fetch(s3tBasePath(`/api/s3tables/table-policy?${query.toString()}`), { method: 'DELETE', headers: s3tWriteHeaders() });
|
||||
const data = await response.json();
|
||||
if (!response.ok) {
|
||||
alert(data.error || 'Failed to delete policy');
|
||||
@@ -872,7 +858,7 @@ async function updateS3TablesTags(resourceArn, tags) {
|
||||
try {
|
||||
const response = await fetch(s3tBasePath('/api/s3tables/tags'), {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: s3tWriteHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify({ resource_arn: resourceArn, tags: tags })
|
||||
});
|
||||
const data = await response.json();
|
||||
@@ -899,7 +885,7 @@ async function deleteS3TablesTags() {
|
||||
try {
|
||||
const response = await fetch(s3tBasePath('/api/s3tables/tags'), {
|
||||
method: 'DELETE',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
headers: s3tWriteHeaders({ 'Content-Type': 'application/json' }),
|
||||
body: JSON.stringify({ resource_arn: resourceArn, tag_keys: tagKeys })
|
||||
});
|
||||
const data = await response.json();
|
||||
|
||||
@@ -261,11 +261,11 @@ func TestTargetSelectionScenarios(t *testing.T) {
|
||||
expectedTargets: 4, // All 4 disks available
|
||||
},
|
||||
{
|
||||
name: "Vacuum task - avoid conflicting disks",
|
||||
name: "Vacuum task - cross-type tasks do not block per disk",
|
||||
topology: createTopologyWithConflicts(),
|
||||
taskType: TaskTypeVacuum,
|
||||
excludeNode: "",
|
||||
expectedTargets: 1, // Only 1 disk without conflicts (conflicts exclude more disks)
|
||||
expectedTargets: 4, // All 4 disks available; per-volume safety is enforced by HasAnyTask
|
||||
},
|
||||
}
|
||||
|
||||
@@ -279,8 +279,6 @@ func TestTargetSelectionScenarios(t *testing.T) {
|
||||
for _, disk := range availableDisks {
|
||||
assert.NotEqual(t, tt.excludeNode, disk.NodeID,
|
||||
"Available disk should not be on excluded node")
|
||||
|
||||
assert.Less(t, disk.LoadCount, 2, "Disk load should be less than 2")
|
||||
}
|
||||
})
|
||||
}
|
||||
@@ -353,12 +351,10 @@ func TestDiskLoadCalculation(t *testing.T) {
|
||||
assert.Equal(t, 1, targetDisk.LoadCount)
|
||||
}
|
||||
|
||||
// TestTaskConflictDetection tests task conflict detection
|
||||
func TestTaskConflictDetection(t *testing.T) {
|
||||
func TestCrossTypeTasksDoNotBlockPerDisk(t *testing.T) {
|
||||
topology := NewActiveTopology(10)
|
||||
topology.UpdateTopology(createSampleTopology())
|
||||
|
||||
// Add a balance task
|
||||
err := topology.AddPendingTask(TaskSpec{
|
||||
TaskID: "balance1",
|
||||
TaskType: TaskTypeBalance,
|
||||
@@ -371,13 +367,10 @@ func TestTaskConflictDetection(t *testing.T) {
|
||||
{ServerID: "10.0.0.2:8080", DiskID: 1},
|
||||
},
|
||||
})
|
||||
assert.NoError(t, err, "Should add balance task successfully")
|
||||
topology.AssignTask("balance1")
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, topology.AssignTask("balance1"))
|
||||
|
||||
// Try to get available disks for vacuum (conflicts with balance)
|
||||
availableDisks := topology.GetAvailableDisks(TaskTypeVacuum, "")
|
||||
|
||||
// Source disk should not be available due to conflict
|
||||
sourceDiskAvailable := false
|
||||
for _, disk := range availableDisks {
|
||||
if disk.NodeID == "10.0.0.1:8080" && disk.DiskID == 0 {
|
||||
@@ -385,7 +378,34 @@ func TestTaskConflictDetection(t *testing.T) {
|
||||
break
|
||||
}
|
||||
}
|
||||
assert.False(t, sourceDiskAvailable, "Source disk should not be available due to task conflict")
|
||||
assert.True(t, sourceDiskAvailable,
|
||||
"Source disk should remain available for an unrelated task type")
|
||||
}
|
||||
|
||||
// Regression for #9147: a 4-disk cluster with one in-flight balance task must
|
||||
// still expose all 4 disks to EC placement so MinTotalDisks can be satisfied.
|
||||
func TestECPlanningNotBlockedByUnrelatedBalance(t *testing.T) {
|
||||
topology := NewActiveTopology(10)
|
||||
topology.UpdateTopology(createSampleTopology()) // 2 nodes x 2 disks
|
||||
|
||||
err := topology.AddPendingTask(TaskSpec{
|
||||
TaskID: "balance1",
|
||||
TaskType: TaskTypeBalance,
|
||||
VolumeID: 42,
|
||||
VolumeSize: 1024 * 1024 * 1024,
|
||||
Sources: []TaskSourceSpec{
|
||||
{ServerID: "10.0.0.1:8080", DiskID: 0},
|
||||
},
|
||||
Destinations: []TaskDestinationSpec{
|
||||
{ServerID: "10.0.0.2:8080", DiskID: 0},
|
||||
},
|
||||
})
|
||||
require.NoError(t, err)
|
||||
require.NoError(t, topology.AssignTask("balance1"))
|
||||
|
||||
ecCandidates := topology.GetDisksWithEffectiveCapacity(TaskTypeErasureCoding, "", 0)
|
||||
assert.Equal(t, 4, len(ecCandidates),
|
||||
"EC must still see all 4 disks even with an unrelated in-flight balance")
|
||||
}
|
||||
|
||||
// TestPublicInterfaces tests the public interface methods
|
||||
|
||||
@@ -236,21 +236,13 @@ func (at *ActiveTopology) getPlanningCapacityUnsafe(disk *activeDisk) StorageSlo
|
||||
}
|
||||
}
|
||||
|
||||
// isDiskAvailableForPlanning checks if disk can accept new tasks considering pending load
|
||||
// isDiskAvailableForPlanning checks if disk can accept new tasks considering
|
||||
// pending load. See isDiskAvailable for the cross-type policy.
|
||||
func (at *ActiveTopology) isDiskAvailableForPlanning(disk *activeDisk, taskType TaskType) bool {
|
||||
// Check total load including pending tasks
|
||||
totalLoad := len(disk.pendingTasks) + len(disk.assignedTasks)
|
||||
if MaxTotalTaskLoadPerDisk > 0 && totalLoad >= MaxTotalTaskLoadPerDisk {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check for conflicting task types in active tasks only
|
||||
for _, task := range disk.assignedTasks {
|
||||
if at.areTaskTypesConflicting(task.TaskType, taskType) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
@@ -64,44 +64,17 @@ func (at *ActiveTopology) assignTaskToDisk(task *taskState) {
|
||||
}
|
||||
}
|
||||
|
||||
// isDiskAvailable checks if a disk can accept new tasks
|
||||
// isDiskAvailable checks if a disk can accept new tasks. Per-volume safety is
|
||||
// enforced by HasAnyTask at detection time, so cross-type tasks on the same
|
||||
// disk are intentionally not considered conflicting (see #9147).
|
||||
func (at *ActiveTopology) isDiskAvailable(disk *activeDisk, taskType TaskType) bool {
|
||||
// Check if disk has too many pending and active tasks
|
||||
activeLoad := len(disk.pendingTasks) + len(disk.assignedTasks)
|
||||
if MaxConcurrentTasksPerDisk > 0 && activeLoad >= MaxConcurrentTasksPerDisk {
|
||||
return false
|
||||
}
|
||||
|
||||
// Check for conflicting task types
|
||||
for _, task := range disk.assignedTasks {
|
||||
if at.areTaskTypesConflicting(task.TaskType, taskType) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
return true
|
||||
}
|
||||
|
||||
// areTaskTypesConflicting checks if two task types conflict
|
||||
func (at *ActiveTopology) areTaskTypesConflicting(existing, new TaskType) bool {
|
||||
// Examples of conflicting task types
|
||||
conflictMap := map[TaskType][]TaskType{
|
||||
TaskTypeVacuum: {TaskTypeBalance, TaskTypeErasureCoding},
|
||||
TaskTypeBalance: {TaskTypeVacuum, TaskTypeErasureCoding},
|
||||
TaskTypeErasureCoding: {TaskTypeVacuum, TaskTypeBalance},
|
||||
}
|
||||
|
||||
if conflicts, exists := conflictMap[existing]; exists {
|
||||
for _, conflictType := range conflicts {
|
||||
if conflictType == new {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
// cleanupRecentTasks removes old recent tasks
|
||||
func (at *ActiveTopology) cleanupRecentTasks() {
|
||||
cutoff := time.Now().Add(-time.Duration(at.recentTaskWindowSeconds) * time.Second)
|
||||
|
||||
@@ -231,7 +231,6 @@ templ Groups(data dash.GroupsPageData) {
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<script src="/static/js/iam-utils.js"></script>
|
||||
<script>
|
||||
// Groups page JavaScript
|
||||
let currentGroupName = '';
|
||||
@@ -243,7 +242,7 @@ templ Groups(data dash.GroupsPageData) {
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const response = await fetch('/api/groups', {
|
||||
const response = await fetch(basePath('/api/groups'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ name: name })
|
||||
@@ -269,7 +268,7 @@ templ Groups(data dash.GroupsPageData) {
|
||||
|
||||
async function refreshGroupDetails(requestedName) {
|
||||
try {
|
||||
const response = await fetch('/api/groups/' + encodeURIComponent(requestedName));
|
||||
const response = await fetch(basePath('/api/groups/' + encodeURIComponent(requestedName)));
|
||||
if (!response.ok) throw new Error('Failed to fetch group');
|
||||
if (requestedName !== currentGroupName) return; // stale response
|
||||
const group = await response.json();
|
||||
@@ -339,7 +338,7 @@ templ Groups(data dash.GroupsPageData) {
|
||||
const username = document.getElementById('addMemberSelect').value;
|
||||
if (!username) return;
|
||||
try {
|
||||
const response = await fetch('/api/groups/' + encodeURIComponent(currentGroupName) + '/members', {
|
||||
const response = await fetch(basePath('/api/groups/' + encodeURIComponent(currentGroupName) + '/members'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username: username })
|
||||
@@ -358,7 +357,7 @@ templ Groups(data dash.GroupsPageData) {
|
||||
|
||||
async function removeMember(username) {
|
||||
try {
|
||||
const response = await fetch('/api/groups/' + encodeURIComponent(currentGroupName) + '/members/' + encodeURIComponent(username), {
|
||||
const response = await fetch(basePath('/api/groups/' + encodeURIComponent(currentGroupName) + '/members/' + encodeURIComponent(username)), {
|
||||
method: 'DELETE'
|
||||
});
|
||||
if (response.ok) {
|
||||
@@ -377,7 +376,7 @@ templ Groups(data dash.GroupsPageData) {
|
||||
const policyName = document.getElementById('attachPolicySelect').value;
|
||||
if (!policyName) return;
|
||||
try {
|
||||
const response = await fetch('/api/groups/' + encodeURIComponent(currentGroupName) + '/policies', {
|
||||
const response = await fetch(basePath('/api/groups/' + encodeURIComponent(currentGroupName) + '/policies'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ policy_name: policyName })
|
||||
@@ -396,7 +395,7 @@ templ Groups(data dash.GroupsPageData) {
|
||||
|
||||
async function detachPolicy(policyName) {
|
||||
try {
|
||||
const response = await fetch('/api/groups/' + encodeURIComponent(currentGroupName) + '/policies/' + encodeURIComponent(policyName), {
|
||||
const response = await fetch(basePath('/api/groups/' + encodeURIComponent(currentGroupName) + '/policies/' + encodeURIComponent(policyName)), {
|
||||
method: 'DELETE'
|
||||
});
|
||||
if (response.ok) {
|
||||
@@ -414,7 +413,7 @@ templ Groups(data dash.GroupsPageData) {
|
||||
async function toggleGroupStatus() {
|
||||
const enabled = document.getElementById('groupEnabledSwitch').checked;
|
||||
try {
|
||||
const response = await fetch('/api/groups/' + encodeURIComponent(currentGroupName) + '/status', {
|
||||
const response = await fetch(basePath('/api/groups/' + encodeURIComponent(currentGroupName) + '/status'), {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ enabled: enabled })
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Code generated by templ - DO NOT EDIT.
|
||||
|
||||
// templ: version: v0.3.977
|
||||
// templ: version: v0.3.1001
|
||||
package app
|
||||
|
||||
//lint:file-ignore SA4006 This context is only used if a nested component is present.
|
||||
@@ -41,7 +41,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalGroups))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 38, Col: 72}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 38, Col: 72}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -54,7 +54,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.ActiveGroups))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 57, Col: 73}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 57, Col: 73}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -82,7 +82,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(group.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 96, Col: 63}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 96, Col: 63}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -95,7 +95,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var5 string
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", group.MemberCount))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 99, Col: 109}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 99, Col: 109}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -108,7 +108,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", group.PolicyCount))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 102, Col: 114}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 102, Col: 114}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -136,7 +136,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(group.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 113, Col: 79}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 113, Col: 79}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -149,7 +149,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs("View group " + group.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 115, Col: 90}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 115, Col: 90}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -162,7 +162,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs("View " + group.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 116, Col: 79}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 116, Col: 79}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -175,7 +175,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(group.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 120, Col: 79}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 120, Col: 79}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -188,7 +188,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var11 string
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs("Delete group " + group.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 122, Col: 92}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 122, Col: 92}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -201,7 +201,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var12 string
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs("Delete " + group.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 123, Col: 81}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 123, Col: 81}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -229,7 +229,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var13 string
|
||||
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(user)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 189, Col: 67}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 189, Col: 67}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -242,7 +242,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var14 string
|
||||
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(user)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 189, Col: 74}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 189, Col: 74}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -265,7 +265,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var15 string
|
||||
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(policy)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 206, Col: 69}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 206, Col: 69}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -278,7 +278,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
var templ_7745c5c3_Var16 string
|
||||
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(policy)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/groups.templ`, Line: 206, Col: 78}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/groups.templ`, Line: 206, Col: 78}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -289,7 +289,7 @@ func Groups(data dash.GroupsPageData) templ.Component {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "</select> <button class=\"btn btn-outline-primary\" type=\"button\" onclick=\"attachPolicyToGroup()\"><i class=\"fas fa-plus\"></i> Attach</button></div></div><div id=\"policiesList\"></div></div><!-- Settings Tab --><div class=\"tab-pane fade\" id=\"settingsPane\" role=\"tabpanel\"><div class=\"form-check form-switch mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"groupEnabledSwitch\" checked onchange=\"toggleGroupStatus()\"> <label class=\"form-check-label\" for=\"groupEnabledSwitch\">Group Enabled</label></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button></div></div></div></div></div><script src=\"/static/js/iam-utils.js\"></script><script>\n // Groups page JavaScript\n let currentGroupName = '';\n\n async function createGroup() {\n const name = document.getElementById('groupName').value.trim();\n if (!name) {\n showAlert('Group name is required', 'error');\n return;\n }\n try {\n const response = await fetch('/api/groups', {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ name: name })\n });\n if (response.ok) {\n showAlert('Group created successfully', 'success');\n setTimeout(() => window.location.reload(), 1000);\n } else {\n const error = await response.json().catch(() => ({}));\n showAlert('Failed to create group: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n showAlert('Failed to create group: ' + error.message, 'error');\n }\n }\n\n async function viewGroup(name) {\n currentGroupName = name;\n document.getElementById('viewGroupTitle').textContent = 'Group: ' + name;\n await refreshGroupDetails(name);\n new bootstrap.Modal(document.getElementById('viewGroupModal')).show();\n }\n\n async function refreshGroupDetails(requestedName) {\n try {\n const response = await fetch('/api/groups/' + encodeURIComponent(requestedName));\n if (!response.ok) throw new Error('Failed to fetch group');\n if (requestedName !== currentGroupName) return; // stale response\n const group = await response.json();\n\n // Render members using DOM APIs to prevent XSS\n const membersList = document.getElementById('membersList');\n membersList.innerHTML = '';\n const membersTable = document.createElement('table');\n membersTable.className = 'table table-sm';\n const membersTbody = document.createElement('tbody');\n if (group.members && group.members.length > 0) {\n for (const member of group.members) {\n const tr = membersTbody.insertRow();\n const td1 = tr.insertCell();\n td1.textContent = member;\n const td2 = tr.insertCell();\n const btn = document.createElement('button');\n btn.className = 'btn btn-sm btn-outline-danger';\n btn.onclick = () => removeMember(member);\n btn.innerHTML = '<i class=\"fas fa-times\"></i>';\n td2.appendChild(btn);\n }\n } else {\n const tr = membersTbody.insertRow();\n const td = tr.insertCell();\n td.className = 'text-muted';\n td.textContent = 'No members';\n }\n membersTable.appendChild(membersTbody);\n membersList.appendChild(membersTable);\n\n // Render policies using DOM APIs to prevent XSS\n const policiesList = document.getElementById('policiesList');\n policiesList.innerHTML = '';\n const policiesTable = document.createElement('table');\n policiesTable.className = 'table table-sm';\n const policiesTbody = document.createElement('tbody');\n if (group.policy_names && group.policy_names.length > 0) {\n for (const policy of group.policy_names) {\n const tr = policiesTbody.insertRow();\n const td1 = tr.insertCell();\n td1.textContent = policy;\n const td2 = tr.insertCell();\n const btn = document.createElement('button');\n btn.classNLine truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 28, "</select> <button class=\"btn btn-outline-primary\" type=\"button\" onclick=\"attachPolicyToGroup()\"><i class=\"fas fa-plus\"></i> Attach</button></div></div><div id=\"policiesList\"></div></div><!-- Settings Tab --><div class=\"tab-pane fade\" id=\"settingsPane\" role=\"tabpanel\"><div class=\"form-check form-switch mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"groupEnabledSwitch\" checked onchange=\"toggleGroupStatus()\"> <label class=\"form-check-label\" for=\"groupEnabledSwitch\">Group Enabled</label></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button></div></div></div></div></div><script>\n // Groups page JavaScript\n let currentGroupName = '';\n\n async function createGroup() {\n const name = document.getElementById('groupName').value.trim();\n if (!name) {\n showAlert('Group name is required', 'error');\n return;\n }\n try {\n const response = await fetch(basePath('/api/groups'), {\n method: 'POST',\n headers: { 'Content-Type': 'application/json' },\n body: JSON.stringify({ name: name })\n });\n if (response.ok) {\n showAlert('Group created successfully', 'success');\n setTimeout(() => window.location.reload(), 1000);\n } else {\n const error = await response.json().catch(() => ({}));\n showAlert('Failed to create group: ' + (error.error || 'Unknown error'), 'error');\n }\n } catch (error) {\n showAlert('Failed to create group: ' + error.message, 'error');\n }\n }\n\n async function viewGroup(name) {\n currentGroupName = name;\n document.getElementById('viewGroupTitle').textContent = 'Group: ' + name;\n await refreshGroupDetails(name);\n new bootstrap.Modal(document.getElementById('viewGroupModal')).show();\n }\n\n async function refreshGroupDetails(requestedName) {\n try {\n const response = await fetch(basePath('/api/groups/' + encodeURIComponent(requestedName)));\n if (!response.ok) throw new Error('Failed to fetch group');\n if (requestedName !== currentGroupName) return; // stale response\n const group = await response.json();\n\n // Render members using DOM APIs to prevent XSS\n const membersList = document.getElementById('membersList');\n membersList.innerHTML = '';\n const membersTable = document.createElement('table');\n membersTable.className = 'table table-sm';\n const membersTbody = document.createElement('tbody');\n if (group.members && group.members.length > 0) {\n for (const member of group.members) {\n const tr = membersTbody.insertRow();\n const td1 = tr.insertCell();\n td1.textContent = member;\n const td2 = tr.insertCell();\n const btn = document.createElement('button');\n btn.className = 'btn btn-sm btn-outline-danger';\n btn.onclick = () => removeMember(member);\n btn.innerHTML = '<i class=\"fas fa-times\"></i>';\n td2.appendChild(btn);\n }\n } else {\n const tr = membersTbody.insertRow();\n const td = tr.insertCell();\n td.className = 'text-muted';\n td.textContent = 'No members';\n }\n membersTable.appendChild(membersTbody);\n membersList.appendChild(membersTable);\n\n // Render policies using DOM APIs to prevent XSS\n const policiesList = document.getElementById('policiesList');\n policiesList.innerHTML = '';\n const policiesTable = document.createElement('table');\n policiesTable.className = 'table table-sm';\n const policiesTbody = document.createElement('tbody');\n if (group.policy_names && group.policy_names.length > 0) {\n for (const policy of group.policy_names) {\n const tr = policiesTbody.insertRow();\n const td1 = tr.insertCell();\n td1.textContent = policy;\n const td2 = tr.insertCell();\n const btn = document.createElement('button');\n btn.className = 'btn btn-sm btn-outlineLine truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -504,6 +504,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
const STATUS_ACTIVE = 'Active';
|
||||
const STATUS_INACTIVE = 'Inactive';
|
||||
|
||||
// Use basePath() from admin.js for -urlPrefix; it is loaded in the layout footer before DOMContentLoaded fires.
|
||||
document.addEventListener('DOMContentLoaded', function() {
|
||||
|
||||
// Event delegation for user action buttons
|
||||
@@ -591,7 +592,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
// Load buckets
|
||||
async function loadBuckets() {
|
||||
try {
|
||||
const response = await fetch('/api/s3/buckets');
|
||||
const response = await fetch(basePath('/api/s3/buckets'));
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
availableBuckets = (data.buckets || []).map(bucket => ({ name: bucket.name, type: 's3' }));
|
||||
@@ -605,7 +606,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
availableBuckets = [];
|
||||
}
|
||||
try {
|
||||
const response = await fetch('/api/s3tables/buckets');
|
||||
const response = await fetch(basePath('/api/s3tables/buckets'));
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
const tableBuckets = (data.buckets || data.tableBuckets || []).map(bucket => ({ name: bucket.name, type: 's3tables' }));
|
||||
@@ -623,7 +624,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
// Load policies
|
||||
async function loadPolicies() {
|
||||
try {
|
||||
const response = await fetch('/api/object-store/policies');
|
||||
const response = await fetch(basePath('/api/object-store/policies'));
|
||||
if (response.ok) {
|
||||
const data = await response.json();
|
||||
const policies = data.policies || [];
|
||||
@@ -910,7 +911,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
async function showUserDetails(username) {
|
||||
try {
|
||||
const encodedUsername = encodeURIComponent(username);
|
||||
const response = await fetch(`/api/users/${encodedUsername}`);
|
||||
const response = await fetch(basePath(`/api/users/${encodedUsername}`));
|
||||
if (response.ok) {
|
||||
const user = await response.json();
|
||||
document.getElementById('userDetailsContent').innerHTML = createUserDetailsContent(user);
|
||||
@@ -929,7 +930,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
async function editUser(username) {
|
||||
try {
|
||||
const encodedUsername = encodeURIComponent(username);
|
||||
const response = await fetch(`/api/users/${encodedUsername}`);
|
||||
const response = await fetch(basePath(`/api/users/${encodedUsername}`));
|
||||
if (response.ok) {
|
||||
const user = await response.json();
|
||||
|
||||
@@ -1008,7 +1009,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
async function manageAccessKeys(username) {
|
||||
try {
|
||||
const encodedUsername = encodeURIComponent(username);
|
||||
const response = await fetch(`/api/users/${encodedUsername}`);
|
||||
const response = await fetch(basePath(`/api/users/${encodedUsername}`));
|
||||
if (response.ok) {
|
||||
const user = await response.json();
|
||||
document.getElementById('accessKeysUsername').textContent = username;
|
||||
@@ -1029,7 +1030,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
showDeleteConfirm(username, async function() {
|
||||
try {
|
||||
const encodedUsername = encodeURIComponent(username);
|
||||
const response = await fetch(`/api/users/${encodedUsername}`, {
|
||||
const response = await fetch(basePath(`/api/users/${encodedUsername}`), {
|
||||
method: 'DELETE'
|
||||
});
|
||||
|
||||
@@ -1074,7 +1075,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
};
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/users', {
|
||||
const response = await fetch(basePath('/api/users'), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -1118,13 +1119,13 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
|
||||
try {
|
||||
// Fetch all groups
|
||||
const groupsResp = await fetch('/api/groups');
|
||||
const groupsResp = await fetch(basePath('/api/groups'));
|
||||
if (!groupsResp.ok) return;
|
||||
const groupsData = await groupsResp.json();
|
||||
const allGroups = groupsData.groups || [];
|
||||
|
||||
// Fetch user details to get current groups
|
||||
const userResp = await fetch(`/api/users/${encodeURIComponent(username)}`);
|
||||
const userResp = await fetch(basePath(`/api/users/${encodeURIComponent(username)}`));
|
||||
if (!userResp.ok) return;
|
||||
const user = await userResp.json();
|
||||
const userGroups = user.groups || [];
|
||||
@@ -1172,7 +1173,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
if (!groupName) return;
|
||||
|
||||
try {
|
||||
const response = await fetch(`/api/groups/${encodeURIComponent(groupName)}/members`, {
|
||||
const response = await fetch(basePath(`/api/groups/${encodeURIComponent(groupName)}/members`), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ username: username })
|
||||
@@ -1192,7 +1193,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
async function removeUserFromGroupInEdit(groupName) {
|
||||
const username = document.getElementById('editUsername').value;
|
||||
try {
|
||||
const response = await fetch(`/api/groups/${encodeURIComponent(groupName)}/members/${encodeURIComponent(username)}`, {
|
||||
const response = await fetch(basePath(`/api/groups/${encodeURIComponent(groupName)}/members/${encodeURIComponent(username)}`), {
|
||||
method: 'DELETE'
|
||||
});
|
||||
if (response.ok) {
|
||||
@@ -1237,7 +1238,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
|
||||
try {
|
||||
const encodedUsername = encodeURIComponent(username);
|
||||
const response = await fetch(`/api/users/${encodedUsername}`, {
|
||||
const response = await fetch(basePath(`/api/users/${encodedUsername}`), {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -1374,7 +1375,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
async function refreshAccessKeysList(username) {
|
||||
try {
|
||||
const encodedUsername = encodeURIComponent(username);
|
||||
const response = await fetch(`/api/users/${encodedUsername}`);
|
||||
const response = await fetch(basePath(`/api/users/${encodedUsername}`));
|
||||
if (response.ok) {
|
||||
const user = await response.json();
|
||||
document.getElementById('accessKeysContent').innerHTML = createAccessKeysContent(user);
|
||||
@@ -1387,7 +1388,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
// Update access key status
|
||||
async function updateAccessKeyStatus(username, accessKey, status) {
|
||||
try {
|
||||
const response = await fetch(`/api/users/${encodeURIComponent(username)}/access-keys/${encodeURIComponent(accessKey)}/status`, {
|
||||
const response = await fetch(basePath(`/api/users/${encodeURIComponent(username)}/access-keys/${encodeURIComponent(accessKey)}/status`), {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -1473,7 +1474,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
|
||||
try {
|
||||
const encodedUsername = encodeURIComponent(username);
|
||||
const response = await fetch(`/api/users/${encodedUsername}/access-keys`, {
|
||||
const response = await fetch(basePath(`/api/users/${encodedUsername}/access-keys`), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -1514,7 +1515,7 @@ templ ObjectStoreUsers(data dash.ObjectStoreUsersData) {
|
||||
try {
|
||||
const encodedUsername = encodeURIComponent(username);
|
||||
const encodedAccessKey = encodeURIComponent(accessKey);
|
||||
const response = await fetch(`/api/users/${encodedUsername}/access-keys/${encodedAccessKey}`, {
|
||||
const response = await fetch(basePath(`/api/users/${encodedUsername}/access-keys/${encodedAccessKey}`), {
|
||||
method: 'DELETE'
|
||||
});
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Code generated by templ - DO NOT EDIT.
|
||||
|
||||
// templ: version: v0.3.977
|
||||
// templ: version: v0.3.1001
|
||||
package app
|
||||
|
||||
//lint:file-ignore SA4006 This context is only used if a nested component is present.
|
||||
@@ -41,7 +41,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalUsers))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 38, Col: 71}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 38, Col: 71}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -54,7 +54,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", len(data.Users)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 58, Col: 71}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 58, Col: 71}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -67,7 +67,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("15:04"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 78, Col: 69}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 78, Col: 69}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -85,7 +85,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
var templ_7745c5c3_Var5 string
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(user.Username)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 127, Col: 74}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 127, Col: 74}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -108,7 +108,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(user.Email)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 133, Col: 59}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 133, Col: 59}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -121,7 +121,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(user.AccessKey)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 135, Col: 88}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 135, Col: 88}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -134,7 +134,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(user.Username)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 140, Col: 121}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 140, Col: 121}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -152,7 +152,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(user.Username)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 145, Col: 117}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 145, Col: 117}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -171,7 +171,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(user.Username)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 151, Col: 126}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 151, Col: 126}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -190,7 +190,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
var templ_7745c5c3_Var11 string
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(user.Username)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 157, Col: 119}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 157, Col: 119}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -219,7 +219,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
var templ_7745c5c3_Var12 string
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/object_store_users.templ`, Line: 189, Col: 81}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/object_store_users.templ`, Line: 189, Col: 81}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -240,7 +240,7 @@ func ObjectStoreUsers(data dash.ObjectStoreUsersData) templ.Component {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "</div><div class=\"mb-3\"><label for=\"email\" class=\"form-label\">Email</label> <input type=\"email\" class=\"form-control\" id=\"email\" name=\"email\"></div><div class=\"mb-3\"><label for=\"actions\" class=\"form-label\">Permissions</label> <select multiple class=\"form-control\" id=\"actions\" name=\"actions\" size=\"10\"><option value=\"Admin\">Admin (Full Access)</option> <option value=\"Read\">Read</option> <option value=\"Write\">Write</option> <option value=\"List\">List</option> <option value=\"Tagging\">Tagging</option> <optgroup label=\"Object Lock Permissions\"><option value=\"BypassGovernanceRetention\">Bypass Governance Retention</option> <option value=\"GetObjectRetention\">Get Object Retention</option> <option value=\"PutObjectRetention\">Put Object Retention</option> <option value=\"GetObjectLegalHold\">Get Object Legal Hold</option> <option value=\"PutObjectLegalHold\">Put Object Legal Hold</option> <option value=\"GetBucketObjectLockConfiguration\">Get Bucket Object Lock Configuration</option> <option value=\"PutBucketObjectLockConfiguration\">Put Bucket Object Lock Configuration</option></optgroup> <optgroup label=\"S3 Tables Permissions\"><option value=\"S3TablesAdmin\">S3 Tables Admin (Full Access)</option> <option value=\"CreateTableBucket\">Create Table Bucket</option> <option value=\"GetTableBucket\">Get Table Bucket</option> <option value=\"ListTableBuckets\">List Table Buckets</option> <option value=\"DeleteTableBucket\">Delete Table Bucket</option> <option value=\"PutTableBucketPolicy\">Put Table Bucket Policy</option> <option value=\"GetTableBucketPolicy\">Get Table Bucket Policy</option> <option value=\"DeleteTableBucketPolicy\">Delete Table Bucket Policy</option> <option value=\"CreateNamespace\">Create Namespace</option> <option value=\"GetNamespace\">Get Namespace</option> <option value=\"ListNamespaces\">List Namespaces</option> <option value=\"DeleteNamespace\">Delete Namespace</option> <option value=\"CreateTable\">Create Table</option> <option value=\"GetTable\">Get Table</option> <option value=\"ListTables\">List Tables</option> <option value=\"DeleteTable\">Delete Table</option> <option value=\"PutTablePolicy\">Put Table Policy</option> <option value=\"GetTablePolicy\">Get Table Policy</option> <option value=\"DeleteTablePolicy\">Delete Table Policy</option> <option value=\"TagResource\">Tag Resource</option> <option value=\"ListTagsForResource\">List Tags</option> <option value=\"UntagResource\">Untag Resource</option></optgroup></select> <small class=\"form-text text-muted\">Hold Ctrl/Cmd to select multiple permissions</small></div><div class=\"mb-3\"><label class=\"form-label\">Bucket Scope</label> <small class=\"form-text text-muted d-block mb-2\">Apply selected permissions to specific buckets or all buckets</small><div class=\"form-check mb-2\"><input class=\"form-check-input\" type=\"radio\" name=\"bucketScope\" id=\"allBuckets\" value=\"all\" checked onchange=\"toggleBucketList()\"> <label class=\"form-check-label\" for=\"allBuckets\">All Buckets</label></div><div class=\"form-check mb-2\"><input class=\"form-check-input\" type=\"radio\" name=\"bucketScope\" id=\"specificBuckets\" value=\"specific\" onchange=\"toggleBucketList()\"> <label class=\"form-check-label\" for=\"specificBuckets\">Specific Buckets</label></div><div id=\"bucketSelectionList\" class=\"mt-2\" style=\"display: none;\"><select multiple class=\"form-select\" id=\"selectedBuckets\" size=\"5\"><!-- Options loaded dynamically --></select> <small class=\"form-text text-muted\">Hold Ctrl/Cmd to select multiple buckets</small></div></div><div class=\"mb-3\"><label for=\"policies\" class=\"form-label\">Attached Policies</label> <select multiple class=\"form-control\" id=\"policies\" name=\"policies\" size=\"5\"><!-- Options loaded dynamically --></select> <small class=\"form-text text-muted\">Hold Ctrl/Cmd to select multiple policies</small></div><div class=\"mb-3 form-check\"><input type=\"checkbox\" class=\"form-check-input\" id=\"generateKey\" name=\"generateKey\" checked> <label class=\"form-check-label\" for=\"generateKey\">Generate access key automatically</label></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"handleCreateUser()\">Create User</button></div></div></div></div><!-- Edit User Modal --><div class=\"modal fade\" id=\"editUserModal\" tabindex=\"-1\" role=\"dialog\"><div class=\"modal-dialog\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\"><i class=\"fas fa-user-edit me-2\"></i>Edit User</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\"><form id=\"editUserForm\"><input type=\"hidden\" id=\"editUsername\" name=\"username\"><div class=\"mb-3\"Line truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 24, "</div><div class=\"mb-3\"><label for=\"email\" class=\"form-label\">Email</label> <input type=\"email\" class=\"form-control\" id=\"email\" name=\"email\"></div><div class=\"mb-3\"><label for=\"actions\" class=\"form-label\">Permissions</label> <select multiple class=\"form-control\" id=\"actions\" name=\"actions\" size=\"10\"><option value=\"Admin\">Admin (Full Access)</option> <option value=\"Read\">Read</option> <option value=\"Write\">Write</option> <option value=\"List\">List</option> <option value=\"Tagging\">Tagging</option> <optgroup label=\"Object Lock Permissions\"><option value=\"BypassGovernanceRetention\">Bypass Governance Retention</option> <option value=\"GetObjectRetention\">Get Object Retention</option> <option value=\"PutObjectRetention\">Put Object Retention</option> <option value=\"GetObjectLegalHold\">Get Object Legal Hold</option> <option value=\"PutObjectLegalHold\">Put Object Legal Hold</option> <option value=\"GetBucketObjectLockConfiguration\">Get Bucket Object Lock Configuration</option> <option value=\"PutBucketObjectLockConfiguration\">Put Bucket Object Lock Configuration</option></optgroup> <optgroup label=\"S3 Tables Permissions\"><option value=\"S3TablesAdmin\">S3 Tables Admin (Full Access)</option> <option value=\"CreateTableBucket\">Create Table Bucket</option> <option value=\"GetTableBucket\">Get Table Bucket</option> <option value=\"ListTableBuckets\">List Table Buckets</option> <option value=\"DeleteTableBucket\">Delete Table Bucket</option> <option value=\"PutTableBucketPolicy\">Put Table Bucket Policy</option> <option value=\"GetTableBucketPolicy\">Get Table Bucket Policy</option> <option value=\"DeleteTableBucketPolicy\">Delete Table Bucket Policy</option> <option value=\"CreateNamespace\">Create Namespace</option> <option value=\"GetNamespace\">Get Namespace</option> <option value=\"ListNamespaces\">List Namespaces</option> <option value=\"DeleteNamespace\">Delete Namespace</option> <option value=\"CreateTable\">Create Table</option> <option value=\"GetTable\">Get Table</option> <option value=\"ListTables\">List Tables</option> <option value=\"DeleteTable\">Delete Table</option> <option value=\"PutTablePolicy\">Put Table Policy</option> <option value=\"GetTablePolicy\">Get Table Policy</option> <option value=\"DeleteTablePolicy\">Delete Table Policy</option> <option value=\"TagResource\">Tag Resource</option> <option value=\"ListTagsForResource\">List Tags</option> <option value=\"UntagResource\">Untag Resource</option></optgroup></select> <small class=\"form-text text-muted\">Hold Ctrl/Cmd to select multiple permissions</small></div><div class=\"mb-3\"><label class=\"form-label\">Bucket Scope</label> <small class=\"form-text text-muted d-block mb-2\">Apply selected permissions to specific buckets or all buckets</small><div class=\"form-check mb-2\"><input class=\"form-check-input\" type=\"radio\" name=\"bucketScope\" id=\"allBuckets\" value=\"all\" checked onchange=\"toggleBucketList()\"> <label class=\"form-check-label\" for=\"allBuckets\">All Buckets</label></div><div class=\"form-check mb-2\"><input class=\"form-check-input\" type=\"radio\" name=\"bucketScope\" id=\"specificBuckets\" value=\"specific\" onchange=\"toggleBucketList()\"> <label class=\"form-check-label\" for=\"specificBuckets\">Specific Buckets</label></div><div id=\"bucketSelectionList\" class=\"mt-2\" style=\"display: none;\"><select multiple class=\"form-select\" id=\"selectedBuckets\" size=\"5\"><!-- Options loaded dynamically --></select> <small class=\"form-text text-muted\">Hold Ctrl/Cmd to select multiple buckets</small></div></div><div class=\"mb-3\"><label for=\"policies\" class=\"form-label\">Attached Policies</label> <select multiple class=\"form-control\" id=\"policies\" name=\"policies\" size=\"5\"><!-- Options loaded dynamically --></select> <small class=\"form-text text-muted\">Hold Ctrl/Cmd to select multiple policies</small></div><div class=\"mb-3 form-check\"><input type=\"checkbox\" class=\"form-check-input\" id=\"generateKey\" name=\"generateKey\" checked> <label class=\"form-check-label\" for=\"generateKey\">Generate access key automatically</label></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"handleCreateUser()\">Create User</button></div></div></div></div><!-- Edit User Modal --><div class=\"modal fade\" id=\"editUserModal\" tabindex=\"-1\" role=\"dialog\"><div class=\"modal-dialog\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\"><i class=\"fas fa-user-edit me-2\"></i>Edit User</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\"><form id=\"editUserForm\"><input type=\"hidden\" id=\"editUsername\" name=\"username\"><div class=\"mb-3\"Line truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -368,7 +368,7 @@ templ Policies(data dash.PoliciesData) {
|
||||
document: policyDocument
|
||||
};
|
||||
|
||||
fetch('/api/object-store/policies', {
|
||||
fetch(basePath('/api/object-store/policies'), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -408,7 +408,7 @@ templ Policies(data dash.PoliciesData) {
|
||||
`;
|
||||
|
||||
// Fetch policy data
|
||||
fetch('/api/object-store/policies/' + encodeURIComponent(policyName))
|
||||
fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)))
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error('Policy not found');
|
||||
@@ -494,7 +494,7 @@ templ Policies(data dash.PoliciesData) {
|
||||
document.getElementById('editPolicyDocument').value = 'Loading...';
|
||||
|
||||
// Fetch policy data
|
||||
fetch('/api/object-store/policies/' + encodeURIComponent(policyName))
|
||||
fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)))
|
||||
.then(response => {
|
||||
if (!response.ok) {
|
||||
throw new Error('Policy not found');
|
||||
@@ -534,7 +534,7 @@ templ Policies(data dash.PoliciesData) {
|
||||
document: policyDocument
|
||||
};
|
||||
|
||||
fetch('/api/object-store/policies/' + encodeURIComponent(policyName), {
|
||||
fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)), {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -636,7 +636,7 @@ templ Policies(data dash.PoliciesData) {
|
||||
|
||||
function deletePolicy(policyName) {
|
||||
showDeleteConfirm(policyName, function() {
|
||||
fetch('/api/object-store/policies/' + encodeURIComponent(policyName), {
|
||||
fetch(basePath('/api/object-store/policies/' + encodeURIComponent(policyName)), {
|
||||
method: 'DELETE'
|
||||
})
|
||||
.then(response => response.json())
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Code generated by templ - DO NOT EDIT.
|
||||
|
||||
// templ: version: v0.3.977
|
||||
// templ: version: v0.3.1001
|
||||
package app
|
||||
|
||||
//lint:file-ignore SA4006 This context is only used if a nested component is present.
|
||||
@@ -41,7 +41,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalPolicies))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 34, Col: 74}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 34, Col: 74}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -54,7 +54,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalPolicies))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 54, Col: 74}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 54, Col: 74}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -67,7 +67,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("15:04"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 74, Col: 69}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 74, Col: 69}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -85,7 +85,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var5 string
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 123, Col: 68}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 123, Col: 68}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -98,7 +98,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Document.Version)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 126, Col: 100}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 126, Col: 100}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -111,7 +111,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d statements", len(policy.Document.Statement)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 129, Col: 142}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 129, Col: 142}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -124,7 +124,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(policy.CreatedAt.Format("2006-01-02 15:04"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 132, Col: 118}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 132, Col: 118}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -137,7 +137,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(policy.UpdatedAt.Format("2006-01-02 15:04"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 135, Col: 118}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 135, Col: 118}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -150,7 +150,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 139, Col: 168}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 139, Col: 168}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -163,7 +163,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var11 string
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 142, Col: 171}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 142, Col: 171}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -176,7 +176,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
var templ_7745c5c3_Var12 string
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(policy.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/policies.templ`, Line: 145, Col: 174}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/policies.templ`, Line: 145, Col: 174}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -193,7 +193,7 @@ func Policies(data dash.PoliciesData) templ.Component {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</tbody></table></div></div></div></div></div></div><!-- Create Policy Modal --><div class=\"modal fade\" id=\"createPolicyModal\" tabindex=\"-1\" aria-labelledby=\"createPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createPolicyModalLabel\"><i class=\"fas fa-shield-alt me-2\"></i>Create IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"createPolicyForm\"><div class=\"mb-3\"><label for=\"policyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"policyName\" name=\"name\" required placeholder=\"e.g., S3ReadOnlyPolicy\"><div class=\"form-text\">Enter a unique name for this policy (alphanumeric and underscores only)</div></div><div class=\"mb-3\"><label for=\"policyDocument\" class=\"form-label\">Policy Document</label> <textarea class=\"form-control\" id=\"policyDocument\" name=\"document\" rows=\"15\" required placeholder=\"Enter IAM policy JSON document...\"></textarea><div class=\"form-text\">Enter the policy document in AWS IAM JSON format</div></div><div class=\"mb-3\"><div class=\"row\"><div class=\"col-md-6\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" onclick=\"insertSamplePolicy()\"><i class=\"fas fa-file-alt me-1\"></i>Use Sample Policy</button></div><div class=\"col-md-6 text-end\"><button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" onclick=\"validatePolicyDocument()\"><i class=\"fas fa-check me-1\"></i>Validate JSON</button></div></div></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"createPolicy()\"><i class=\"fas fa-plus me-1\"></i>Create Policy</button></div></div></div></div><!-- View Policy Modal --><div class=\"modal fade\" id=\"viewPolicyModal\" tabindex=\"-1\" aria-labelledby=\"viewPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"viewPolicyModalLabel\"><i class=\"fas fa-eye me-2\"></i>View IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><div id=\"viewPolicyContent\"><div class=\"text-center\"><div class=\"spinner-border\" role=\"status\"><span class=\"visually-hidden\">Loading...</span></div><p class=\"mt-2\">Loading policy...</p></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button> <button type=\"button\" class=\"btn btn-primary\" id=\"editFromViewBtn\"><i class=\"fas fa-edit me-1\"></i>Edit Policy</button></div></div></div></div><!-- Edit Policy Modal --><div class=\"modal fade\" id=\"editPolicyModal\" tabindex=\"-1\" aria-labelledby=\"editPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"editPolicyModalLabel\"><i class=\"fas fa-edit me-2\"></i>Edit IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"editPolicyForm\"><div class=\"mb-3\"><label for=\"editPolicyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"editPolicyName\" name=\"name\" readonly><div class=\"form-text\">Policy name cannot be changed</div></div><div class=\"mb-3\"><label for=\"editPolicyDocument\" class=\"form-label\">Policy Document</label> <textarea class=\"form-control\" id=\"editPolicyDocument\" name=\"document\" rows=\"15\" required></textarea><div class=\"form-text\">Edit the policy document in AWS IAM JSON format</div></div><div class=\"mb-3\"><div class=\"row\"><div class=\"col-md-6\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" onclick=\"insertSamplePolicyEdit()\"><i class=\"fas fa-file-alt me-1\"></i>Reset to Sample</button></div><div class=\"col-md-6 text-end\"><button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" onclick=\"validateEditPolicyDocument()\"><i class=\"fas fa-check me-1\"></i>Validate JSON</button></div></div></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"updatePolicy()\"><i class=\"fas fa-save me-1\"></i>Save Changes</button></div></div></div></div><!-- JavaScript for Policy Management --><script>\n // Current policy being viewed/edited\n let currentPolicy = null;\n \n // Event listeners for policy actions\n document.adLine truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 15, "</tbody></table></div></div></div></div></div></div><!-- Create Policy Modal --><div class=\"modal fade\" id=\"createPolicyModal\" tabindex=\"-1\" aria-labelledby=\"createPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createPolicyModalLabel\"><i class=\"fas fa-shield-alt me-2\"></i>Create IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"createPolicyForm\"><div class=\"mb-3\"><label for=\"policyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"policyName\" name=\"name\" required placeholder=\"e.g., S3ReadOnlyPolicy\"><div class=\"form-text\">Enter a unique name for this policy (alphanumeric and underscores only)</div></div><div class=\"mb-3\"><label for=\"policyDocument\" class=\"form-label\">Policy Document</label> <textarea class=\"form-control\" id=\"policyDocument\" name=\"document\" rows=\"15\" required placeholder=\"Enter IAM policy JSON document...\"></textarea><div class=\"form-text\">Enter the policy document in AWS IAM JSON format</div></div><div class=\"mb-3\"><div class=\"row\"><div class=\"col-md-6\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" onclick=\"insertSamplePolicy()\"><i class=\"fas fa-file-alt me-1\"></i>Use Sample Policy</button></div><div class=\"col-md-6 text-end\"><button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" onclick=\"validatePolicyDocument()\"><i class=\"fas fa-check me-1\"></i>Validate JSON</button></div></div></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"createPolicy()\"><i class=\"fas fa-plus me-1\"></i>Create Policy</button></div></div></div></div><!-- View Policy Modal --><div class=\"modal fade\" id=\"viewPolicyModal\" tabindex=\"-1\" aria-labelledby=\"viewPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"viewPolicyModalLabel\"><i class=\"fas fa-eye me-2\"></i>View IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><div id=\"viewPolicyContent\"><div class=\"text-center\"><div class=\"spinner-border\" role=\"status\"><span class=\"visually-hidden\">Loading...</span></div><p class=\"mt-2\">Loading policy...</p></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button> <button type=\"button\" class=\"btn btn-primary\" id=\"editFromViewBtn\"><i class=\"fas fa-edit me-1\"></i>Edit Policy</button></div></div></div></div><!-- Edit Policy Modal --><div class=\"modal fade\" id=\"editPolicyModal\" tabindex=\"-1\" aria-labelledby=\"editPolicyModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog modal-lg\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"editPolicyModalLabel\"><i class=\"fas fa-edit me-2\"></i>Edit IAM Policy</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><div class=\"modal-body\"><form id=\"editPolicyForm\"><div class=\"mb-3\"><label for=\"editPolicyName\" class=\"form-label\">Policy Name</label> <input type=\"text\" class=\"form-control\" id=\"editPolicyName\" name=\"name\" readonly><div class=\"form-text\">Policy name cannot be changed</div></div><div class=\"mb-3\"><label for=\"editPolicyDocument\" class=\"form-label\">Policy Document</label> <textarea class=\"form-control\" id=\"editPolicyDocument\" name=\"document\" rows=\"15\" required></textarea><div class=\"form-text\">Edit the policy document in AWS IAM JSON format</div></div><div class=\"mb-3\"><div class=\"row\"><div class=\"col-md-6\"><button type=\"button\" class=\"btn btn-outline-info btn-sm\" onclick=\"insertSamplePolicyEdit()\"><i class=\"fas fa-file-alt me-1\"></i>Reset to Sample</button></div><div class=\"col-md-6 text-end\"><button type=\"button\" class=\"btn btn-outline-secondary btn-sm\" onclick=\"validateEditPolicyDocument()\"><i class=\"fas fa-check me-1\"></i>Validate JSON</button></div></div></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"updatePolicy()\"><i class=\"fas fa-save me-1\"></i>Save Changes</button></div></div></div></div><!-- JavaScript for Policy Management --><script>\n // Current policy being viewed/edited\n let currentPolicy = null;\n \n // Event listeners for policy actions\n document.adLine truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -712,7 +712,7 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
// Only fetch if not already populated
|
||||
if (ownerSelect.options.length <= 1) {
|
||||
try {
|
||||
const response = await fetch('/api/users');
|
||||
const response = await fetch(basePath('/api/users'));
|
||||
const data = await response.json();
|
||||
const users = data.users || [];
|
||||
|
||||
@@ -756,7 +756,7 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
return;
|
||||
}
|
||||
|
||||
fetch('/api/s3/buckets', {
|
||||
fetch(basePath('/api/s3/buckets'), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -846,7 +846,7 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
quota_enabled: enabled
|
||||
};
|
||||
|
||||
fetch(`/api/s3/buckets/${bucketName}/quota`, {
|
||||
fetch(basePath(`/api/s3/buckets/${bucketName}/quota`), {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -897,7 +897,7 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
// Fetch users if not cached
|
||||
try {
|
||||
if (!cachedUsers) {
|
||||
const response = await fetch('/api/users');
|
||||
const response = await fetch(basePath('/api/users'));
|
||||
const data = await response.json();
|
||||
cachedUsers = data.users || [];
|
||||
}
|
||||
@@ -941,7 +941,7 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
const owner = document.getElementById('bucketOwnerSelect').value;
|
||||
const data = { owner: owner };
|
||||
|
||||
fetch(`/api/s3/buckets/${bucketName}/owner`, {
|
||||
fetch(basePath(`/api/s3/buckets/${bucketName}/owner`), {
|
||||
method: 'PUT',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
@@ -988,7 +988,7 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
detailsModalInstance.show();
|
||||
|
||||
// Fetch bucket details
|
||||
fetch('/api/s3/buckets/' + bucketName)
|
||||
fetch(basePath('/api/s3/buckets/' + bucketName))
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.error) {
|
||||
@@ -1017,7 +1017,7 @@ templ S3Buckets(data dash.S3BucketsData) {
|
||||
const bucketName = document.getElementById('deleteBucketModal').dataset.bucketName;
|
||||
if (!bucketName) return;
|
||||
|
||||
fetch(`/api/s3/buckets/${bucketName}`, {
|
||||
fetch(basePath(`/api/s3/buckets/${bucketName}`), {
|
||||
method: 'DELETE'
|
||||
})
|
||||
.then(response => response.json())
|
||||
@@ -1172,7 +1172,7 @@ function displayBucketDetails(data) {
|
||||
}
|
||||
|
||||
// Fetch all buckets from the API (not just the current page)
|
||||
fetch('/api/s3/buckets')
|
||||
fetch(basePath('/api/s3/buckets'))
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
if (data.error) {
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Code generated by templ - DO NOT EDIT.
|
||||
|
||||
// templ: version: v0.3.977
|
||||
// templ: version: v0.3.1001
|
||||
package app
|
||||
|
||||
//lint:file-ignore SA4006 This context is only used if a nested component is present.
|
||||
@@ -81,7 +81,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalBuckets))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 42, Col: 73}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 42, Col: 73}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -94,7 +94,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(data.TotalSize))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 62, Col: 64}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 62, Col: 64}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -107,7 +107,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 83, Col: 72}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 83, Col: 72}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -165,7 +165,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var5 templ.SafeURL
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, fmt.Sprintf("/files?path=/buckets/%s", bucket.Name)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 160, Col: 124}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 160, Col: 124}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -178,7 +178,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 163, Col: 64}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 163, Col: 64}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -196,7 +196,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Owner)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 169, Col: 101}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 169, Col: 101}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -219,7 +219,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.CreatedAt.Format("2006-01-02 15:04"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 175, Col: 92}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 175, Col: 92}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -232,7 +232,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(bucket.LogicalSize))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 177, Col: 85}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 177, Col: 85}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -250,7 +250,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%.1fx overhead", float64(bucket.PhysicalSize)/float64(bucket.LogicalSize)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 180, Col: 144}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 180, Col: 144}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -268,7 +268,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var11 string
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(bucket.PhysicalSize))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 184, Col: 81}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 184, Col: 81}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -295,7 +295,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var13 string
|
||||
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(templ.CSSClasses(templ_7745c5c3_Var12).String())
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 1, Col: 0}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 1, Col: 0}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -308,7 +308,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var14 string
|
||||
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(formatBytes(bucket.Quota))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 189, Col: 86}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 189, Col: 86}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -326,7 +326,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var15 string
|
||||
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%.1f%% used", float64(bucket.LogicalSize)/float64(bucket.Quota)*100))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 193, Col: 146}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 193, Col: 146}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -384,7 +384,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var16 string
|
||||
templ_7745c5c3_Var16, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.ObjectLockMode)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 223, Col: 82}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 223, Col: 82}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var16))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -397,7 +397,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var17 string
|
||||
templ_7745c5c3_Var17, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d days", bucket.ObjectLockDuration))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 223, Col: 138}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 223, Col: 138}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var17))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -420,7 +420,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var18 templ.SafeURL
|
||||
templ_7745c5c3_Var18, templ_7745c5c3_Err = templ.JoinURLErrs(dash.PUrl(ctx, fmt.Sprintf("/files?path=/buckets/%s", bucket.Name)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 232, Col: 128}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 232, Col: 128}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var18))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -433,7 +433,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var19 string
|
||||
templ_7745c5c3_Var19, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 239, Col: 89}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 239, Col: 89}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var19))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -446,7 +446,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var20 string
|
||||
templ_7745c5c3_Var20, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 245, Col: 89}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 245, Col: 89}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var20))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -459,7 +459,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var21 string
|
||||
templ_7745c5c3_Var21, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Owner)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 246, Col: 92}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 246, Col: 92}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var21))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -472,7 +472,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var22 string
|
||||
templ_7745c5c3_Var22, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 252, Col: 89}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 252, Col: 89}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var22))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -485,7 +485,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var23 string
|
||||
templ_7745c5c3_Var23, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", getQuotaInMB(bucket.Quota)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 253, Col: 125}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 253, Col: 125}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var23))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -498,7 +498,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var24 string
|
||||
templ_7745c5c3_Var24, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%t", bucket.QuotaEnabled))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 254, Col: 118}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 254, Col: 118}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var24))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -511,7 +511,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var25 string
|
||||
templ_7745c5c3_Var25, templ_7745c5c3_Err = templ.JoinStringErrs(bucket.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 260, Col: 89}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 260, Col: 89}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var25))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -540,7 +540,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var26 string
|
||||
templ_7745c5c3_Var26, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", (data.CurrentPage-1)*data.PageSize+1))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 292, Col: 101}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 292, Col: 101}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var26))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -553,7 +553,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var27 string
|
||||
templ_7745c5c3_Var27, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", minInt(data.CurrentPage*data.PageSize, data.TotalBuckets)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 292, Col: 185}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 292, Col: 185}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var27))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -566,7 +566,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var28 string
|
||||
templ_7745c5c3_Var28, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalBuckets))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 292, Col: 229}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 292, Col: 229}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var28))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -584,7 +584,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var29 string
|
||||
templ_7745c5c3_Var29, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.CurrentPage-1))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 299, Col: 142}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 299, Col: 142}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var29))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -613,7 +613,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var30 string
|
||||
templ_7745c5c3_Var30, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 315, Col: 97}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 315, Col: 97}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var30))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -631,7 +631,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var31 string
|
||||
templ_7745c5c3_Var31, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 319, Col: 129}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 319, Col: 129}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var31))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -644,7 +644,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var32 string
|
||||
templ_7745c5c3_Var32, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", i))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 319, Col: 152}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 319, Col: 152}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var32))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -668,7 +668,7 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var33 string
|
||||
templ_7745c5c3_Var33, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.CurrentPage+1))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 327, Col: 142}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 327, Col: 142}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var33))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -696,13 +696,13 @@ func S3Buckets(data dash.S3BucketsData) templ.Component {
|
||||
var templ_7745c5c3_Var34 string
|
||||
templ_7745c5c3_Var34, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/s3_buckets.templ`, Line: 352, Col: 81}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/s3_buckets.templ`, Line: 352, Col: 81}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var34))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 79, "</small></div></div></div><!-- Create Bucket Modal --><div class=\"modal fade\" id=\"createBucketModal\" tabindex=\"-1\" aria-labelledby=\"createBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createBucketModalLabel\"><i class=\"fas fa-plus me-2\"></i>Create New S3 Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"createBucketForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label for=\"bucketName\" class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"bucketName\" name=\"name\" placeholder=\"my-bucket-name\" required pattern=\"[a-z0-9.-]+\" title=\"Bucket name must contain only lowercase letters, numbers, dots, and hyphens\"><div class=\"form-text\">Bucket names must be between 3 and 63 characters, contain only lowercase letters, numbers, dots, and hyphens.</div></div><div class=\"mb-3\"><label for=\"bucketOwner\" class=\"form-label\">Owner (Optional)</label> <select class=\"form-select\" id=\"bucketOwner\" name=\"owner\"><option value=\"\">No owner (admin-only access)</option><!-- Options will be populated dynamically when modal opens --></select><div class=\"form-text\">The S3 identity that owns this bucket. Non-admin users can only access buckets they own.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableQuota\" name=\"quota_enabled\"> <label class=\"form-check-label\" for=\"enableQuota\">Enable Storage Quota</label></div></div><div class=\"mb-3\" id=\"quotaSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-8\"><label for=\"quotaSize\" class=\"form-label\">Quota Size</label> <input type=\"number\" class=\"form-control\" id=\"quotaSize\" name=\"quota_size\" placeholder=\"1024\" min=\"1\" step=\"1\"></div><div class=\"col-md-4\"><label for=\"quotaUnit\" class=\"form-label\">Unit</label> <select class=\"form-select\" id=\"quotaUnit\" name=\"quota_unit\"><option value=\"MB\" selected>MB</option> <option value=\"GB\">GB</option> <option value=\"TB\">TB</option></select></div></div><div class=\"form-text\">Set the maximum storage size for this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableVersioning\" name=\"versioning_enabled\"> <label class=\"form-check-label\" for=\"enableVersioning\">Enable Object Versioning</label></div><div class=\"form-text\">Keep multiple versions of objects in this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableObjectLock\" name=\"object_lock_enabled\"> <label class=\"form-check-label\" for=\"enableObjectLock\">Enable Object Lock</label></div><div class=\"form-text\">Prevent objects from being deleted or overwritten for a specified period. Automatically enables versioning.</div></div><div class=\"mb-3\" id=\"objectLockSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-6\"><label for=\"objectLockMode\" class=\"form-label\">Object Lock Mode</label> <select class=\"form-select\" id=\"objectLockMode\" name=\"object_lock_mode\"><option value=\"GOVERNANCE\" selected>Governance</option> <option value=\"COMPLIANCE\">Compliance</option></select><div class=\"form-text\">Governance allows override with special permissions, Compliance is immutable.</div></div><div class=\"col-md-6\"><div class=\"form-check mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"setDefaultRetention\" name=\"set_default_retention\"> <label class=\"form-check-label\" for=\"setDefaultRetention\">Set Default Retention</label><div class=\"form-text\">Apply default retention to all new objects in this bucket.</div></div><div id=\"defaultRetentionSettings\" style=\"display: none;\"><label for=\"objectLockDuration\" class=\"form-label\">Default Retention (days)</label> <input type=\"number\" class=\"form-control\" id=\"objectLockDuration\" name=\"object_lock_duration\" placeholder=\"30\" min=\"1\" max=\"36500\" step=\"1\"><div class=\"form-text\">Default retention period for new objects (1-36500 days).</div></div></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></form></div></div></div><!-- Delete Confirmation Modal --><div class=\"modal fade\" id=\"deleteBucketModal\" tabindex=\"-1\" aria-labelledby=\"deleteBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"deleteBucketModalLabel\"><i class=\"fas fa-exclamation-triangle me-2 text-Line truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 79, "</small></div></div></div><!-- Create Bucket Modal --><div class=\"modal fade\" id=\"createBucketModal\" tabindex=\"-1\" aria-labelledby=\"createBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"createBucketModalLabel\"><i class=\"fas fa-plus me-2\"></i>Create New S3 Bucket</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\" aria-label=\"Close\"></button></div><form id=\"createBucketForm\"><div class=\"modal-body\"><div class=\"mb-3\"><label for=\"bucketName\" class=\"form-label\">Bucket Name</label> <input type=\"text\" class=\"form-control\" id=\"bucketName\" name=\"name\" placeholder=\"my-bucket-name\" required pattern=\"[a-z0-9.-]+\" title=\"Bucket name must contain only lowercase letters, numbers, dots, and hyphens\"><div class=\"form-text\">Bucket names must be between 3 and 63 characters, contain only lowercase letters, numbers, dots, and hyphens.</div></div><div class=\"mb-3\"><label for=\"bucketOwner\" class=\"form-label\">Owner (Optional)</label> <select class=\"form-select\" id=\"bucketOwner\" name=\"owner\"><option value=\"\">No owner (admin-only access)</option><!-- Options will be populated dynamically when modal opens --></select><div class=\"form-text\">The S3 identity that owns this bucket. Non-admin users can only access buckets they own.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableQuota\" name=\"quota_enabled\"> <label class=\"form-check-label\" for=\"enableQuota\">Enable Storage Quota</label></div></div><div class=\"mb-3\" id=\"quotaSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-8\"><label for=\"quotaSize\" class=\"form-label\">Quota Size</label> <input type=\"number\" class=\"form-control\" id=\"quotaSize\" name=\"quota_size\" placeholder=\"1024\" min=\"1\" step=\"1\"></div><div class=\"col-md-4\"><label for=\"quotaUnit\" class=\"form-label\">Unit</label> <select class=\"form-select\" id=\"quotaUnit\" name=\"quota_unit\"><option value=\"MB\" selected>MB</option> <option value=\"GB\">GB</option> <option value=\"TB\">TB</option></select></div></div><div class=\"form-text\">Set the maximum storage size for this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableVersioning\" name=\"versioning_enabled\"> <label class=\"form-check-label\" for=\"enableVersioning\">Enable Object Versioning</label></div><div class=\"form-text\">Keep multiple versions of objects in this bucket.</div></div><div class=\"mb-3\"><div class=\"form-check\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableObjectLock\" name=\"object_lock_enabled\"> <label class=\"form-check-label\" for=\"enableObjectLock\">Enable Object Lock</label></div><div class=\"form-text\">Prevent objects from being deleted or overwritten for a specified period. Automatically enables versioning.</div></div><div class=\"mb-3\" id=\"objectLockSettings\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-6\"><label for=\"objectLockMode\" class=\"form-label\">Object Lock Mode</label> <select class=\"form-select\" id=\"objectLockMode\" name=\"object_lock_mode\"><option value=\"GOVERNANCE\" selected>Governance</option> <option value=\"COMPLIANCE\">Compliance</option></select><div class=\"form-text\">Governance allows override with special permissions, Compliance is immutable.</div></div><div class=\"col-md-6\"><div class=\"form-check mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"setDefaultRetention\" name=\"set_default_retention\"> <label class=\"form-check-label\" for=\"setDefaultRetention\">Set Default Retention</label><div class=\"form-text\">Apply default retention to all new objects in this bucket.</div></div><div id=\"defaultRetentionSettings\" style=\"display: none;\"><label for=\"objectLockDuration\" class=\"form-label\">Default Retention (days)</label> <input type=\"number\" class=\"form-control\" id=\"objectLockDuration\" name=\"object_lock_duration\" placeholder=\"30\" min=\"1\" max=\"36500\" step=\"1\"><div class=\"form-text\">Default retention period for new objects (1-36500 days).</div></div></div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"submit\" class=\"btn btn-primary\"><i class=\"fas fa-plus me-1\"></i>Create Bucket</button></div></form></div></div></div><!-- Delete Confirmation Modal --><div class=\"modal fade\" id=\"deleteBucketModal\" tabindex=\"-1\" aria-labelledby=\"deleteBucketModalLabel\" aria-hidden=\"true\"><div class=\"modal-dialog\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\" id=\"deleteBucketModalLabel\"><i class=\"fas fa-exclamation-triangle me-2 text-Line truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -336,7 +336,7 @@ templ ServiceAccounts(data dash.ServiceAccountsData) {
|
||||
async function showSADetails(id) {
|
||||
try {
|
||||
const encodedId = encodeURIComponent(id);
|
||||
const response = await fetch(`/api/service-accounts/${encodedId}`);
|
||||
const response = await fetch(basePath(`/api/service-accounts/${encodedId}`));
|
||||
if (response.ok) {
|
||||
const sa = await response.json();
|
||||
document.getElementById('saDetailsContent').innerHTML = createSADetailsContent(sa);
|
||||
@@ -355,7 +355,7 @@ templ ServiceAccounts(data dash.ServiceAccountsData) {
|
||||
const newStatus = currentStatus === 'Active' ? 'Inactive' : 'Active';
|
||||
try {
|
||||
const encodedId = encodeURIComponent(id);
|
||||
const response = await fetch(`/api/service-accounts/${encodedId}`, {
|
||||
const response = await fetch(basePath(`/api/service-accounts/${encodedId}`), {
|
||||
method: 'PUT',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ status: newStatus })
|
||||
@@ -378,7 +378,7 @@ templ ServiceAccounts(data dash.ServiceAccountsData) {
|
||||
showDeleteConfirm(id, async function() {
|
||||
try {
|
||||
const encodedId = encodeURIComponent(id);
|
||||
const response = await fetch(`/api/service-accounts/${encodedId}`, {
|
||||
const response = await fetch(basePath(`/api/service-accounts/${encodedId}`), {
|
||||
method: 'DELETE'
|
||||
});
|
||||
|
||||
@@ -427,7 +427,7 @@ templ ServiceAccounts(data dash.ServiceAccountsData) {
|
||||
}
|
||||
|
||||
try {
|
||||
const response = await fetch('/api/service-accounts', {
|
||||
const response = await fetch(basePath('/api/service-accounts'), {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(saData)
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
// Code generated by templ - DO NOT EDIT.
|
||||
|
||||
// templ: version: v0.3.977
|
||||
// templ: version: v0.3.1001
|
||||
package app
|
||||
|
||||
//lint:file-ignore SA4006 This context is only used if a nested component is present.
|
||||
@@ -41,7 +41,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalAccounts))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 38, Col: 74}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 38, Col: 74}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -54,7 +54,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.ActiveAccounts))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 58, Col: 75}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 58, Col: 75}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -67,7 +67,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("15:04"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 78, Col: 69}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 78, Col: 69}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -85,7 +85,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var5 string
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(sa.ID)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 118, Col: 64}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 118, Col: 64}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -98,7 +98,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var6 string
|
||||
templ_7745c5c3_Var6, templ_7745c5c3_Err = templ.JoinStringErrs(sa.ParentUser)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 123, Col: 62}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 123, Col: 62}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -111,7 +111,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var7 string
|
||||
templ_7745c5c3_Var7, templ_7745c5c3_Err = templ.JoinStringErrs(sa.AccessKeyId)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 126, Col: 88}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 126, Col: 88}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -139,7 +139,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(sa.CreateDate.Format("2006-01-02"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 135, Col: 83}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 135, Col: 83}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -152,7 +152,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(sa.ID)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 139, Col: 108}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 139, Col: 108}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -165,7 +165,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(sa.ID)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 143, Col: 109}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 143, Col: 109}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -178,7 +178,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var11 string
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(sa.Status)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 143, Col: 143}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 143, Col: 143}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -206,7 +206,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var12 string
|
||||
templ_7745c5c3_Var12, templ_7745c5c3_Err = templ.JoinStringErrs(sa.ID)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 151, Col: 102}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 151, Col: 102}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var12))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -230,7 +230,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var13 string
|
||||
templ_7745c5c3_Var13, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 182, Col: 81}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 182, Col: 81}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var13))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -248,7 +248,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var14 string
|
||||
templ_7745c5c3_Var14, templ_7745c5c3_Err = templ.JoinStringErrs(user)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 205, Col: 56}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 205, Col: 56}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var14))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -261,7 +261,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
var templ_7745c5c3_Var15 string
|
||||
templ_7745c5c3_Var15, templ_7745c5c3_Err = templ.JoinStringErrs(user)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/service_accounts.templ`, Line: 205, Col: 65}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/service_accounts.templ`, Line: 205, Col: 65}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var15))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -272,7 +272,7 @@ func ServiceAccounts(data dash.ServiceAccountsData) templ.Component {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "</select> <small class=\"form-text text-muted\">The service account will inherit permissions from this user</small></div><div class=\"mb-3\"><label for=\"description\" class=\"form-label\">Description</label> <textarea class=\"form-control\" id=\"description\" name=\"description\" rows=\"2\" placeholder=\"What is this service account used for?\"></textarea></div><div class=\"mb-3\"><label for=\"expiration\" class=\"form-label\">Expiration (optional)</label> <input type=\"datetime-local\" class=\"form-control\" id=\"expiration\" name=\"expiration\"> <small class=\"form-text text-muted\">Leave empty for no expiration</small></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"handleCreateServiceAccount()\">Create</button></div></div></div></div><!-- Service Account Details Modal --><div class=\"modal fade\" id=\"saDetailsModal\" tabindex=\"-1\" role=\"dialog\"><div class=\"modal-dialog modal-lg\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\"><i class=\"fas fa-robot me-2\"></i>Service Account Details</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\" id=\"saDetailsContent\"><!-- Content will be loaded dynamically --></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button></div></div></div></div><!-- Credentials Display Modal --><div class=\"modal fade\" id=\"credentialsModal\" tabindex=\"-1\" role=\"dialog\" data-bs-backdrop=\"static\" data-bs-keyboard=\"false\"><div class=\"modal-dialog modal-lg\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header bg-success text-white\"><h5 class=\"modal-title\"><i class=\"fas fa-check-circle me-2\"></i>Service Account Created Successfully</h5></div><div class=\"modal-body\"><div class=\"alert alert-warning\"><i class=\"fas fa-exclamation-triangle me-2\"></i> <strong>Important:</strong> This is the only time you will see the secret access key. Please save it securely.</div><div class=\"mb-4\"><h6 class=\"text-muted mb-3\">AWS CLI Configuration</h6><p class=\"text-muted small\">Use these credentials to configure AWS CLI or SDKs:</p><div class=\"mb-3\"><label class=\"form-label fw-bold\">AWS_ACCESS_KEY_ID</label><div class=\"input-group\"><input type=\"text\" class=\"form-control font-monospace\" id=\"displayAccessKey\" readonly> <button class=\"btn btn-outline-secondary\" type=\"button\" onclick=\"copyCredentialToClipboard(this, 'displayAccessKey')\"><i class=\"fas fa-copy\"></i> Copy</button></div></div><div class=\"mb-3\"><label class=\"form-label fw-bold\">AWS_SECRET_ACCESS_KEY</label><div class=\"input-group\"><input type=\"text\" class=\"form-control font-monospace\" id=\"displaySecretKey\" readonly> <button class=\"btn btn-outline-secondary\" type=\"button\" onclick=\"copyCredentialToClipboard(this, 'displaySecretKey')\"><i class=\"fas fa-copy\"></i> Copy</button></div></div></div><div class=\"bg-light p-3 rounded\"><h6 class=\"text-muted mb-2\">Example AWS CLI Usage:</h6><div class=\"font-monospace small\"><div>export AWS_ACCESS_KEY_ID=<span id=\"exampleAccessKey\"></span></div><div>export AWS_SECRET_ACCESS_KEY=<span id=\"exampleSecretKey\"></span></div><div>export AWS_ENDPOINT_URL=http://localhost:8333</div><div class=\"mt-2\"># List buckets</div><div>aws s3 ls</div><div class=\"mt-2\"># Upload a file</div><div>aws s3 cp myfile.txt s3://mybucket/</div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-primary\" onclick=\"closeCredentialsModal()\"><i class=\"fas fa-check me-1\"></i>I have saved the credentials</button></div></div></div></div><!-- JavaScript for service account management --><script>\n document.addEventListener('DOMContentLoaded', function() {\n document.addEventListener('click', function(e) {\n const button = e.target.closest('[data-action]');\n if (!button) return;\n \n const action = button.getAttribute('data-action');\n const saId = button.getAttribute('data-sa-id');\n \n switch (action) {\n case 'show-sa-details':\n showSADetails(saId);\n break;\n case 'toggle-sa-status':\n toggleSAStatus(saId, button.getAttribute('data-current-status'));\n break;\n case 'delete-sa':\n deleteSA(saId);\n break;\n }\n });\n });\n\n async function showSADetails(id) {\n try {\n const encodedId = encodeURIComponent(id);\n Line truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 26, "</select> <small class=\"form-text text-muted\">The service account will inherit permissions from this user</small></div><div class=\"mb-3\"><label for=\"description\" class=\"form-label\">Description</label> <textarea class=\"form-control\" id=\"description\" name=\"description\" rows=\"2\" placeholder=\"What is this service account used for?\"></textarea></div><div class=\"mb-3\"><label for=\"expiration\" class=\"form-label\">Expiration (optional)</label> <input type=\"datetime-local\" class=\"form-control\" id=\"expiration\" name=\"expiration\"> <small class=\"form-text text-muted\">Leave empty for no expiration</small></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"handleCreateServiceAccount()\">Create</button></div></div></div></div><!-- Service Account Details Modal --><div class=\"modal fade\" id=\"saDetailsModal\" tabindex=\"-1\" role=\"dialog\"><div class=\"modal-dialog modal-lg\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\"><i class=\"fas fa-robot me-2\"></i>Service Account Details</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\" id=\"saDetailsContent\"><!-- Content will be loaded dynamically --></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Close</button></div></div></div></div><!-- Credentials Display Modal --><div class=\"modal fade\" id=\"credentialsModal\" tabindex=\"-1\" role=\"dialog\" data-bs-backdrop=\"static\" data-bs-keyboard=\"false\"><div class=\"modal-dialog modal-lg\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header bg-success text-white\"><h5 class=\"modal-title\"><i class=\"fas fa-check-circle me-2\"></i>Service Account Created Successfully</h5></div><div class=\"modal-body\"><div class=\"alert alert-warning\"><i class=\"fas fa-exclamation-triangle me-2\"></i> <strong>Important:</strong> This is the only time you will see the secret access key. Please save it securely.</div><div class=\"mb-4\"><h6 class=\"text-muted mb-3\">AWS CLI Configuration</h6><p class=\"text-muted small\">Use these credentials to configure AWS CLI or SDKs:</p><div class=\"mb-3\"><label class=\"form-label fw-bold\">AWS_ACCESS_KEY_ID</label><div class=\"input-group\"><input type=\"text\" class=\"form-control font-monospace\" id=\"displayAccessKey\" readonly> <button class=\"btn btn-outline-secondary\" type=\"button\" onclick=\"copyCredentialToClipboard(this, 'displayAccessKey')\"><i class=\"fas fa-copy\"></i> Copy</button></div></div><div class=\"mb-3\"><label class=\"form-label fw-bold\">AWS_SECRET_ACCESS_KEY</label><div class=\"input-group\"><input type=\"text\" class=\"form-control font-monospace\" id=\"displaySecretKey\" readonly> <button class=\"btn btn-outline-secondary\" type=\"button\" onclick=\"copyCredentialToClipboard(this, 'displaySecretKey')\"><i class=\"fas fa-copy\"></i> Copy</button></div></div></div><div class=\"bg-light p-3 rounded\"><h6 class=\"text-muted mb-2\">Example AWS CLI Usage:</h6><div class=\"font-monospace small\"><div>export AWS_ACCESS_KEY_ID=<span id=\"exampleAccessKey\"></span></div><div>export AWS_SECRET_ACCESS_KEY=<span id=\"exampleSecretKey\"></span></div><div>export AWS_ENDPOINT_URL=http://localhost:8333</div><div class=\"mt-2\"># List buckets</div><div>aws s3 ls</div><div class=\"mt-2\"># Upload a file</div><div>aws s3 cp myfile.txt s3://mybucket/</div></div></div></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-primary\" onclick=\"closeCredentialsModal()\"><i class=\"fas fa-check me-1\"></i>I have saved the credentials</button></div></div></div></div><!-- JavaScript for service account management --><script>\n document.addEventListener('DOMContentLoaded', function() {\n document.addEventListener('click', function(e) {\n const button = e.target.closest('[data-action]');\n if (!button) return;\n \n const action = button.getAttribute('data-action');\n const saId = button.getAttribute('data-sa-id');\n \n switch (action) {\n case 'show-sa-details':\n showSADetails(saId);\n break;\n case 'toggle-sa-status':\n toggleSAStatus(saId, button.getAttribute('data-current-status'));\n break;\n case 'delete-sa':\n deleteSA(saId);\n break;\n }\n });\n });\n\n async function showSADetails(id) {\n try {\n const encodedId = encodeURIComponent(id);\n Line truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
@@ -273,7 +273,7 @@ templ Topics(data dash.TopicsData) {
|
||||
};
|
||||
|
||||
// Create the topic
|
||||
fetch('/api/mq/topics/create', {
|
||||
fetch(basePath('/api/mq/topics/create'), {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json'
|
||||
@@ -354,7 +354,7 @@ templ Topics(data dash.TopicsData) {
|
||||
var detailsRow = document.getElementById('details-' + topicName.replace(/\./g, '_'));
|
||||
var contentDiv = detailsRow.querySelector('.topic-details-content');
|
||||
|
||||
fetch('/admin/topics/' + encodeURIComponent(topicName) + '/details')
|
||||
fetch(basePath('/admin/topics/' + encodeURIComponent(topicName) + '/details'))
|
||||
.then(response => response.json())
|
||||
.then(data => {
|
||||
var html = '<div class="row">';
|
||||
|
||||
@@ -40,7 +40,7 @@ func Topics(data dash.TopicsData) templ.Component {
|
||||
var templ_7745c5c3_Var2 string
|
||||
templ_7745c5c3_Var2, templ_7745c5c3_Err = templ.JoinStringErrs(data.LastUpdated.Format("2006-01-02 15:04:05"))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 13, Col: 107}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 13, Col: 107}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var2))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -53,7 +53,7 @@ func Topics(data dash.TopicsData) templ.Component {
|
||||
var templ_7745c5c3_Var3 string
|
||||
templ_7745c5c3_Var3, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", data.TotalTopics))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 22, Col: 93}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 22, Col: 93}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var3))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -66,7 +66,7 @@ func Topics(data dash.TopicsData) templ.Component {
|
||||
var templ_7745c5c3_Var4 string
|
||||
templ_7745c5c3_Var4, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", len(data.Topics)))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 30, Col: 90}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 30, Col: 90}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var4))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -94,7 +94,7 @@ func Topics(data dash.TopicsData) templ.Component {
|
||||
var templ_7745c5c3_Var5 string
|
||||
templ_7745c5c3_Var5, templ_7745c5c3_Err = templ.JoinStringErrs(topic.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 70, Col: 93}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 70, Col: 93}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var5))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -113,7 +113,7 @@ func Topics(data dash.TopicsData) templ.Component {
|
||||
return topic.Name[:idx]
|
||||
}())
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 78, Col: 55}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 78, Col: 55}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var6))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -132,7 +132,7 @@ func Topics(data dash.TopicsData) templ.Component {
|
||||
return topic.Name[idx+1:]
|
||||
}())
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 87, Col: 55}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 87, Col: 55}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var7))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -145,7 +145,7 @@ func Topics(data dash.TopicsData) templ.Component {
|
||||
var templ_7745c5c3_Var8 string
|
||||
templ_7745c5c3_Var8, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d", topic.Partitions))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 90, Col: 116}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 90, Col: 116}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var8))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -163,7 +163,7 @@ func Topics(data dash.TopicsData) templ.Component {
|
||||
var templ_7745c5c3_Var9 string
|
||||
templ_7745c5c3_Var9, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("%d %s", topic.Retention.DisplayValue, topic.Retention.DisplayUnit))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 96, Col: 140}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 96, Col: 140}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var9))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -186,7 +186,7 @@ func Topics(data dash.TopicsData) templ.Component {
|
||||
var templ_7745c5c3_Var10 string
|
||||
templ_7745c5c3_Var10, templ_7745c5c3_Err = templ.JoinStringErrs(topic.Name)
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 105, Col: 160}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 105, Col: 160}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var10))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -199,7 +199,7 @@ func Topics(data dash.TopicsData) templ.Component {
|
||||
var templ_7745c5c3_Var11 string
|
||||
templ_7745c5c3_Var11, templ_7745c5c3_Err = templ.JoinStringErrs(fmt.Sprintf("details-%s", strings.ReplaceAll(topic.Name, ".", "_")))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `weed/admin/view/app/topics.templ`, Line: 110, Col: 146}
|
||||
return templ.Error{Err: templ_7745c5c3_Err, FileName: `view/app/topics.templ`, Line: 110, Col: 146}
|
||||
}
|
||||
_, templ_7745c5c3_Err = templ_7745c5c3_Buffer.WriteString(templ.EscapeString(templ_7745c5c3_Var11))
|
||||
if templ_7745c5c3_Err != nil {
|
||||
@@ -215,7 +215,7 @@ func Topics(data dash.TopicsData) templ.Component {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
}
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "</div></div></div></div></div><!-- Create Topic Modal --><div class=\"modal fade\" id=\"createTopicModal\" tabindex=\"-1\" role=\"dialog\"><div class=\"modal-dialog modal-lg\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\"><i class=\"fas fa-plus me-2\"></i>Create New Topic</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\"><form id=\"createTopicForm\"><div class=\"row\"><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"topicNamespace\" class=\"form-label\">Namespace *</label> <input type=\"text\" class=\"form-control\" id=\"topicNamespace\" name=\"namespace\" required placeholder=\"e.g., default\"></div></div><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"topicName\" class=\"form-label\">Topic Name *</label> <input type=\"text\" class=\"form-control\" id=\"topicName\" name=\"name\" required placeholder=\"e.g., user-events\"></div></div></div><div class=\"row\"><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"partitionCount\" class=\"form-label\">Partition Count *</label> <input type=\"number\" class=\"form-control\" id=\"partitionCount\" name=\"partitionCount\" required min=\"1\" max=\"100\" value=\"6\"></div></div></div><!-- Retention Configuration --><div class=\"card mt-3\"><div class=\"card-header\"><h6 class=\"mb-0\"><i class=\"fas fa-clock me-2\"></i>Retention Policy</h6></div><div class=\"card-body\"><div class=\"form-check mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableRetention\" name=\"enableRetention\" onchange=\"toggleRetentionFields()\"> <label class=\"form-check-label\" for=\"enableRetention\">Enable data retention</label></div><div id=\"retentionFields\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"retentionValue\" class=\"form-label\">Retention Duration</label> <input type=\"number\" class=\"form-control\" id=\"retentionValue\" name=\"retentionValue\" min=\"1\" value=\"7\"></div></div><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"retentionUnit\" class=\"form-label\">Unit</label> <select class=\"form-control\" id=\"retentionUnit\" name=\"retentionUnit\"><option value=\"hours\">Hours</option> <option value=\"days\" selected>Days</option></select></div></div></div><div class=\"alert alert-info\"><i class=\"fas fa-info-circle me-2\"></i> Data older than this duration will be automatically purged to save storage space.</div></div></div></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"createTopic()\"><i class=\"fas fa-plus me-1\"></i>Create Topic</button></div></div></div></div><script type=\"text/javascript\">\n // Topic management functions\n function showCreateTopicModal() {\n var modal = new bootstrap.Modal(document.getElementById('createTopicModal'));\n modal.show();\n }\n\n function toggleRetentionFields() {\n var enableRetention = document.getElementById('enableRetention').checked;\n var retentionFields = document.getElementById('retentionFields');\n \n if (enableRetention) {\n retentionFields.style.display = 'block';\n } else {\n retentionFields.style.display = 'none';\n }\n }\n\n function createTopic() {\n var form = document.getElementById('createTopicForm');\n var formData = new FormData(form);\n \n if (!form.checkValidity()) {\n form.classList.add('was-validated');\n return;\n }\n \n var namespace = formData.get('namespace');\n var name = formData.get('name');\n var partitionCount = formData.get('partitionCount');\n var enableRetention = formData.get('enableRetention');\n var retentionValue = enableRetention === 'on' ? parseInt(formData.get('retentionValue')) : 0;\n var retentionUnit = enableRetention === 'on' ? formData.get('retentionUnit') : 'hours';\n \n // Convert retention to seconds\n var retentionSeconds = 0;\n if (enableRetention === 'on' && retentionValue > 0) {\n if (retentionUnit === 'hours') {\n retentionSeconds = retentionValue * 3600;\n } else if (retentionUnit === 'days') {\n retentionSeconds = retentionValue * 86400;\n }\n }\n \n var topicData = {\n namespace: namespace,\n name: name,\n partition_count: parseInt(partitionCount),\n retention: {\n enabled: enableRetentLine truncated
|
||||
templ_7745c5c3_Err = templruntime.WriteString(templ_7745c5c3_Buffer, 19, "</div></div></div></div></div><!-- Create Topic Modal --><div class=\"modal fade\" id=\"createTopicModal\" tabindex=\"-1\" role=\"dialog\"><div class=\"modal-dialog modal-lg\" role=\"document\"><div class=\"modal-content\"><div class=\"modal-header\"><h5 class=\"modal-title\"><i class=\"fas fa-plus me-2\"></i>Create New Topic</h5><button type=\"button\" class=\"btn-close\" data-bs-dismiss=\"modal\"></button></div><div class=\"modal-body\"><form id=\"createTopicForm\"><div class=\"row\"><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"topicNamespace\" class=\"form-label\">Namespace *</label> <input type=\"text\" class=\"form-control\" id=\"topicNamespace\" name=\"namespace\" required placeholder=\"e.g., default\"></div></div><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"topicName\" class=\"form-label\">Topic Name *</label> <input type=\"text\" class=\"form-control\" id=\"topicName\" name=\"name\" required placeholder=\"e.g., user-events\"></div></div></div><div class=\"row\"><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"partitionCount\" class=\"form-label\">Partition Count *</label> <input type=\"number\" class=\"form-control\" id=\"partitionCount\" name=\"partitionCount\" required min=\"1\" max=\"100\" value=\"6\"></div></div></div><!-- Retention Configuration --><div class=\"card mt-3\"><div class=\"card-header\"><h6 class=\"mb-0\"><i class=\"fas fa-clock me-2\"></i>Retention Policy</h6></div><div class=\"card-body\"><div class=\"form-check mb-3\"><input class=\"form-check-input\" type=\"checkbox\" id=\"enableRetention\" name=\"enableRetention\" onchange=\"toggleRetentionFields()\"> <label class=\"form-check-label\" for=\"enableRetention\">Enable data retention</label></div><div id=\"retentionFields\" style=\"display: none;\"><div class=\"row\"><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"retentionValue\" class=\"form-label\">Retention Duration</label> <input type=\"number\" class=\"form-control\" id=\"retentionValue\" name=\"retentionValue\" min=\"1\" value=\"7\"></div></div><div class=\"col-md-6\"><div class=\"mb-3\"><label for=\"retentionUnit\" class=\"form-label\">Unit</label> <select class=\"form-control\" id=\"retentionUnit\" name=\"retentionUnit\"><option value=\"hours\">Hours</option> <option value=\"days\" selected>Days</option></select></div></div></div><div class=\"alert alert-info\"><i class=\"fas fa-info-circle me-2\"></i> Data older than this duration will be automatically purged to save storage space.</div></div></div></div></form></div><div class=\"modal-footer\"><button type=\"button\" class=\"btn btn-secondary\" data-bs-dismiss=\"modal\">Cancel</button> <button type=\"button\" class=\"btn btn-primary\" onclick=\"createTopic()\"><i class=\"fas fa-plus me-1\"></i>Create Topic</button></div></div></div></div><script type=\"text/javascript\">\n // Topic management functions\n function showCreateTopicModal() {\n var modal = new bootstrap.Modal(document.getElementById('createTopicModal'));\n modal.show();\n }\n\n function toggleRetentionFields() {\n var enableRetention = document.getElementById('enableRetention').checked;\n var retentionFields = document.getElementById('retentionFields');\n \n if (enableRetention) {\n retentionFields.style.display = 'block';\n } else {\n retentionFields.style.display = 'none';\n }\n }\n\n function createTopic() {\n var form = document.getElementById('createTopicForm');\n var formData = new FormData(form);\n \n if (!form.checkValidity()) {\n form.classList.add('was-validated');\n return;\n }\n \n var namespace = formData.get('namespace');\n var name = formData.get('name');\n var partitionCount = formData.get('partitionCount');\n var enableRetention = formData.get('enableRetention');\n var retentionValue = enableRetention === 'on' ? parseInt(formData.get('retentionValue')) : 0;\n var retentionUnit = enableRetention === 'on' ? formData.get('retentionUnit') : 'hours';\n \n // Convert retention to seconds\n var retentionSeconds = 0;\n if (enableRetention === 'on' && retentionValue > 0) {\n if (retentionUnit === 'hours') {\n retentionSeconds = retentionValue * 3600;\n } else if (retentionUnit === 'days') {\n retentionSeconds = retentionValue * 86400;\n }\n }\n \n var topicData = {\n namespace: namespace,\n name: name,\n partition_count: parseInt(partitionCount),\n retention: {\n enabled: enableRetentLine truncated
|
||||
if templ_7745c5c3_Err != nil {
|
||||
return templ_7745c5c3_Err
|
||||
}
|
||||
|
||||
+45
-30
@@ -4,6 +4,7 @@ import (
|
||||
"bufio"
|
||||
"context"
|
||||
"crypto/rand"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"log"
|
||||
"net"
|
||||
@@ -411,43 +412,57 @@ func startAdminServer(ctx context.Context, options AdminOptions, enableUI bool,
|
||||
Handler: handler,
|
||||
}
|
||||
|
||||
// Decide TLS configuration BEFORE launching the server goroutine, so a
|
||||
// bad cert or a missing key surfaces as a startup error instead of a
|
||||
// silently returned goroutine that leaves startAdminServer blocked on
|
||||
// ctx.Done() with no listener.
|
||||
var (
|
||||
clientCertFile,
|
||||
certFile,
|
||||
keyFile string
|
||||
)
|
||||
useTLS := false
|
||||
useMTLS := false
|
||||
|
||||
if viper.GetString("https.admin.key") != "" {
|
||||
useTLS = true
|
||||
certFile = viper.GetString("https.admin.cert")
|
||||
keyFile = viper.GetString("https.admin.key")
|
||||
}
|
||||
|
||||
if viper.GetString("https.admin.ca") != "" {
|
||||
useMTLS = true
|
||||
clientCertFile = viper.GetString("https.admin.ca")
|
||||
}
|
||||
|
||||
if useMTLS {
|
||||
server.TLSConfig = security.LoadClientTLSHTTP(clientCertFile)
|
||||
}
|
||||
|
||||
if useTLS {
|
||||
getCert, certProvider, certErr := security.NewReloadingServerCertificate(certFile, keyFile)
|
||||
if certErr != nil {
|
||||
return fmt.Errorf("load admin HTTPS certificate: %w", certErr)
|
||||
}
|
||||
defer certProvider.Close()
|
||||
if server.TLSConfig == nil {
|
||||
server.TLSConfig = &tls.Config{}
|
||||
}
|
||||
server.TLSConfig.GetCertificate = getCert
|
||||
}
|
||||
|
||||
// Start server
|
||||
go func() {
|
||||
log.Printf("Starting SeaweedFS Admin Server on port %d", *options.port)
|
||||
|
||||
// start http or https server with security.toml
|
||||
var (
|
||||
clientCertFile,
|
||||
certFile,
|
||||
keyFile string
|
||||
)
|
||||
useTLS := false
|
||||
useMTLS := false
|
||||
|
||||
if viper.GetString("https.admin.key") != "" {
|
||||
useTLS = true
|
||||
certFile = viper.GetString("https.admin.cert")
|
||||
keyFile = viper.GetString("https.admin.key")
|
||||
}
|
||||
|
||||
if viper.GetString("https.admin.ca") != "" {
|
||||
useMTLS = true
|
||||
clientCertFile = viper.GetString("https.admin.ca")
|
||||
}
|
||||
|
||||
if useMTLS {
|
||||
server.TLSConfig = security.LoadClientTLSHTTP(clientCertFile)
|
||||
}
|
||||
|
||||
var serveErr error
|
||||
if useTLS {
|
||||
log.Printf("Starting SeaweedFS Admin Server with TLS on port %d", *options.port)
|
||||
err = server.ListenAndServeTLS(certFile, keyFile)
|
||||
serveErr = server.ListenAndServeTLS("", "")
|
||||
} else {
|
||||
err = server.ListenAndServe()
|
||||
serveErr = server.ListenAndServe()
|
||||
}
|
||||
|
||||
if err != nil && err != http.ErrServerClosed {
|
||||
log.Printf("Failed to start server: %v", err)
|
||||
if serveErr != nil && serveErr != http.ErrServerClosed {
|
||||
log.Printf("Failed to start server: %v", serveErr)
|
||||
}
|
||||
}()
|
||||
|
||||
|
||||
+17
-26
@@ -15,8 +15,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
"google.golang.org/grpc/credentials/tls/certprovider"
|
||||
"google.golang.org/grpc/credentials/tls/certprovider/pemfile"
|
||||
"google.golang.org/grpc/reflection"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential"
|
||||
@@ -82,9 +80,7 @@ type FilerOptions struct {
|
||||
allowedOrigins *string
|
||||
exposeDirectoryData *bool
|
||||
tusBasePath *string
|
||||
certProvider certprovider.Provider
|
||||
s3ConfigFile *string // optional path to static S3 identity config
|
||||
mountPeerRegistryEnable *bool // accept MountRegister/MountList RPCs (peer chunk sharing tier 1)
|
||||
// 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.
|
||||
@@ -127,7 +123,6 @@ func init() {
|
||||
f.allowedOrigins = cmdFiler.Flag.String("allowedOrigins", "*", "comma separated list of allowed origins")
|
||||
f.exposeDirectoryData = cmdFiler.Flag.Bool("exposeDirectoryData", true, "whether to return directory metadata and content in Filer UI")
|
||||
f.tusBasePath = cmdFiler.Flag.String("tusBasePath", "/.tus", "TUS resumable upload endpoint base path (e.g., /.tus)")
|
||||
f.mountPeerRegistryEnable = cmdFiler.Flag.Bool("mount.p2p", true, "accept MountRegister/MountList RPCs from weed mount clients for peer chunk sharing (tier 1). Idle cost is near-zero; set false to disable.")
|
||||
|
||||
// start s3 on filer
|
||||
filerStartS3 = cmdFiler.Flag.Bool("s3", false, "whether to start S3 gateway")
|
||||
@@ -315,15 +310,6 @@ func runFiler(cmd *Command, args []string) bool {
|
||||
return true
|
||||
}
|
||||
|
||||
// GetCertificateWithUpdate Auto refreshing TSL certificate
|
||||
func (fo *FilerOptions) GetCertificateWithUpdate(*tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||
certs, err := fo.certProvider.KeyMaterial(context.Background())
|
||||
if certs == nil {
|
||||
return nil, err
|
||||
}
|
||||
return &certs.Certs[0], err
|
||||
}
|
||||
|
||||
func (fo *FilerOptions) startFiler() {
|
||||
|
||||
defaultMux := http.NewServeMux()
|
||||
@@ -388,7 +374,6 @@ func (fo *FilerOptions) startFiler() {
|
||||
AllowedOrigins: strings.Split(*fo.allowedOrigins, ","),
|
||||
TusBasePath: *fo.tusBasePath,
|
||||
CredentialManager: credentialManager,
|
||||
MountPeerRegistryEnabled: fo.mountPeerRegistryEnable != nil && *fo.mountPeerRegistryEnable,
|
||||
})
|
||||
if nfs_err != nil {
|
||||
glog.Fatalf("Filer startup error: %v", nfs_err)
|
||||
@@ -500,14 +485,11 @@ func (fo *FilerOptions) startFiler() {
|
||||
caCertFile := viper.GetString("https.filer.ca")
|
||||
disbaleTlsVerifyClientCert := viper.GetBool("https.filer.disable_tls_verify_client_cert")
|
||||
|
||||
pemfileOptions := pemfile.Options{
|
||||
CertFile: certFile,
|
||||
KeyFile: keyFile,
|
||||
RefreshDuration: security.CredRefreshingInterval,
|
||||
}
|
||||
if fo.certProvider, err = pemfile.NewProvider(pemfileOptions); err != nil {
|
||||
glog.Fatalf("pemfile.NewProvider(%v) failed: %v", pemfileOptions, err)
|
||||
getCert, certProvider, err := security.NewReloadingServerCertificate(certFile, keyFile)
|
||||
if err != nil {
|
||||
glog.Fatalf("Filer failed to load HTTPS certificate: %v", err)
|
||||
}
|
||||
defer certProvider.Close()
|
||||
|
||||
caCertPool := x509.NewCertPool()
|
||||
if caCertFile != "" {
|
||||
@@ -524,12 +506,15 @@ func (fo *FilerOptions) startFiler() {
|
||||
}
|
||||
|
||||
tlsConfig := &tls.Config{
|
||||
GetCertificate: fo.GetCertificateWithUpdate,
|
||||
GetCertificate: getCert,
|
||||
ClientAuth: clientAuth,
|
||||
ClientCAs: caCertPool,
|
||||
}
|
||||
|
||||
security.FixTlsConfig(util.GetViper(), tlsConfig)
|
||||
err = security.FixTlsConfig(util.GetViper(), tlsConfig)
|
||||
if err != nil {
|
||||
glog.Fatalf("Filer failed to fix TLS config: %v", err)
|
||||
}
|
||||
|
||||
var localTLSServer *http.Server
|
||||
if filerLocalListener != nil {
|
||||
@@ -552,10 +537,16 @@ func (fo *FilerOptions) startFiler() {
|
||||
shutdownCtx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
|
||||
defer cancel()
|
||||
if socketServer != nil {
|
||||
socketServer.Shutdown(shutdownCtx)
|
||||
err = socketServer.Shutdown(shutdownCtx)
|
||||
if err != nil {
|
||||
glog.Warningf("socket server shutdown: %v", err)
|
||||
}
|
||||
}
|
||||
if localTLSServer != nil {
|
||||
localTLSServer.Shutdown(shutdownCtx)
|
||||
err = localTLSServer.Shutdown(shutdownCtx)
|
||||
if err != nil {
|
||||
glog.Warningf("local TLS server shutdown: %v", err)
|
||||
}
|
||||
}
|
||||
if err := httpS.Shutdown(shutdownCtx); err != nil {
|
||||
glog.Warningf("HTTPS server shutdown: %v", err)
|
||||
|
||||
@@ -161,11 +161,13 @@ func doFilerBackup(grpcDialOption grpc.DialOption, backupOption *FilerBackupOpti
|
||||
|
||||
// create filer sink
|
||||
filerSource := &source.FilerSource{}
|
||||
filerSource.DoInitialize(
|
||||
if err := filerSource.DoInitialize(
|
||||
sourceFiler.ToHttpAddress(),
|
||||
sourceFiler.ToGrpcAddress(),
|
||||
sourcePath,
|
||||
*backupOption.proxyByFiler)
|
||||
*backupOption.proxyByFiler); err != nil {
|
||||
return fmt.Errorf("filersource initialization failed: %v", err)
|
||||
}
|
||||
|
||||
if err := repl_util.InitializeSSEForReplication(filerSource); err != nil {
|
||||
return fmt.Errorf("SSE initialization failed: %v", err)
|
||||
|
||||
@@ -4,7 +4,9 @@ package command
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
jsoniter "github.com/json-iterator/go"
|
||||
elastic "github.com/olivere/elastic/v7"
|
||||
@@ -13,16 +15,17 @@ import (
|
||||
)
|
||||
|
||||
type EsDocument struct {
|
||||
Dir string `json:"dir,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
IsDirectory bool `json:"isDir,omitempty"`
|
||||
Size uint64 `json:"size,omitempty"`
|
||||
Uid uint32 `json:"uid,omitempty"`
|
||||
Gid uint32 `json:"gid,omitempty"`
|
||||
UserName string `json:"userName,omitempty"`
|
||||
Crtime int64 `json:"crtime,omitempty"`
|
||||
Mtime int64 `json:"mtime,omitempty"`
|
||||
Mime string `json:"mime,omitempty"`
|
||||
Dir string `json:"dir,omitempty"`
|
||||
Name string `json:"name,omitempty"`
|
||||
IsDirectory bool `json:"isDir,omitempty"`
|
||||
Size uint64 `json:"size,omitempty"`
|
||||
Uid uint32 `json:"uid,omitempty"`
|
||||
Gid uint32 `json:"gid,omitempty"`
|
||||
UserName string `json:"userName,omitempty"`
|
||||
Crtime int64 `json:"crtime,omitempty"`
|
||||
Mtime int64 `json:"mtime,omitempty"`
|
||||
Mime string `json:"mime,omitempty"`
|
||||
Extended map[string]string `json:"extended,omitempty"`
|
||||
}
|
||||
|
||||
func toEsEntry(event *filer_pb.EventNotification) (*EsDocument, string) {
|
||||
@@ -40,10 +43,31 @@ func toEsEntry(event *filer_pb.EventNotification) (*EsDocument, string) {
|
||||
Crtime: entry.Attributes.Crtime,
|
||||
Mtime: entry.Attributes.Mtime,
|
||||
Mime: entry.Attributes.Mime,
|
||||
Extended: toExtendedStrings(entry.Extended),
|
||||
}
|
||||
return esEntry, id
|
||||
}
|
||||
|
||||
// toExtendedStrings converts the xattr map (e.g. S3 user metadata like
|
||||
// X-Amz-Meta-*) to string values so Elasticsearch indexes them as text
|
||||
// instead of base64-encoding the raw bytes. Non-UTF-8 values are prefixed
|
||||
// with "base64:" so consumers can distinguish encoded bytes from plain
|
||||
// strings that happen to look like base64.
|
||||
func toExtendedStrings(extended map[string][]byte) map[string]string {
|
||||
if len(extended) == 0 {
|
||||
return nil
|
||||
}
|
||||
result := make(map[string]string, len(extended))
|
||||
for k, v := range extended {
|
||||
if utf8.Valid(v) {
|
||||
result[k] = string(v)
|
||||
} else {
|
||||
result[k] = "base64:" + base64.StdEncoding.EncodeToString(v)
|
||||
}
|
||||
}
|
||||
return result
|
||||
}
|
||||
|
||||
func sendToElasticSearchFunc(servers string, esIndex string) (func(resp *filer_pb.SubscribeMetadataResponse) error, error) {
|
||||
options := []elastic.ClientOptionFunc{}
|
||||
options = append(options, elastic.SetURL(strings.Split(servers, ",")...))
|
||||
|
||||
@@ -3,11 +3,11 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/filer_pb"
|
||||
)
|
||||
|
||||
func sendToElasticSearchFunc(servers string, esIndex string) (func(resp *filer_pb.SubscribeMetadataResponse) error, error) {
|
||||
return func(resp *filer_pb.SubscribeMetadataResponse) error {
|
||||
return nil
|
||||
}, nil
|
||||
return nil, fmt.Errorf("this weed binary was built without Elasticsearch support. Rebuild with `-tags elastic` (see docker/Dockerfile.go_build) to use -es/-es.index")
|
||||
}
|
||||
+3
-1
@@ -195,7 +195,9 @@ func doFixOneVolume(basepath string, baseFileName string, collection string, vol
|
||||
if *fixIgnoreError {
|
||||
glog.Error(err)
|
||||
} else {
|
||||
os.Remove(indexFileName)
|
||||
if err := os.Remove(indexFileName); err != nil {
|
||||
glog.Errorf("failed to cleanup file %s:%v", indexFileName, err)
|
||||
}
|
||||
glog.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -243,7 +243,9 @@ func runFuse(cmd *Command, args []string) bool {
|
||||
case "fusermount.path":
|
||||
fusermountPath = parameter.value
|
||||
case "config_dir":
|
||||
util.ConfigurationFileDirectory.Set(parameter.value)
|
||||
if err := util.ConfigurationFileDirectory.Set(parameter.value); err != nil {
|
||||
panic(fmt.Errorf("config_dir %s: %w", parameter.value, err))
|
||||
}
|
||||
// FUSE performance options
|
||||
case "writebackCache":
|
||||
if parsed, err := strconv.ParseBool(parameter.value); err == nil {
|
||||
|
||||
+20
-3
@@ -148,7 +148,9 @@ func runMaster(cmd *Command, args []string) bool {
|
||||
|
||||
parent, _ := util.FullPath(*m.metaFolder).DirAndName()
|
||||
if util.FileExists(string(parent)) && !util.FileExists(*m.metaFolder) {
|
||||
os.MkdirAll(*m.metaFolder, 0755)
|
||||
if err := os.MkdirAll(*m.metaFolder, 0755); err != nil {
|
||||
glog.Fatalf("Could not create Meta Folder %s: %v", *m.metaFolder, err)
|
||||
}
|
||||
}
|
||||
if err := util.TestFolderWritable(util.ResolvePath(*m.metaFolder)); err != nil {
|
||||
glog.Fatalf("Check Meta Folder (-mdir) Writable %s : %s", *m.metaFolder, err)
|
||||
@@ -324,11 +326,26 @@ func startMaster(masterOption MasterOptions, masterWhiteList []string) {
|
||||
var tlsConfig *tls.Config
|
||||
if useMTLS {
|
||||
tlsConfig = security.LoadClientTLSHTTP(clientCertFile)
|
||||
security.FixTlsConfig(util.GetViper(), tlsConfig)
|
||||
if err := security.FixTlsConfig(util.GetViper(), tlsConfig); err != nil {
|
||||
glog.Fatalf("failed to fix TLS config: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
if useTLS {
|
||||
go newHttpServer(r, tlsConfig).ServeTLS(masterListener, certFile, keyFile)
|
||||
getCert, certProvider, err := security.NewReloadingServerCertificate(certFile, keyFile)
|
||||
if err != nil {
|
||||
glog.Fatalf("failed to load master HTTPS certificate: %v", err)
|
||||
}
|
||||
// Master runs ServeTLS in a goroutine and this function then blocks
|
||||
// on shutdownCtx / select{}; tie the pem refresh goroutine to the
|
||||
// existing interrupt hook instead of a local defer that would fire
|
||||
// while the server is still running.
|
||||
grace.OnInterrupt(certProvider.Close)
|
||||
if tlsConfig == nil {
|
||||
tlsConfig = &tls.Config{}
|
||||
}
|
||||
tlsConfig.GetCertificate = getCert
|
||||
go newHttpServer(r, tlsConfig).ServeTLS(masterListener, "", "")
|
||||
} else {
|
||||
go newHttpServer(r, nil).Serve(masterListener)
|
||||
}
|
||||
|
||||
+13
-9
@@ -82,11 +82,11 @@ var (
|
||||
// goroutines (registered via onMiniClientsShutdown / trackMiniClient) to
|
||||
// drain.
|
||||
type miniClientsState struct {
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
wg sync.WaitGroup
|
||||
preCancelMu sync.Mutex
|
||||
preCancelFns []func()
|
||||
ctx context.Context
|
||||
cancel context.CancelFunc
|
||||
wg sync.WaitGroup
|
||||
preCancelMu sync.Mutex
|
||||
preCancelFns []func()
|
||||
}
|
||||
|
||||
var miniClients *miniClientsState
|
||||
@@ -311,7 +311,6 @@ func initMiniFilerFlags() {
|
||||
miniFilerOptions.allowedOrigins = cmdMini.Flag.String("filer.allowedOrigins", "*", "comma separated list of allowed origins")
|
||||
miniFilerOptions.exposeDirectoryData = cmdMini.Flag.Bool("filer.exposeDirectoryData", true, "whether to return directory metadata and content in Filer UI")
|
||||
miniFilerOptions.tusBasePath = cmdMini.Flag.String("filer.tusBasePath", "/.tus", "TUS resumable upload endpoint base path")
|
||||
miniFilerOptions.mountPeerRegistryEnable = cmdMini.Flag.Bool("filer.mount.p2p", true, "accept MountRegister/MountList RPCs from weed mount clients for peer chunk sharing (tier 1). Idle cost is near-zero; set false to disable.")
|
||||
}
|
||||
|
||||
// initMiniVolumeFlags initializes Volume server flag options
|
||||
@@ -808,8 +807,11 @@ func applyConfigFileOptions(options map[string]string) {
|
||||
if flag != nil {
|
||||
// Only set if not already set (by command line)
|
||||
if flag.Value.String() == flag.DefValue {
|
||||
flag.Value.Set(value)
|
||||
glog.V(2).Infof("Applied config file option: %s=%s", key, value)
|
||||
if err := flag.Value.Set(value); err != nil {
|
||||
glog.Warningf("Failed to apply config file option: %s=%s: %v", key, value, err)
|
||||
} else {
|
||||
glog.V(2).Infof("Applied config file option: %s=%s", key, value)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1022,7 +1024,9 @@ func runMini(cmd *Command, args []string) bool {
|
||||
printWelcomeMessage()
|
||||
|
||||
// Save configuration to file for persistence and documentation
|
||||
saveMiniConfiguration(*miniDataFolders)
|
||||
if err := saveMiniConfiguration(*miniDataFolders); err != nil {
|
||||
glog.Warningf("failed to save mini configuration in %s: %v", *miniDataFolders, err)
|
||||
}
|
||||
|
||||
if MiniClusterCtx != nil {
|
||||
<-MiniClusterCtx.Done()
|
||||
|
||||
@@ -166,7 +166,9 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
unmount.Unmount(dir)
|
||||
if err := unmount.Unmount(dir); err != nil {
|
||||
glog.V(1).Infof("pre-mount cleanup unmount %s: %v", dir, err)
|
||||
}
|
||||
|
||||
// start on local unix socket
|
||||
if *option.localSocket == "" {
|
||||
@@ -186,7 +188,9 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
|
||||
// detect mount folder mode
|
||||
if *option.dirAutoCreate {
|
||||
os.MkdirAll(dir, os.FileMode(0777)&^umask)
|
||||
if err := os.MkdirAll(dir, os.FileMode(0777)&^umask); err != nil {
|
||||
glog.Fatalf("failed to create directory %s:%v", dir, err)
|
||||
}
|
||||
}
|
||||
fileInfo, err := os.Stat(dir)
|
||||
|
||||
@@ -357,8 +361,8 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
WritebackCache: option.writebackCache != nil && *option.writebackCache,
|
||||
PosixDirNlink: option.posixDirNlink != nil && *option.posixDirNlink,
|
||||
// Peer chunk sharing
|
||||
PeerEnabled: option.peerEnabled != nil && *option.peerEnabled,
|
||||
PeerListen: peerStringOrEmpty(option.peerListen),
|
||||
PeerEnabled: option.peerEnabled != nil && *option.peerEnabled,
|
||||
PeerListen: peerStringOrEmpty(option.peerListen),
|
||||
PeerAdvertise: peerStringOrEmpty(option.peerAdvertise),
|
||||
PeerDataCenter: peerStringOrEmpty(option.peerDataCenter),
|
||||
PeerRack: peerStringOrEmpty(option.peerRack),
|
||||
@@ -381,7 +385,9 @@ func RunMount(option *MountOptions, umask os.FileMode) bool {
|
||||
glog.Fatalf("Mount fail: %v", err)
|
||||
}
|
||||
grace.OnInterrupt(func() {
|
||||
unmount.Unmount(dir)
|
||||
if err := unmount.Unmount(dir); err != nil {
|
||||
glog.Errorf("failed to unmount %s: %v", dir, err)
|
||||
}
|
||||
})
|
||||
|
||||
if mountOptions.fuseCommandPid != 0 {
|
||||
|
||||
@@ -3,6 +3,7 @@ package command
|
||||
import (
|
||||
"github.com/seaweedfs/seaweedfs/weed/mq/agent"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/mq_agent_pb"
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/reflection"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
@@ -84,7 +85,9 @@ func (mqAgentOpt *MessageQueueAgentOptions) startQueueAgent() bool {
|
||||
}
|
||||
|
||||
glog.Infof("Start Seaweed Message Queue Agent on %s:%d", *mqAgentOpt.ip, *mqAgentOpt.port)
|
||||
grpcS.Serve(grpcL)
|
||||
if err := grpcS.Serve(grpcL); err != nil && err != grpc.ErrServerStopped {
|
||||
glog.Errorf("MQ Agent failed to start: %v", err)
|
||||
}
|
||||
|
||||
return true
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
package command
|
||||
|
||||
import (
|
||||
"google.golang.org/grpc"
|
||||
"google.golang.org/grpc/reflection"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
@@ -109,14 +110,16 @@ func (mqBrokerOpt *MessageQueueBrokerOptions) startQueueServer() bool {
|
||||
reflection.Register(localGrpcS)
|
||||
go func() {
|
||||
glog.V(0).Infof("MQ Broker listening on localhost:%d", *mqBrokerOpt.port)
|
||||
if err := localGrpcS.Serve(localL); err != nil {
|
||||
if err := localGrpcS.Serve(localL); err != nil && err != grpc.ErrServerStopped {
|
||||
glog.Errorf("MQ Broker localhost listener error: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
glog.V(0).Infof("MQ Broker listening on %s:%d", *mqBrokerOpt.ip, *mqBrokerOpt.port)
|
||||
grpcS.Serve(grpcL)
|
||||
if err := grpcS.Serve(grpcL); err != nil && err != grpc.ErrServerStopped {
|
||||
glog.Errorf("Failed to serve MQ Broker: %v", err)
|
||||
}
|
||||
|
||||
return true
|
||||
|
||||
|
||||
@@ -23,6 +23,7 @@ type NfsOptions struct {
|
||||
readOnly *bool
|
||||
allowedClients *string
|
||||
volumeServerAccess *string
|
||||
portmapBind *string
|
||||
}
|
||||
|
||||
func init() {
|
||||
@@ -34,6 +35,7 @@ func init() {
|
||||
nfsStandaloneOptions.readOnly = cmdNfs.Flag.Bool("readOnly", false, "export the filer path as read only")
|
||||
nfsStandaloneOptions.allowedClients = cmdNfs.Flag.String("allowedClients", "", "comma-separated client IPs, hostnames, or CIDRs allowed to connect")
|
||||
nfsStandaloneOptions.volumeServerAccess = cmdNfs.Flag.String("volumeServerAccess", "direct", "access volume servers by [direct|publicUrl|filerProxy]")
|
||||
nfsStandaloneOptions.portmapBind = cmdNfs.Flag.String("portmap.bind", "", "when set, bind a built-in portmap v2 responder on <ip>:111 so plain `mount -t nfs` works without client-side portmap bypass. Empty disables it. Binding port 111 requires root or CAP_NET_BIND_SERVICE and must not conflict with a system rpcbind.")
|
||||
}
|
||||
|
||||
var cmdNfs = &Command{
|
||||
@@ -53,6 +55,26 @@ Safer defaults (since export ACLs are still not implemented):
|
||||
|
||||
Override -ip.bind to a routable address only after you have reviewed
|
||||
-allowedClients and the readiness of the rest of your deployment.
|
||||
|
||||
Mounting from a Linux client
|
||||
----------------------------
|
||||
The server does not run portmap/rpcbind by default. That means Linux
|
||||
mount.nfs, which queries portmap on port 111 first, will fail with
|
||||
"portmap query failed" against the plain form:
|
||||
|
||||
mount -t nfs -o nfsvers=3,nolock <host>:/export /mnt
|
||||
|
||||
Either tell the client to bypass portmap:
|
||||
|
||||
mount -t nfs -o nfsvers=3,nolock,port=2049,mountport=2049,\
|
||||
proto=tcp,mountproto=tcp <host>:/export /mnt
|
||||
|
||||
or enable the built-in portmap responder on the server:
|
||||
|
||||
weed nfs ... -portmap.bind=0.0.0.0
|
||||
|
||||
Binding port 111 requires root or CAP_NET_BIND_SERVICE and must not
|
||||
collide with a system rpcbind.
|
||||
`,
|
||||
}
|
||||
|
||||
@@ -85,6 +107,7 @@ func runNfs(cmd *Command, args []string) bool {
|
||||
AllowedClients: util.StringSplit(*nfsStandaloneOptions.allowedClients, ","),
|
||||
VolumeServerAccess: *nfsStandaloneOptions.volumeServerAccess,
|
||||
GrpcDialOption: grpcDialOption,
|
||||
PortmapBind: *nfsStandaloneOptions.portmapBind,
|
||||
})
|
||||
if err != nil {
|
||||
glog.Errorf("NFS Server startup error: %v", err)
|
||||
|
||||
+8
-21
@@ -15,8 +15,6 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/gorilla/mux"
|
||||
"google.golang.org/grpc/credentials/tls/certprovider"
|
||||
"google.golang.org/grpc/credentials/tls/certprovider/pemfile"
|
||||
"google.golang.org/grpc/reflection"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
@@ -62,7 +60,6 @@ type S3Options struct {
|
||||
localFilerSocket *string
|
||||
dataCenter *string
|
||||
localSocket *string
|
||||
certProvider certprovider.Provider
|
||||
idleTimeout *int
|
||||
concurrentUploadLimitMB *int
|
||||
concurrentFileUploadLimit *int
|
||||
@@ -228,15 +225,6 @@ func runS3(cmd *Command, args []string) bool {
|
||||
|
||||
}
|
||||
|
||||
// GetCertificateWithUpdate Auto refreshing TSL certificate
|
||||
func (s3opt *S3Options) GetCertificateWithUpdate(*tls.ClientHelloInfo) (*tls.Certificate, error) {
|
||||
certs, err := s3opt.certProvider.KeyMaterial(context.Background())
|
||||
if certs == nil {
|
||||
return nil, err
|
||||
}
|
||||
return &certs.Certs[0], err
|
||||
}
|
||||
|
||||
// resolveExternalUrl returns the external URL from the flag or falls back to the S3_EXTERNAL_URL env var.
|
||||
func (s3opt *S3Options) resolveExternalUrl() string {
|
||||
if s3opt.externalUrl != nil && *s3opt.externalUrl != "" {
|
||||
@@ -376,7 +364,9 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
if err != nil {
|
||||
glog.Fatalf("Failed to listen on %s: %v", localSocket, err)
|
||||
}
|
||||
newHttpServer(router, nil).Serve(s3SocketListener)
|
||||
if err := newHttpServer(router, nil).Serve(s3SocketListener); err != nil && err != http.ErrServerClosed {
|
||||
glog.Fatalf("Failed to start S3 http server: %v", err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
@@ -415,14 +405,11 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
glog.Fatalf("S3 API Server error: -s3.port.https (%d) cannot be the same as -s3.port (%d)", *s3opt.portHttps, *s3opt.port)
|
||||
}
|
||||
|
||||
pemfileOptions := pemfile.Options{
|
||||
CertFile: *s3opt.tlsCertificate,
|
||||
KeyFile: *s3opt.tlsPrivateKey,
|
||||
RefreshDuration: security.CredRefreshingInterval,
|
||||
}
|
||||
if s3opt.certProvider, err = pemfile.NewProvider(pemfileOptions); err != nil {
|
||||
glog.Fatalf("pemfile.NewProvider(%v) failed: %v", pemfileOptions, err)
|
||||
getCert, certProvider, err := security.NewReloadingServerCertificate(*s3opt.tlsCertificate, *s3opt.tlsPrivateKey)
|
||||
if err != nil {
|
||||
glog.Fatalf("S3 API Server failed to load HTTPS certificate: %v", err)
|
||||
}
|
||||
grace.OnInterrupt(certProvider.Close)
|
||||
|
||||
caCertPool := x509.NewCertPool()
|
||||
if *s3opt.tlsCACertificate != "" {
|
||||
@@ -440,7 +427,7 @@ func (s3opt *S3Options) startS3Server() bool {
|
||||
}
|
||||
|
||||
tlsConfig := &tls.Config{
|
||||
GetCertificate: s3opt.GetCertificateWithUpdate,
|
||||
GetCertificate: getCert,
|
||||
ClientAuth: clientAuth,
|
||||
ClientCAs: caCertPool,
|
||||
}
|
||||
|
||||
@@ -130,7 +130,6 @@ func init() {
|
||||
filerOptions.diskType = cmdServer.Flag.String("filer.disk", "", "[hdd|ssd|<tag>] hard drive or solid state drive or any tag")
|
||||
filerOptions.exposeDirectoryData = cmdServer.Flag.Bool("filer.exposeDirectoryData", true, "expose directory data via filer. If false, filer UI will be innaccessible.")
|
||||
filerOptions.tusBasePath = cmdServer.Flag.String("filer.tusBasePath", "/.tus", "TUS resumable upload endpoint base path (e.g., /.tus)")
|
||||
filerOptions.mountPeerRegistryEnable = cmdServer.Flag.Bool("filer.mount.p2p", true, "accept MountRegister/MountList RPCs from weed mount clients for peer chunk sharing (tier 1). Idle cost is near-zero; set false to disable.")
|
||||
|
||||
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")
|
||||
|
||||
+33
-6
@@ -2,6 +2,7 @@ package command
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"net/http"
|
||||
httppprof "net/http/pprof"
|
||||
@@ -312,7 +313,7 @@ func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, v
|
||||
}
|
||||
|
||||
// starting the cluster http server
|
||||
clusterHttpServer := v.startClusterHttpService(volumeMux)
|
||||
clusterHttpServer, closeCert := v.startClusterHttpService(volumeMux)
|
||||
|
||||
grace.OnReload(volumeServer.LoadNewVolumes)
|
||||
grace.OnReload(volumeServer.Reload)
|
||||
@@ -329,6 +330,9 @@ func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, v
|
||||
}
|
||||
|
||||
shutdown(publicHttpDown, clusterHttpServer, grpcS, volumeServer)
|
||||
if closeCert != nil {
|
||||
closeCert()
|
||||
}
|
||||
stopChan <- true
|
||||
})
|
||||
|
||||
@@ -337,6 +341,9 @@ func (v VolumeServerOptions) startVolumeServer(volumeFolders, maxVolumeCounts, v
|
||||
case <-stopChan:
|
||||
case <-v.shutdownCtx.Done():
|
||||
shutdown(publicHttpDown, clusterHttpServer, grpcS, volumeServer)
|
||||
if closeCert != nil {
|
||||
closeCert()
|
||||
}
|
||||
}
|
||||
} else {
|
||||
select {
|
||||
@@ -442,7 +449,13 @@ func (v VolumeServerOptions) startPublicHttpService(handler http.Handler) httpdo
|
||||
return publicHttpDown
|
||||
}
|
||||
|
||||
func (v VolumeServerOptions) startClusterHttpService(handler http.Handler) httpdown.Server {
|
||||
// startClusterHttpService starts the volume cluster HTTP server and
|
||||
// returns it along with a close func for the cert reloader's refresh
|
||||
// goroutine (nil when HTTPS is disabled). The caller is responsible
|
||||
// for invoking the close func on every shutdown path — both the
|
||||
// SIGTERM/grace.OnInterrupt path and the shutdownCtx path used by
|
||||
// mini/integration tests.
|
||||
func (v VolumeServerOptions) startClusterHttpService(handler http.Handler) (httpdown.Server, func()) {
|
||||
var (
|
||||
certFile, keyFile string
|
||||
)
|
||||
@@ -461,14 +474,28 @@ func (v VolumeServerOptions) startClusterHttpService(handler http.Handler) httpd
|
||||
httpDown := httpdown.HTTP{
|
||||
KillTimeout: time.Minute,
|
||||
StopTimeout: 30 * time.Second,
|
||||
CertFile: certFile,
|
||||
KeyFile: keyFile}
|
||||
}
|
||||
httpS := &http.Server{Handler: handler}
|
||||
|
||||
if viper.GetString("https.volume.ca") != "" {
|
||||
clientCertFile := viper.GetString("https.volume.ca")
|
||||
httpS.TLSConfig = security.LoadClientTLSHTTP(clientCertFile)
|
||||
security.FixTlsConfig(util.GetViper(), httpS.TLSConfig)
|
||||
if err := security.FixTlsConfig(util.GetViper(), httpS.TLSConfig); err != nil {
|
||||
glog.Fatalf("Could not fix TLS config: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
var closeCert func()
|
||||
if certFile != "" && keyFile != "" {
|
||||
getCert, certProvider, err := security.NewReloadingServerCertificate(certFile, keyFile)
|
||||
if err != nil {
|
||||
glog.Fatalf("Volume server failed to load TLS certificate: %v", err)
|
||||
}
|
||||
closeCert = certProvider.Close
|
||||
if httpS.TLSConfig == nil {
|
||||
httpS.TLSConfig = &tls.Config{}
|
||||
}
|
||||
httpS.TLSConfig.GetCertificate = getCert
|
||||
}
|
||||
|
||||
clusterHttpServer := httpDown.Serve(httpS, listener)
|
||||
@@ -477,5 +504,5 @@ func (v VolumeServerOptions) startClusterHttpService(handler http.Handler) httpd
|
||||
glog.Fatalf("Volume server fail to serve: %v", e)
|
||||
}
|
||||
}()
|
||||
return clusterHttpServer
|
||||
return clusterHttpServer, closeCert
|
||||
}
|
||||
@@ -2,6 +2,7 @@ package command
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
@@ -150,7 +151,13 @@ func (wo *WebDavOption) startWebDav() bool {
|
||||
|
||||
if *wo.tlsPrivateKey != "" {
|
||||
glog.V(0).Infof("Start Seaweed WebDav Server %s at https %s", version.Version(), listenAddress)
|
||||
if err = httpS.ServeTLS(webDavListener, *wo.tlsCertificate, *wo.tlsPrivateKey); err != nil && err != http.ErrServerClosed {
|
||||
getCert, certProvider, err := security.NewReloadingServerCertificate(*wo.tlsCertificate, *wo.tlsPrivateKey)
|
||||
if err != nil {
|
||||
glog.Fatalf("WebDav Server failed to load TLS certificate: %v", err)
|
||||
}
|
||||
defer certProvider.Close()
|
||||
httpS.TLSConfig = &tls.Config{GetCertificate: getCert}
|
||||
if err = httpS.ServeTLS(webDavListener, "", ""); err != nil && err != http.ErrServerClosed {
|
||||
glog.Fatalf("WebDav Server Fail to serve: %v", err)
|
||||
}
|
||||
} else {
|
||||
|
||||
@@ -305,6 +305,20 @@ func (cm *CredentialManager) ListUserInlinePolicies(ctx context.Context, userNam
|
||||
return nil, nil
|
||||
}
|
||||
|
||||
// RenameUser atomically renames a user along with all FK-backed
|
||||
// dependents (credentials, inline policies, ...) when the underlying
|
||||
// store implements UserRenamer. Returns false if the store does not
|
||||
// support an atomic rename, in which case the caller is expected to
|
||||
// fall back to its own best-effort path. A returned non-nil error
|
||||
// always means the rename was attempted and failed.
|
||||
func (cm *CredentialManager) RenameUser(ctx context.Context, oldName, newName string) (bool, error) {
|
||||
store, ok := cm.Store.(UserRenamer)
|
||||
if !ok {
|
||||
return false, nil
|
||||
}
|
||||
return true, store.RenameUser(ctx, oldName, newName)
|
||||
}
|
||||
|
||||
// LoadS3ConfigFile reads a static S3 identity config file and registers
|
||||
// the identities so they appear in LoadConfiguration and listing results.
|
||||
func (cm *CredentialManager) LoadS3ConfigFile(path string) error {
|
||||
|
||||
@@ -148,5 +148,17 @@ type InlinePolicyStore interface {
|
||||
ListUserInlinePolicies(ctx context.Context, userName string) ([]string, error)
|
||||
}
|
||||
|
||||
// UserRenamer is an optional interface for credential stores that can
|
||||
// atomically rename a user along with all rows that reference the old
|
||||
// username (credentials, inline policies, etc). Backends with referential
|
||||
// integrity (e.g. PostgreSQL with ON DELETE CASCADE foreign keys on
|
||||
// user_inline_policies) MUST implement this so the IAM rename path can
|
||||
// move the dependents within a single transaction; copying them via
|
||||
// per-row Put / Get / Delete calls would violate the FK at statement
|
||||
// time because the new user row does not yet exist.
|
||||
type UserRenamer interface {
|
||||
RenameUser(ctx context.Context, oldName, newName string) error
|
||||
}
|
||||
|
||||
// Stores holds all available credential store implementations
|
||||
var Stores []CredentialStore
|
||||
@@ -3,6 +3,9 @@ package grpc
|
||||
import (
|
||||
"context"
|
||||
|
||||
"google.golang.org/grpc/codes"
|
||||
"google.golang.org/grpc/status"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
)
|
||||
@@ -50,6 +53,12 @@ func (store *IamGrpcStore) GetUser(ctx context.Context, username string) (*iam_p
|
||||
identity = resp.Identity
|
||||
return nil
|
||||
})
|
||||
// The filer-side handler returns gRPC NotFound when the user is absent;
|
||||
// translate back to the package sentinel so callers can use
|
||||
// errors.Is(err, credential.ErrUserNotFound) uniformly across stores.
|
||||
if err != nil && status.Code(err) == codes.NotFound {
|
||||
return nil, credential.ErrUserNotFound
|
||||
}
|
||||
return identity, err
|
||||
}
|
||||
|
||||
|
||||
@@ -176,6 +176,46 @@ func (store *MemoryStore) DeleteUser(ctx context.Context, username string) error
|
||||
|
||||
// Remove user
|
||||
delete(store.users, username)
|
||||
delete(store.inlinePolicies, username)
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// RenameUser implements credential.UserRenamer for the memory store.
|
||||
// Renames the user and re-points access-key and inline-policy indexes
|
||||
// to the new name. The whole operation is performed under the store
|
||||
// lock so it is atomic with respect to concurrent reads.
|
||||
func (store *MemoryStore) RenameUser(ctx context.Context, oldName, newName string) error {
|
||||
store.mu.Lock()
|
||||
defer store.mu.Unlock()
|
||||
|
||||
if !store.initialized {
|
||||
return fmt.Errorf("store not initialized")
|
||||
}
|
||||
if oldName == newName {
|
||||
return nil
|
||||
}
|
||||
|
||||
user, exists := store.users[oldName]
|
||||
if !exists {
|
||||
return credential.ErrUserNotFound
|
||||
}
|
||||
if _, clash := store.users[newName]; clash {
|
||||
return credential.ErrUserAlreadyExists
|
||||
}
|
||||
|
||||
user.Name = newName
|
||||
store.users[newName] = user
|
||||
delete(store.users, oldName)
|
||||
|
||||
for _, cred := range user.Credentials {
|
||||
store.accessKeys[cred.AccessKey] = newName
|
||||
}
|
||||
|
||||
if policies, ok := store.inlinePolicies[oldName]; ok {
|
||||
store.inlinePolicies[newName] = policies
|
||||
delete(store.inlinePolicies, oldName)
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -173,3 +173,23 @@ func (store *MemoryStore) ListUserInlinePolicies(ctx context.Context, userName s
|
||||
}
|
||||
return names, nil
|
||||
}
|
||||
|
||||
// LoadInlinePolicies returns all inline policies keyed by username then policy name.
|
||||
func (store *MemoryStore) LoadInlinePolicies(ctx context.Context) (map[string]map[string]policy_engine.PolicyDocument, error) {
|
||||
store.mu.RLock()
|
||||
defer store.mu.RUnlock()
|
||||
|
||||
if !store.initialized {
|
||||
return nil, fmt.Errorf("store not initialized")
|
||||
}
|
||||
|
||||
result := make(map[string]map[string]policy_engine.PolicyDocument, len(store.inlinePolicies))
|
||||
for userName, userPolicies := range store.inlinePolicies {
|
||||
copied := make(map[string]policy_engine.PolicyDocument, len(userPolicies))
|
||||
for policyName, doc := range userPolicies {
|
||||
copied[policyName] = doc
|
||||
}
|
||||
result[userName] = copied
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
@@ -27,7 +27,7 @@ func (store *PostgresStore) CreateGroup(ctx context.Context, group *iam_pb.Group
|
||||
|
||||
_, err = store.db.ExecContext(ctx,
|
||||
`INSERT INTO groups (name, members, policy_names, disabled) VALUES ($1, $2, $3, $4)`,
|
||||
group.Name, membersJSON, policyNamesJSON, group.Disabled)
|
||||
group.Name, jsonbParam(membersJSON), jsonbParam(policyNamesJSON), group.Disabled)
|
||||
if err != nil {
|
||||
var pgErr *pgconn.PgError
|
||||
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
|
||||
@@ -112,7 +112,7 @@ func (store *PostgresStore) UpdateGroup(ctx context.Context, group *iam_pb.Group
|
||||
|
||||
result, err := store.db.ExecContext(ctx,
|
||||
`UPDATE groups SET members = $1, policy_names = $2, disabled = $3, updated_at = CURRENT_TIMESTAMP WHERE name = $4`,
|
||||
membersJSON, policyNamesJSON, group.Disabled, group.Name)
|
||||
jsonbParam(membersJSON), jsonbParam(policyNamesJSON), group.Disabled, group.Name)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to update group: %w", err)
|
||||
}
|
||||
|
||||
@@ -7,6 +7,7 @@ import (
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
)
|
||||
|
||||
@@ -17,9 +18,9 @@ func (store *PostgresStore) LoadConfiguration(ctx context.Context) (*iam_pb.S3Ap
|
||||
|
||||
config := &iam_pb.S3ApiConfiguration{}
|
||||
|
||||
// Query all users
|
||||
rows, err := store.db.QueryContext(ctx, "SELECT username, email, account_data, actions, policy_names FROM users")
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: LoadConfiguration query failed: %v", err)
|
||||
return nil, fmt.Errorf("failed to query users: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
@@ -29,6 +30,7 @@ func (store *PostgresStore) LoadConfiguration(ctx context.Context) (*iam_pb.S3Ap
|
||||
var accountDataJSON, actionsJSON, policyNamesJSON []byte
|
||||
|
||||
if err := rows.Scan(&username, &email, &accountDataJSON, &actionsJSON, &policyNamesJSON); err != nil {
|
||||
glog.Errorf("credential postgres: LoadConfiguration scan failed: %v", err)
|
||||
return nil, fmt.Errorf("failed to scan user row: %w", err)
|
||||
}
|
||||
|
||||
@@ -36,28 +38,24 @@ func (store *PostgresStore) LoadConfiguration(ctx context.Context) (*iam_pb.S3Ap
|
||||
Name: username,
|
||||
}
|
||||
|
||||
// Parse account data
|
||||
if len(accountDataJSON) > 0 {
|
||||
if err := json.Unmarshal(accountDataJSON, &identity.Account); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal account data for user %s: %v", username, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Parse actions
|
||||
if len(actionsJSON) > 0 {
|
||||
if err := json.Unmarshal(actionsJSON, &identity.Actions); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal actions for user %s: %v", username, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Parse policy names
|
||||
if len(policyNamesJSON) > 0 {
|
||||
if err := json.Unmarshal(policyNamesJSON, &identity.PolicyNames); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal policy names for user %s: %v", username, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Query credentials for this user
|
||||
credRows, err := store.db.QueryContext(ctx, "SELECT access_key, secret_key FROM credentials WHERE username = $1", username)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to query credentials for user %s: %v", username, err)
|
||||
@@ -75,11 +73,18 @@ func (store *PostgresStore) LoadConfiguration(ctx context.Context) (*iam_pb.S3Ap
|
||||
SecretKey: secretKey,
|
||||
})
|
||||
}
|
||||
credErr := credRows.Err()
|
||||
credRows.Close()
|
||||
|
||||
if credErr != nil {
|
||||
return nil, fmt.Errorf("failed iterating credential rows for user %s: %w", username, credErr)
|
||||
}
|
||||
config.Identities = append(config.Identities, identity)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("failed iterating user rows: %w", err)
|
||||
}
|
||||
|
||||
glog.V(0).Infof("credential postgres: LoadConfiguration loaded %d identities", len(config.Identities))
|
||||
return config, nil
|
||||
}
|
||||
|
||||
@@ -88,24 +93,20 @@ func (store *PostgresStore) SaveConfiguration(ctx context.Context, config *iam_p
|
||||
return fmt.Errorf("store not configured")
|
||||
}
|
||||
|
||||
// Start transaction
|
||||
tx, err := store.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to begin transaction: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
// Clear existing data
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM credentials"); err != nil {
|
||||
return fmt.Errorf("failed to clear credentials: %w", err)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM users"); err != nil {
|
||||
return fmt.Errorf("failed to clear users: %w", err)
|
||||
// Track which usernames are in the incoming config for pruning
|
||||
configUsernames := make(map[string]bool, len(config.Identities))
|
||||
for _, identity := range config.Identities {
|
||||
configUsernames[identity.Name] = true
|
||||
}
|
||||
|
||||
// Insert all identities
|
||||
// Upsert each user's row.
|
||||
for _, identity := range config.Identities {
|
||||
// Marshal account data
|
||||
var accountDataJSON []byte
|
||||
if identity.Account != nil {
|
||||
accountDataJSON, err = json.Marshal(identity.Account)
|
||||
@@ -114,7 +115,6 @@ func (store *PostgresStore) SaveConfiguration(ctx context.Context, config *iam_p
|
||||
}
|
||||
}
|
||||
|
||||
// Marshal actions
|
||||
var actionsJSON []byte
|
||||
if identity.Actions != nil {
|
||||
actionsJSON, err = json.Marshal(identity.Actions)
|
||||
@@ -123,7 +123,6 @@ func (store *PostgresStore) SaveConfiguration(ctx context.Context, config *iam_p
|
||||
}
|
||||
}
|
||||
|
||||
// Marshal policy names
|
||||
var policyNamesJSON []byte
|
||||
if identity.PolicyNames != nil {
|
||||
policyNamesJSON, err = json.Marshal(identity.PolicyNames)
|
||||
@@ -132,26 +131,98 @@ func (store *PostgresStore) SaveConfiguration(ctx context.Context, config *iam_p
|
||||
}
|
||||
}
|
||||
|
||||
// Insert user
|
||||
_, err := tx.ExecContext(ctx,
|
||||
"INSERT INTO users (username, email, account_data, actions, policy_names) VALUES ($1, $2, $3, $4, $5)",
|
||||
identity.Name, "", accountDataJSON, actionsJSON, policyNamesJSON)
|
||||
// Upsert user — preserves the row (and its CASCADE dependents) if it already exists
|
||||
_, err = tx.ExecContext(ctx,
|
||||
`INSERT INTO users (username, email, account_data, actions, policy_names)
|
||||
VALUES ($1, $2, $3, $4, $5)
|
||||
ON CONFLICT (username) DO UPDATE SET
|
||||
email = EXCLUDED.email,
|
||||
account_data = EXCLUDED.account_data,
|
||||
actions = EXCLUDED.actions,
|
||||
policy_names = EXCLUDED.policy_names,
|
||||
updated_at = CURRENT_TIMESTAMP`,
|
||||
identity.Name, "", jsonbParam(accountDataJSON), jsonbParam(actionsJSON), jsonbParam(policyNamesJSON))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to insert user %s: %v", identity.Name, err)
|
||||
return fmt.Errorf("failed to upsert user %s: %v", identity.Name, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Insert credentials
|
||||
// Prune users no longer in config BEFORE replacing credentials. The
|
||||
// IAM rename path (s3api UpdateUser) renames an identity in place and
|
||||
// keeps its access keys: the renamed user shows up in the incoming
|
||||
// config, the old name shows up in the pruned set. If we inserted the
|
||||
// new credentials first, the renamed user's access keys would still be
|
||||
// owned by the old row in this transaction and the INSERT would
|
||||
// violate the global UNIQUE constraint on credentials.access_key.
|
||||
// CASCADE on the old row releases those keys before the insert.
|
||||
rows, err := tx.QueryContext(ctx, "SELECT username FROM users")
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to list existing users for pruning: %w", err)
|
||||
}
|
||||
var toDelete []string
|
||||
for rows.Next() {
|
||||
var username string
|
||||
if err := rows.Scan(&username); err != nil {
|
||||
rows.Close()
|
||||
return fmt.Errorf("failed to scan username for pruning: %w", err)
|
||||
}
|
||||
if !configUsernames[username] {
|
||||
toDelete = append(toDelete, username)
|
||||
}
|
||||
}
|
||||
scanErr := rows.Err()
|
||||
rows.Close()
|
||||
if scanErr != nil {
|
||||
return fmt.Errorf("failed iterating user rows for pruning: %w", scanErr)
|
||||
}
|
||||
|
||||
if len(toDelete) > 0 {
|
||||
var inlineCount int
|
||||
if err := tx.QueryRowContext(ctx,
|
||||
"SELECT COUNT(*) FROM user_inline_policies WHERE username = ANY($1)",
|
||||
toDelete).Scan(&inlineCount); err != nil {
|
||||
glog.Warningf("credential postgres: SaveConfiguration failed to count inline policies for prune candidates: %v", err)
|
||||
} else if inlineCount > 0 {
|
||||
glog.Warningf("credential postgres: SaveConfiguration pruning %d users will CASCADE-remove %d inline policies; if this was a rename, re-create them under the new name", len(toDelete), inlineCount)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM users WHERE username = ANY($1)", toDelete); err != nil {
|
||||
return fmt.Errorf("failed to prune users: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Two-pass credential replace: first clear every user we are about to
|
||||
// rewrite in a single round-trip, then insert. Doing the per-user delete
|
||||
// + insert in a single pass would violate the global UNIQUE constraint
|
||||
// on credentials.access_key when an access key gets reassigned from one
|
||||
// user to another within the same SaveConfiguration call.
|
||||
usernames := make([]string, 0, len(configUsernames))
|
||||
for name := range configUsernames {
|
||||
usernames = append(usernames, name)
|
||||
}
|
||||
if _, err := tx.ExecContext(ctx, "DELETE FROM credentials WHERE username = ANY($1)", usernames); err != nil {
|
||||
return fmt.Errorf("failed to clear credentials for incoming users: %w", err)
|
||||
}
|
||||
for _, identity := range config.Identities {
|
||||
for _, cred := range identity.Credentials {
|
||||
_, err := tx.ExecContext(ctx,
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"INSERT INTO credentials (username, access_key, secret_key) VALUES ($1, $2, $3)",
|
||||
identity.Name, cred.AccessKey, cred.SecretKey)
|
||||
if err != nil {
|
||||
identity.Name, cred.AccessKey, cred.SecretKey); err != nil {
|
||||
return fmt.Errorf("failed to insert credential for user %s: %v", identity.Name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
if err := tx.Commit(); err != nil {
|
||||
glog.Errorf("credential postgres: SaveConfiguration commit failed: %v", err)
|
||||
return fmt.Errorf("failed to commit SaveConfiguration: %w", err)
|
||||
}
|
||||
|
||||
if len(toDelete) > 0 {
|
||||
glog.Warningf("credential postgres: SaveConfiguration saved %d identities, pruned %d", len(config.Identities), len(toDelete))
|
||||
} else {
|
||||
glog.V(0).Infof("credential postgres: SaveConfiguration saved %d identities", len(config.Identities))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *PostgresStore) CreateUser(ctx context.Context, identity *iam_pb.Identity) error {
|
||||
@@ -159,24 +230,23 @@ func (store *PostgresStore) CreateUser(ctx context.Context, identity *iam_pb.Ide
|
||||
return fmt.Errorf("store not configured")
|
||||
}
|
||||
|
||||
// Check if user already exists
|
||||
var count int
|
||||
err := store.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM users WHERE username = $1", identity.Name).Scan(&count)
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: CreateUser check failed user=%s: %v", identity.Name, err)
|
||||
return fmt.Errorf("failed to check user existence: %w", err)
|
||||
}
|
||||
if count > 0 {
|
||||
glog.V(1).Infof("credential postgres: CreateUser user=%s already exists", identity.Name)
|
||||
return credential.ErrUserAlreadyExists
|
||||
}
|
||||
|
||||
// Start transaction
|
||||
tx, err := store.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to begin transaction: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
// Marshal account data
|
||||
var accountDataJSON []byte
|
||||
if identity.Account != nil {
|
||||
accountDataJSON, err = json.Marshal(identity.Account)
|
||||
@@ -185,7 +255,6 @@ func (store *PostgresStore) CreateUser(ctx context.Context, identity *iam_pb.Ide
|
||||
}
|
||||
}
|
||||
|
||||
// Marshal actions
|
||||
var actionsJSON []byte
|
||||
if identity.Actions != nil {
|
||||
actionsJSON, err = json.Marshal(identity.Actions)
|
||||
@@ -194,7 +263,6 @@ func (store *PostgresStore) CreateUser(ctx context.Context, identity *iam_pb.Ide
|
||||
}
|
||||
}
|
||||
|
||||
// Marshal policy names
|
||||
var policyNamesJSON []byte
|
||||
if identity.PolicyNames != nil {
|
||||
policyNamesJSON, err = json.Marshal(identity.PolicyNames)
|
||||
@@ -203,25 +271,31 @@ func (store *PostgresStore) CreateUser(ctx context.Context, identity *iam_pb.Ide
|
||||
}
|
||||
}
|
||||
|
||||
// Insert user
|
||||
_, err = tx.ExecContext(ctx,
|
||||
"INSERT INTO users (username, email, account_data, actions, policy_names) VALUES ($1, $2, $3, $4, $5)",
|
||||
identity.Name, "", accountDataJSON, actionsJSON, policyNamesJSON)
|
||||
identity.Name, "", jsonbParam(accountDataJSON), jsonbParam(actionsJSON), jsonbParam(policyNamesJSON))
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: CreateUser insert failed user=%s: %v", identity.Name, err)
|
||||
return fmt.Errorf("failed to insert user: %w", err)
|
||||
}
|
||||
|
||||
// Insert credentials
|
||||
for _, cred := range identity.Credentials {
|
||||
_, err = tx.ExecContext(ctx,
|
||||
"INSERT INTO credentials (username, access_key, secret_key) VALUES ($1, $2, $3)",
|
||||
identity.Name, cred.AccessKey, cred.SecretKey)
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: CreateUser insert credential failed user=%s accessKey=%s: %v", identity.Name, cred.AccessKey, err)
|
||||
return fmt.Errorf("failed to insert credential: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
if err := tx.Commit(); err != nil {
|
||||
glog.Errorf("credential postgres: CreateUser commit failed user=%s: %v", identity.Name, err)
|
||||
return fmt.Errorf("failed to commit create user %s: %w", identity.Name, err)
|
||||
}
|
||||
|
||||
glog.V(0).Infof("credential postgres: CreateUser user=%s credentials=%d actions=%d", identity.Name, len(identity.Credentials), len(identity.Actions))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *PostgresStore) GetUser(ctx context.Context, username string) (*iam_pb.Identity, error) {
|
||||
@@ -237,8 +311,10 @@ func (store *PostgresStore) GetUser(ctx context.Context, username string) (*iam_
|
||||
username).Scan(&email, &accountDataJSON, &actionsJSON, &policyNamesJSON)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
glog.V(2).Infof("credential postgres: GetUser user=%s not found", username)
|
||||
return nil, credential.ErrUserNotFound
|
||||
}
|
||||
glog.Errorf("credential postgres: GetUser query failed user=%s: %v", username, err)
|
||||
return nil, fmt.Errorf("failed to query user: %w", err)
|
||||
}
|
||||
|
||||
@@ -246,28 +322,24 @@ func (store *PostgresStore) GetUser(ctx context.Context, username string) (*iam_
|
||||
Name: username,
|
||||
}
|
||||
|
||||
// Parse account data
|
||||
if len(accountDataJSON) > 0 {
|
||||
if err := json.Unmarshal(accountDataJSON, &identity.Account); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal account data: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Parse actions
|
||||
if len(actionsJSON) > 0 {
|
||||
if err := json.Unmarshal(actionsJSON, &identity.Actions); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal actions: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Parse policy names
|
||||
if len(policyNamesJSON) > 0 {
|
||||
if err := json.Unmarshal(policyNamesJSON, &identity.PolicyNames); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal policy names: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// Query credentials
|
||||
rows, err := store.db.QueryContext(ctx, "SELECT access_key, secret_key FROM credentials WHERE username = $1", username)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("failed to query credentials: %w", err)
|
||||
@@ -279,13 +351,16 @@ func (store *PostgresStore) GetUser(ctx context.Context, username string) (*iam_
|
||||
if err := rows.Scan(&accessKey, &secretKey); err != nil {
|
||||
return nil, fmt.Errorf("failed to scan credential: %w", err)
|
||||
}
|
||||
|
||||
identity.Credentials = append(identity.Credentials, &iam_pb.Credential{
|
||||
AccessKey: accessKey,
|
||||
SecretKey: secretKey,
|
||||
})
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("failed iterating credential rows: %w", err)
|
||||
}
|
||||
|
||||
glog.V(2).Infof("credential postgres: GetUser user=%s credentials=%d actions=%d", username, len(identity.Credentials), len(identity.Actions))
|
||||
return identity, nil
|
||||
}
|
||||
|
||||
@@ -294,14 +369,12 @@ func (store *PostgresStore) UpdateUser(ctx context.Context, username string, ide
|
||||
return fmt.Errorf("store not configured")
|
||||
}
|
||||
|
||||
// Start transaction
|
||||
tx, err := store.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to begin transaction: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
// Check if user exists
|
||||
var count int
|
||||
err = tx.QueryRowContext(ctx, "SELECT COUNT(*) FROM users WHERE username = $1", username).Scan(&count)
|
||||
if err != nil {
|
||||
@@ -311,7 +384,6 @@ func (store *PostgresStore) UpdateUser(ctx context.Context, username string, ide
|
||||
return credential.ErrUserNotFound
|
||||
}
|
||||
|
||||
// Marshal account data
|
||||
var accountDataJSON []byte
|
||||
if identity.Account != nil {
|
||||
accountDataJSON, err = json.Marshal(identity.Account)
|
||||
@@ -320,7 +392,6 @@ func (store *PostgresStore) UpdateUser(ctx context.Context, username string, ide
|
||||
}
|
||||
}
|
||||
|
||||
// Marshal actions
|
||||
var actionsJSON []byte
|
||||
if identity.Actions != nil {
|
||||
actionsJSON, err = json.Marshal(identity.Actions)
|
||||
@@ -329,7 +400,6 @@ func (store *PostgresStore) UpdateUser(ctx context.Context, username string, ide
|
||||
}
|
||||
}
|
||||
|
||||
// Marshal policy names
|
||||
var policyNamesJSON []byte
|
||||
if identity.PolicyNames != nil {
|
||||
policyNamesJSON, err = json.Marshal(identity.PolicyNames)
|
||||
@@ -338,21 +408,19 @@ func (store *PostgresStore) UpdateUser(ctx context.Context, username string, ide
|
||||
}
|
||||
}
|
||||
|
||||
// Update user
|
||||
_, err = tx.ExecContext(ctx,
|
||||
"UPDATE users SET email = $2, account_data = $3, actions = $4, policy_names = $5, updated_at = CURRENT_TIMESTAMP WHERE username = $1",
|
||||
username, "", accountDataJSON, actionsJSON, policyNamesJSON)
|
||||
username, "", jsonbParam(accountDataJSON), jsonbParam(actionsJSON), jsonbParam(policyNamesJSON))
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: UpdateUser failed user=%s: %v", username, err)
|
||||
return fmt.Errorf("failed to update user: %w", err)
|
||||
}
|
||||
|
||||
// Delete existing credentials
|
||||
_, err = tx.ExecContext(ctx, "DELETE FROM credentials WHERE username = $1", username)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to delete existing credentials: %w", err)
|
||||
}
|
||||
|
||||
// Insert new credentials
|
||||
for _, cred := range identity.Credentials {
|
||||
_, err = tx.ExecContext(ctx,
|
||||
"INSERT INTO credentials (username, access_key, secret_key) VALUES ($1, $2, $3)",
|
||||
@@ -362,7 +430,13 @@ func (store *PostgresStore) UpdateUser(ctx context.Context, username string, ide
|
||||
}
|
||||
}
|
||||
|
||||
return tx.Commit()
|
||||
if err := tx.Commit(); err != nil {
|
||||
glog.Errorf("credential postgres: UpdateUser commit failed user=%s: %v", username, err)
|
||||
return fmt.Errorf("failed to commit update user %s: %w", username, err)
|
||||
}
|
||||
|
||||
glog.V(0).Infof("credential postgres: UpdateUser user=%s credentials=%d", username, len(identity.Credentials))
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *PostgresStore) DeleteUser(ctx context.Context, username string) error {
|
||||
@@ -372,6 +446,7 @@ func (store *PostgresStore) DeleteUser(ctx context.Context, username string) err
|
||||
|
||||
result, err := store.db.ExecContext(ctx, "DELETE FROM users WHERE username = $1", username)
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: DeleteUser failed user=%s: %v", username, err)
|
||||
return fmt.Errorf("failed to delete user: %w", err)
|
||||
}
|
||||
|
||||
@@ -381,9 +456,86 @@ func (store *PostgresStore) DeleteUser(ctx context.Context, username string) err
|
||||
}
|
||||
|
||||
if rowsAffected == 0 {
|
||||
glog.V(1).Infof("credential postgres: DeleteUser user=%s not found", username)
|
||||
return credential.ErrUserNotFound
|
||||
}
|
||||
|
||||
glog.V(0).Infof("credential postgres: DeleteUser user=%s", username)
|
||||
return nil
|
||||
}
|
||||
|
||||
// RenameUser atomically renames oldName to newName, re-pointing every
|
||||
// FK-backed dependent row in a single transaction. The schema's foreign
|
||||
// keys (credentials.username, user_inline_policies.username) reference
|
||||
// users.username with ON DELETE CASCADE and the default ON UPDATE
|
||||
// NO ACTION, which means a plain UPDATE users SET username = newName
|
||||
// would fail because the children still reference the old name. Instead:
|
||||
// 1. Insert the new users row by copying every non-key column from old.
|
||||
// 2. Re-point the dependent tables (credentials, user_inline_policies)
|
||||
// to the new username — both rows now exist so the FK is satisfied.
|
||||
// 3. Delete the old users row, which has no remaining dependents.
|
||||
//
|
||||
// Implements credential.UserRenamer.
|
||||
func (store *PostgresStore) RenameUser(ctx context.Context, oldName, newName string) error {
|
||||
if !store.configured {
|
||||
return fmt.Errorf("store not configured")
|
||||
}
|
||||
if oldName == newName {
|
||||
return nil
|
||||
}
|
||||
|
||||
tx, err := store.db.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to begin transaction: %w", err)
|
||||
}
|
||||
defer tx.Rollback()
|
||||
|
||||
// Refuse if oldName is missing or newName already exists, so the
|
||||
// caller surfaces a recognisable error instead of a constraint
|
||||
// violation midway through.
|
||||
var oldExists, newExists bool
|
||||
if err := tx.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM users WHERE username = $1)", oldName).Scan(&oldExists); err != nil {
|
||||
return fmt.Errorf("failed to check old user %s: %w", oldName, err)
|
||||
}
|
||||
if !oldExists {
|
||||
return credential.ErrUserNotFound
|
||||
}
|
||||
if err := tx.QueryRowContext(ctx, "SELECT EXISTS(SELECT 1 FROM users WHERE username = $1)", newName).Scan(&newExists); err != nil {
|
||||
return fmt.Errorf("failed to check new user %s: %w", newName, err)
|
||||
}
|
||||
if newExists {
|
||||
return credential.ErrUserAlreadyExists
|
||||
}
|
||||
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
`INSERT INTO users (username, email, account_data, actions, policy_names, created_at, updated_at)
|
||||
SELECT $1, email, account_data, actions, policy_names, created_at, CURRENT_TIMESTAMP
|
||||
FROM users WHERE username = $2`,
|
||||
newName, oldName); err != nil {
|
||||
return fmt.Errorf("failed to insert renamed user %s: %w", newName, err)
|
||||
}
|
||||
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"UPDATE credentials SET username = $1 WHERE username = $2", newName, oldName); err != nil {
|
||||
return fmt.Errorf("failed to re-point credentials to %s: %w", newName, err)
|
||||
}
|
||||
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"UPDATE user_inline_policies SET username = $1 WHERE username = $2", newName, oldName); err != nil {
|
||||
return fmt.Errorf("failed to re-point inline policies to %s: %w", newName, err)
|
||||
}
|
||||
|
||||
if _, err := tx.ExecContext(ctx,
|
||||
"DELETE FROM users WHERE username = $1", oldName); err != nil {
|
||||
return fmt.Errorf("failed to drop old user %s: %w", oldName, err)
|
||||
}
|
||||
|
||||
if err := tx.Commit(); err != nil {
|
||||
glog.Errorf("credential postgres: RenameUser commit failed %s -> %s: %v", oldName, newName, err)
|
||||
return fmt.Errorf("failed to commit rename %s -> %s: %w", oldName, newName, err)
|
||||
}
|
||||
|
||||
glog.V(0).Infof("credential postgres: RenameUser %s -> %s", oldName, newName)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -394,6 +546,7 @@ func (store *PostgresStore) ListUsers(ctx context.Context) ([]string, error) {
|
||||
|
||||
rows, err := store.db.QueryContext(ctx, "SELECT username FROM users ORDER BY username")
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: ListUsers query failed: %v", err)
|
||||
return nil, fmt.Errorf("failed to query users: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
@@ -406,7 +559,11 @@ func (store *PostgresStore) ListUsers(ctx context.Context) ([]string, error) {
|
||||
}
|
||||
usernames = append(usernames, username)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("failed iterating user rows: %w", err)
|
||||
}
|
||||
|
||||
glog.V(1).Infof("credential postgres: ListUsers count=%d", len(usernames))
|
||||
return usernames, nil
|
||||
}
|
||||
|
||||
@@ -419,11 +576,14 @@ func (store *PostgresStore) GetUserByAccessKey(ctx context.Context, accessKey st
|
||||
err := store.db.QueryRowContext(ctx, "SELECT username FROM credentials WHERE access_key = $1", accessKey).Scan(&username)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
glog.V(2).Infof("credential postgres: GetUserByAccessKey accessKey=%s not found", accessKey)
|
||||
return nil, credential.ErrAccessKeyNotFound
|
||||
}
|
||||
glog.Errorf("credential postgres: GetUserByAccessKey query failed accessKey=%s: %v", accessKey, err)
|
||||
return nil, fmt.Errorf("failed to query access key: %w", err)
|
||||
}
|
||||
|
||||
glog.V(2).Infof("credential postgres: GetUserByAccessKey accessKey=%s resolved to user=%s", accessKey, username)
|
||||
return store.GetUser(ctx, username)
|
||||
}
|
||||
|
||||
@@ -432,7 +592,6 @@ func (store *PostgresStore) CreateAccessKey(ctx context.Context, username string
|
||||
return fmt.Errorf("store not configured")
|
||||
}
|
||||
|
||||
// Check if user exists
|
||||
var count int
|
||||
err := store.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM users WHERE username = $1", username).Scan(&count)
|
||||
if err != nil {
|
||||
@@ -442,14 +601,15 @@ func (store *PostgresStore) CreateAccessKey(ctx context.Context, username string
|
||||
return credential.ErrUserNotFound
|
||||
}
|
||||
|
||||
// Insert credential
|
||||
_, err = store.db.ExecContext(ctx,
|
||||
"INSERT INTO credentials (username, access_key, secret_key) VALUES ($1, $2, $3)",
|
||||
username, cred.AccessKey, cred.SecretKey)
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: CreateAccessKey failed user=%s accessKey=%s: %v", username, cred.AccessKey, err)
|
||||
return fmt.Errorf("failed to insert credential: %w", err)
|
||||
}
|
||||
|
||||
glog.V(0).Infof("credential postgres: CreateAccessKey user=%s accessKey=%s", username, cred.AccessKey)
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -462,6 +622,7 @@ func (store *PostgresStore) DeleteAccessKey(ctx context.Context, username string
|
||||
"DELETE FROM credentials WHERE username = $1 AND access_key = $2",
|
||||
username, accessKey)
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: DeleteAccessKey failed user=%s accessKey=%s: %v", username, accessKey, err)
|
||||
return fmt.Errorf("failed to delete access key: %w", err)
|
||||
}
|
||||
|
||||
@@ -471,7 +632,6 @@ func (store *PostgresStore) DeleteAccessKey(ctx context.Context, username string
|
||||
}
|
||||
|
||||
if rowsAffected == 0 {
|
||||
// Check if user exists
|
||||
var count int
|
||||
err = store.db.QueryRowContext(ctx, "SELECT COUNT(*) FROM users WHERE username = $1", username).Scan(&count)
|
||||
if err != nil {
|
||||
@@ -483,22 +643,20 @@ func (store *PostgresStore) DeleteAccessKey(ctx context.Context, username string
|
||||
return credential.ErrAccessKeyNotFound
|
||||
}
|
||||
|
||||
glog.V(0).Infof("credential postgres: DeleteAccessKey user=%s accessKey=%s", username, accessKey)
|
||||
return nil
|
||||
}
|
||||
|
||||
// AttachUserPolicy attaches a managed policy to a user by policy name
|
||||
func (store *PostgresStore) AttachUserPolicy(ctx context.Context, username string, policyName string) error {
|
||||
if !store.configured {
|
||||
return fmt.Errorf("store not configured")
|
||||
}
|
||||
|
||||
// Get user
|
||||
identity, err := store.GetUser(ctx, username)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Verify policy exists
|
||||
policy, err := store.GetPolicy(ctx, policyName)
|
||||
if err != nil {
|
||||
return err
|
||||
@@ -507,31 +665,31 @@ func (store *PostgresStore) AttachUserPolicy(ctx context.Context, username strin
|
||||
return credential.ErrPolicyNotFound
|
||||
}
|
||||
|
||||
// Check if already attached
|
||||
for _, p := range identity.PolicyNames {
|
||||
if p == policyName {
|
||||
return credential.ErrPolicyAlreadyAttached
|
||||
}
|
||||
}
|
||||
|
||||
// Append policy name and update
|
||||
identity.PolicyNames = append(identity.PolicyNames, policyName)
|
||||
return store.UpdateUser(ctx, username, identity)
|
||||
if err := store.UpdateUser(ctx, username, identity); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
glog.V(1).Infof("credential postgres: AttachUserPolicy user=%s policy=%s", username, policyName)
|
||||
return nil
|
||||
}
|
||||
|
||||
// DetachUserPolicy detaches a managed policy from a user
|
||||
func (store *PostgresStore) DetachUserPolicy(ctx context.Context, username string, policyName string) error {
|
||||
if !store.configured {
|
||||
return fmt.Errorf("store not configured")
|
||||
}
|
||||
|
||||
// Get user
|
||||
identity, err := store.GetUser(ctx, username)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
// Find and remove policy
|
||||
found := false
|
||||
var newPolicyNames []string
|
||||
for _, p := range identity.PolicyNames {
|
||||
@@ -547,10 +705,14 @@ func (store *PostgresStore) DetachUserPolicy(ctx context.Context, username strin
|
||||
}
|
||||
|
||||
identity.PolicyNames = newPolicyNames
|
||||
return store.UpdateUser(ctx, username, identity)
|
||||
if err := store.UpdateUser(ctx, username, identity); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
glog.V(1).Infof("credential postgres: DetachUserPolicy user=%s policy=%s", username, policyName)
|
||||
return nil
|
||||
}
|
||||
|
||||
// ListAttachedUserPolicies returns the list of policy names attached to a user
|
||||
func (store *PostgresStore) ListAttachedUserPolicies(ctx context.Context, username string) ([]string, error) {
|
||||
if !store.configured {
|
||||
return nil, fmt.Errorf("store not configured")
|
||||
|
||||
@@ -0,0 +1,154 @@
|
||||
package postgres
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
)
|
||||
|
||||
func (store *PostgresStore) PutUserInlinePolicy(ctx context.Context, userName, policyName string, document policy_engine.PolicyDocument) error {
|
||||
if !store.configured {
|
||||
return fmt.Errorf("store not configured")
|
||||
}
|
||||
|
||||
docJSON, err := json.Marshal(document)
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: PutUserInlinePolicy marshal failed user=%s policy=%s: %v", userName, policyName, err)
|
||||
return fmt.Errorf("failed to marshal policy document: %w", err)
|
||||
}
|
||||
|
||||
_, err = store.db.ExecContext(ctx,
|
||||
`INSERT INTO user_inline_policies (username, policy_name, document)
|
||||
VALUES ($1, $2, $3)
|
||||
ON CONFLICT (username, policy_name)
|
||||
DO UPDATE SET document = $3, updated_at = CURRENT_TIMESTAMP`,
|
||||
userName, policyName, jsonbParam(docJSON))
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: PutUserInlinePolicy failed user=%s policy=%s: %v", userName, policyName, err)
|
||||
return fmt.Errorf("failed to upsert inline policy: %w", err)
|
||||
}
|
||||
|
||||
glog.V(0).Infof("credential postgres: PutUserInlinePolicy user=%s policy=%s", userName, policyName)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *PostgresStore) GetUserInlinePolicy(ctx context.Context, userName, policyName string) (*policy_engine.PolicyDocument, error) {
|
||||
if !store.configured {
|
||||
return nil, fmt.Errorf("store not configured")
|
||||
}
|
||||
|
||||
var docJSON []byte
|
||||
err := store.db.QueryRowContext(ctx,
|
||||
"SELECT document FROM user_inline_policies WHERE username = $1 AND policy_name = $2",
|
||||
userName, policyName).Scan(&docJSON)
|
||||
if err != nil {
|
||||
if err == sql.ErrNoRows {
|
||||
glog.V(2).Infof("credential postgres: GetUserInlinePolicy user=%s policy=%s not found", userName, policyName)
|
||||
return nil, nil
|
||||
}
|
||||
glog.Errorf("credential postgres: GetUserInlinePolicy query failed user=%s policy=%s: %v", userName, policyName, err)
|
||||
return nil, fmt.Errorf("failed to query inline policy: %w", err)
|
||||
}
|
||||
|
||||
var doc policy_engine.PolicyDocument
|
||||
if err := json.Unmarshal(docJSON, &doc); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal inline policy: %w", err)
|
||||
}
|
||||
|
||||
glog.V(2).Infof("credential postgres: GetUserInlinePolicy user=%s policy=%s found", userName, policyName)
|
||||
return &doc, nil
|
||||
}
|
||||
|
||||
func (store *PostgresStore) DeleteUserInlinePolicy(ctx context.Context, userName, policyName string) error {
|
||||
if !store.configured {
|
||||
return fmt.Errorf("store not configured")
|
||||
}
|
||||
|
||||
result, err := store.db.ExecContext(ctx,
|
||||
"DELETE FROM user_inline_policies WHERE username = $1 AND policy_name = $2",
|
||||
userName, policyName)
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: DeleteUserInlinePolicy failed user=%s policy=%s: %v", userName, policyName, err)
|
||||
return fmt.Errorf("failed to delete inline policy: %w", err)
|
||||
}
|
||||
|
||||
rowsAffected, _ := result.RowsAffected()
|
||||
glog.V(0).Infof("credential postgres: DeleteUserInlinePolicy user=%s policy=%s deleted=%d", userName, policyName, rowsAffected)
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *PostgresStore) ListUserInlinePolicies(ctx context.Context, userName string) ([]string, error) {
|
||||
if !store.configured {
|
||||
return nil, fmt.Errorf("store not configured")
|
||||
}
|
||||
|
||||
rows, err := store.db.QueryContext(ctx,
|
||||
"SELECT policy_name FROM user_inline_policies WHERE username = $1 ORDER BY policy_name",
|
||||
userName)
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: ListUserInlinePolicies query failed user=%s: %v", userName, err)
|
||||
return nil, fmt.Errorf("failed to query inline policies: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var names []string
|
||||
for rows.Next() {
|
||||
var name string
|
||||
if err := rows.Scan(&name); err != nil {
|
||||
return nil, fmt.Errorf("failed to scan policy name: %w", err)
|
||||
}
|
||||
names = append(names, name)
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("failed iterating inline policy rows: %w", err)
|
||||
}
|
||||
|
||||
glog.V(1).Infof("credential postgres: ListUserInlinePolicies user=%s count=%d", userName, len(names))
|
||||
return names, nil
|
||||
}
|
||||
|
||||
func (store *PostgresStore) LoadInlinePolicies(ctx context.Context) (map[string]map[string]policy_engine.PolicyDocument, error) {
|
||||
if !store.configured {
|
||||
return nil, fmt.Errorf("store not configured")
|
||||
}
|
||||
|
||||
rows, err := store.db.QueryContext(ctx,
|
||||
"SELECT username, policy_name, document FROM user_inline_policies ORDER BY username, policy_name")
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: LoadInlinePolicies query failed: %v", err)
|
||||
return nil, fmt.Errorf("failed to query inline policies: %w", err)
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
result := make(map[string]map[string]policy_engine.PolicyDocument)
|
||||
count := 0
|
||||
for rows.Next() {
|
||||
var username, policyName string
|
||||
var docJSON []byte
|
||||
if err := rows.Scan(&username, &policyName, &docJSON); err != nil {
|
||||
return nil, fmt.Errorf("failed to scan inline policy row: %w", err)
|
||||
}
|
||||
|
||||
var doc policy_engine.PolicyDocument
|
||||
if err := json.Unmarshal(docJSON, &doc); err != nil {
|
||||
glog.Warningf("credential postgres: LoadInlinePolicies unmarshal failed user=%s policy=%s: %v", username, policyName, err)
|
||||
continue
|
||||
}
|
||||
|
||||
if result[username] == nil {
|
||||
result[username] = make(map[string]policy_engine.PolicyDocument)
|
||||
}
|
||||
result[username][policyName] = doc
|
||||
count++
|
||||
}
|
||||
if err := rows.Err(); err != nil {
|
||||
return nil, fmt.Errorf("failed iterating inline policy rows: %w", err)
|
||||
}
|
||||
|
||||
glog.V(0).Infof("credential postgres: LoadInlinePolicies loaded %d policies for %d users", count, len(result))
|
||||
return result, nil
|
||||
}
|
||||
@@ -78,7 +78,7 @@ func (store *PostgresStore) CreatePolicy(ctx context.Context, name string, docum
|
||||
|
||||
_, err = store.db.ExecContext(ctx,
|
||||
"INSERT INTO policies (name, document) VALUES ($1, $2) ON CONFLICT (name) DO UPDATE SET document = $2, updated_at = CURRENT_TIMESTAMP",
|
||||
name, documentJSON)
|
||||
name, jsonbParam(documentJSON))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to insert policy: %w", err)
|
||||
}
|
||||
@@ -104,7 +104,7 @@ func (store *PostgresStore) UpdatePolicy(ctx context.Context, name string, docum
|
||||
|
||||
result, err := store.db.ExecContext(ctx,
|
||||
"UPDATE policies SET document = $2, updated_at = CURRENT_TIMESTAMP WHERE name = $1",
|
||||
name, documentJSON)
|
||||
name, jsonbParam(documentJSON))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to update policy: %w", err)
|
||||
}
|
||||
|
||||
@@ -33,7 +33,7 @@ func (store *PostgresStore) CreateServiceAccount(ctx context.Context, sa *iam_pb
|
||||
|
||||
_, err = store.db.ExecContext(ctx,
|
||||
"INSERT INTO service_accounts (id, access_key, content) VALUES ($1, $2, $3)",
|
||||
sa.Id, accessKey, data)
|
||||
sa.Id, accessKey, jsonbParam(data))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to insert service account: %w", err)
|
||||
}
|
||||
@@ -63,7 +63,7 @@ func (store *PostgresStore) UpdateServiceAccount(ctx context.Context, id string,
|
||||
|
||||
result, err := store.db.ExecContext(ctx,
|
||||
"UPDATE service_accounts SET access_key = $2, content = $3, updated_at = CURRENT_TIMESTAMP WHERE id = $1",
|
||||
id, accessKey, data)
|
||||
id, accessKey, jsonbParam(data))
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to update service account: %w", err)
|
||||
}
|
||||
|
||||
@@ -3,14 +3,31 @@ package postgres
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential"
|
||||
"github.com/seaweedfs/seaweedfs/weed/glog"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util"
|
||||
|
||||
_ "github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/pgxutil"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultMaxOpenConns = 25
|
||||
defaultMaxIdleConns = 5
|
||||
defaultConnMaxLifetimeSecs = 300
|
||||
)
|
||||
|
||||
// jsonbParam adapts JSON bytes for an ExecContext call against a JSONB
|
||||
// column. Returns nil (so the driver writes SQL NULL) when b is nil or
|
||||
// empty; otherwise returns string(b) so pgx drives it as JSONB text — []byte
|
||||
// would be encoded as bytea under simple_protocol (pgbouncer mode) and
|
||||
// rejected by Postgres with "invalid input syntax for type json".
|
||||
func jsonbParam(b []byte) interface{} {
|
||||
if len(b) == 0 {
|
||||
return nil
|
||||
}
|
||||
return string(b)
|
||||
}
|
||||
|
||||
func init() {
|
||||
credential.Stores = append(credential.Stores, &PostgresStore{})
|
||||
}
|
||||
@@ -37,56 +54,76 @@ func (store *PostgresStore) Initialize(configuration util.Configuration, prefix
|
||||
database := configuration.GetString(prefix + "database")
|
||||
schema := configuration.GetString(prefix + "schema")
|
||||
sslmode := configuration.GetString(prefix + "sslmode")
|
||||
sslcert := configuration.GetString(prefix + "sslcert")
|
||||
sslkey := configuration.GetString(prefix + "sslkey")
|
||||
sslrootcert := configuration.GetString(prefix + "sslrootcert")
|
||||
sslcrl := configuration.GetString(prefix + "sslcrl")
|
||||
pgbouncerCompatible := configuration.GetBool(prefix + "pgbouncer_compatible")
|
||||
maxIdle := configuration.GetInt(prefix + "connection_max_idle")
|
||||
maxOpen := configuration.GetInt(prefix + "connection_max_open")
|
||||
maxLifetimeSeconds := configuration.GetInt(prefix + "connection_max_lifetime_seconds")
|
||||
|
||||
// Set defaults
|
||||
if hostname == "" {
|
||||
hostname = "localhost"
|
||||
}
|
||||
if port == 0 {
|
||||
port = 5432
|
||||
}
|
||||
if schema == "" {
|
||||
schema = "public"
|
||||
}
|
||||
if sslmode == "" {
|
||||
sslmode = "disable"
|
||||
}
|
||||
if maxOpen == 0 {
|
||||
maxOpen = defaultMaxOpenConns
|
||||
}
|
||||
if maxIdle == 0 {
|
||||
maxIdle = defaultMaxIdleConns
|
||||
}
|
||||
if maxLifetimeSeconds == 0 {
|
||||
maxLifetimeSeconds = defaultConnMaxLifetimeSecs
|
||||
}
|
||||
|
||||
// Build pgx-optimized connection string
|
||||
// Note: prefer_simple_protocol=true is only needed for PgBouncer, not direct PostgreSQL connections
|
||||
connStr := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=%s search_path=%s",
|
||||
hostname, port, username, password, database, sslmode, schema)
|
||||
glog.V(0).Infof("credential postgres: initializing store host=%s port=%d user=%s db=%s sslmode=%s pgbouncer=%v",
|
||||
hostname, port, username, database, sslmode, pgbouncerCompatible)
|
||||
|
||||
db, err := sql.Open("pgx", connStr)
|
||||
dsn, adaptedDSN := pgxutil.BuildDSN(pgxutil.DSNOptions{
|
||||
Hostname: hostname,
|
||||
Port: port,
|
||||
User: username,
|
||||
Password: password,
|
||||
Database: database,
|
||||
Schema: schema,
|
||||
SSLMode: sslmode,
|
||||
SSLCert: sslcert,
|
||||
SSLKey: sslkey,
|
||||
SSLRootCert: sslrootcert,
|
||||
SSLCRL: sslcrl,
|
||||
PgBouncerCompatible: pgbouncerCompatible,
|
||||
})
|
||||
|
||||
db, err := pgxutil.OpenDB(dsn, adaptedDSN, pgbouncerCompatible, maxIdle, maxOpen, maxLifetimeSeconds)
|
||||
if err != nil {
|
||||
glog.Errorf("credential postgres: failed to open database: %v", err)
|
||||
return fmt.Errorf("failed to open database: %w", err)
|
||||
}
|
||||
|
||||
// Test connection
|
||||
if err := db.Ping(); err != nil {
|
||||
db.Close()
|
||||
return fmt.Errorf("failed to ping database: %w", err)
|
||||
}
|
||||
|
||||
// Set connection pool settings
|
||||
db.SetMaxOpenConns(25)
|
||||
db.SetMaxIdleConns(5)
|
||||
db.SetConnMaxLifetime(5 * time.Minute)
|
||||
glog.V(0).Infof("credential postgres: connection established")
|
||||
|
||||
store.db = db
|
||||
|
||||
// Create tables if they don't exist
|
||||
if err := store.createTables(); err != nil {
|
||||
db.Close()
|
||||
store.db = nil
|
||||
glog.Errorf("credential postgres: failed to create tables: %v", err)
|
||||
return fmt.Errorf("failed to create tables: %w", err)
|
||||
}
|
||||
|
||||
glog.V(0).Infof("credential postgres: tables verified, store ready")
|
||||
|
||||
store.configured = true
|
||||
return nil
|
||||
}
|
||||
|
||||
func (store *PostgresStore) createTables() error {
|
||||
// Create users table
|
||||
usersTable := `
|
||||
CREATE TABLE IF NOT EXISTS users (
|
||||
username VARCHAR(255) PRIMARY KEY,
|
||||
@@ -100,12 +137,10 @@ func (store *PostgresStore) createTables() error {
|
||||
CREATE INDEX IF NOT EXISTS idx_users_email ON users(email);
|
||||
`
|
||||
|
||||
// Migration: Add policy_names column if it doesn't exist (for existing installations)
|
||||
addPolicyNamesColumn := `
|
||||
ALTER TABLE users ADD COLUMN IF NOT EXISTS policy_names JSONB DEFAULT '[]';
|
||||
`
|
||||
|
||||
// Create credentials table
|
||||
credentialsTable := `
|
||||
CREATE TABLE IF NOT EXISTS credentials (
|
||||
id SERIAL PRIMARY KEY,
|
||||
@@ -118,7 +153,6 @@ func (store *PostgresStore) createTables() error {
|
||||
CREATE INDEX IF NOT EXISTS idx_credentials_access_key ON credentials(access_key);
|
||||
`
|
||||
|
||||
// Create policies table
|
||||
policiesTable := `
|
||||
CREATE TABLE IF NOT EXISTS policies (
|
||||
name VARCHAR(255) PRIMARY KEY,
|
||||
@@ -129,7 +163,6 @@ func (store *PostgresStore) createTables() error {
|
||||
CREATE INDEX IF NOT EXISTS idx_policies_name ON policies(name);
|
||||
`
|
||||
|
||||
// Create service_accounts table
|
||||
serviceAccountsTable := `
|
||||
CREATE TABLE IF NOT EXISTS service_accounts (
|
||||
id VARCHAR(255) PRIMARY KEY,
|
||||
@@ -140,7 +173,18 @@ func (store *PostgresStore) createTables() error {
|
||||
);
|
||||
`
|
||||
|
||||
// Create groups table
|
||||
inlinePoliciesTable := `
|
||||
CREATE TABLE IF NOT EXISTS user_inline_policies (
|
||||
username VARCHAR(255) REFERENCES users(username) ON DELETE CASCADE,
|
||||
policy_name VARCHAR(255) NOT NULL,
|
||||
document JSONB NOT NULL,
|
||||
created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
|
||||
PRIMARY KEY (username, policy_name)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS idx_user_inline_policies_username ON user_inline_policies(username);
|
||||
`
|
||||
|
||||
groupsTable := `
|
||||
CREATE TABLE IF NOT EXISTS groups (
|
||||
name VARCHAR(255) PRIMARY KEY,
|
||||
@@ -152,12 +196,10 @@ func (store *PostgresStore) createTables() error {
|
||||
);
|
||||
`
|
||||
|
||||
// Execute table creation
|
||||
if _, err := store.db.Exec(usersTable); err != nil {
|
||||
return fmt.Errorf("failed to create users table: %w", err)
|
||||
}
|
||||
|
||||
// Run migration to add policy_names column for existing installations
|
||||
if _, err := store.db.Exec(addPolicyNamesColumn); err != nil {
|
||||
return fmt.Errorf("failed to add policy_names column: %w", err)
|
||||
}
|
||||
@@ -174,17 +216,19 @@ func (store *PostgresStore) createTables() error {
|
||||
return fmt.Errorf("failed to create service_accounts table: %w", err)
|
||||
}
|
||||
|
||||
if _, err := store.db.Exec(inlinePoliciesTable); err != nil {
|
||||
return fmt.Errorf("failed to create user_inline_policies table: %w", err)
|
||||
}
|
||||
|
||||
if _, err := store.db.Exec(groupsTable); err != nil {
|
||||
return fmt.Errorf("failed to create groups table: %w", err)
|
||||
}
|
||||
|
||||
// Create index on groups disabled column for filtering
|
||||
groupsDisabledIndex := `CREATE INDEX IF NOT EXISTS idx_groups_disabled ON groups (disabled);`
|
||||
if _, err := store.db.Exec(groupsDisabledIndex); err != nil {
|
||||
return fmt.Errorf("failed to create groups disabled index: %w", err)
|
||||
}
|
||||
|
||||
// Create GIN index on groups members JSONB for membership lookups
|
||||
groupsMembersIndex := `CREATE INDEX IF NOT EXISTS idx_groups_members_gin ON groups USING GIN (members);`
|
||||
if _, err := store.db.Exec(groupsMembersIndex); err != nil {
|
||||
return fmt.Errorf("failed to create groups members index: %w", err)
|
||||
@@ -195,6 +239,7 @@ func (store *PostgresStore) createTables() error {
|
||||
|
||||
func (store *PostgresStore) Shutdown() {
|
||||
if store.db != nil {
|
||||
glog.V(0).Infof("credential postgres: shutting down")
|
||||
store.db.Close()
|
||||
store.db = nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,266 @@
|
||||
package test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential"
|
||||
"github.com/seaweedfs/seaweedfs/weed/credential/memory"
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/seaweedfs/seaweedfs/weed/s3api/policy_engine"
|
||||
|
||||
_ "github.com/seaweedfs/seaweedfs/weed/credential/filer_etc"
|
||||
_ "github.com/seaweedfs/seaweedfs/weed/credential/memory"
|
||||
_ "github.com/seaweedfs/seaweedfs/weed/credential/postgres"
|
||||
)
|
||||
|
||||
func TestInlinePolicyOperations(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
credentialManager, err := credential.NewCredentialManager(credential.StoreTypeMemory, nil, "")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create credential manager: %v", err)
|
||||
}
|
||||
|
||||
store, ok := credentialManager.GetStore().(*memory.MemoryStore)
|
||||
if !ok {
|
||||
t.Fatal("Store is not a memory store")
|
||||
}
|
||||
|
||||
userName := "testuser"
|
||||
policyName := "read-bucket"
|
||||
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:::test-bucket/*"),
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
// Put
|
||||
if err := store.PutUserInlinePolicy(ctx, userName, policyName, doc); err != nil {
|
||||
t.Fatalf("PutUserInlinePolicy failed: %v", err)
|
||||
}
|
||||
|
||||
// Get
|
||||
got, err := store.GetUserInlinePolicy(ctx, userName, policyName)
|
||||
if err != nil {
|
||||
t.Fatalf("GetUserInlinePolicy failed: %v", err)
|
||||
}
|
||||
if got == nil {
|
||||
t.Fatal("GetUserInlinePolicy returned nil")
|
||||
}
|
||||
if got.Version != "2012-10-17" {
|
||||
t.Errorf("Expected version '2012-10-17', got '%s'", got.Version)
|
||||
}
|
||||
if len(got.Statement) != 1 {
|
||||
t.Errorf("Expected 1 statement, got %d", len(got.Statement))
|
||||
}
|
||||
|
||||
// Get non-existent
|
||||
missing, err := store.GetUserInlinePolicy(ctx, userName, "no-such-policy")
|
||||
if err != nil {
|
||||
t.Fatalf("GetUserInlinePolicy for missing policy failed: %v", err)
|
||||
}
|
||||
if missing != nil {
|
||||
t.Error("Expected nil for non-existent policy")
|
||||
}
|
||||
|
||||
// Put second policy, same user
|
||||
doc2 := policy_engine.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy_engine.PolicyStatement{
|
||||
{
|
||||
Effect: policy_engine.PolicyEffectAllow,
|
||||
Action: policy_engine.NewStringOrStringSlice("s3:PutObject"),
|
||||
Resource: policy_engine.NewStringOrStringSlicePtr("arn:aws:s3:::other-bucket/*"),
|
||||
},
|
||||
},
|
||||
}
|
||||
if err := store.PutUserInlinePolicy(ctx, userName, "write-bucket", doc2); err != nil {
|
||||
t.Fatalf("PutUserInlinePolicy second policy failed: %v", err)
|
||||
}
|
||||
|
||||
// List
|
||||
names, err := store.ListUserInlinePolicies(ctx, userName)
|
||||
if err != nil {
|
||||
t.Fatalf("ListUserInlinePolicies failed: %v", err)
|
||||
}
|
||||
if len(names) != 2 {
|
||||
t.Errorf("Expected 2 policies, got %d", len(names))
|
||||
}
|
||||
|
||||
// List for non-existent user
|
||||
emptyNames, err := store.ListUserInlinePolicies(ctx, "nobody")
|
||||
if err != nil {
|
||||
t.Fatalf("ListUserInlinePolicies for missing user failed: %v", err)
|
||||
}
|
||||
if len(emptyNames) != 0 {
|
||||
t.Errorf("Expected 0 policies for missing user, got %d", len(emptyNames))
|
||||
}
|
||||
|
||||
// LoadInlinePolicies (bulk)
|
||||
all, err := store.LoadInlinePolicies(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadInlinePolicies failed: %v", err)
|
||||
}
|
||||
if len(all) != 1 {
|
||||
t.Errorf("Expected 1 user in LoadInlinePolicies, got %d", len(all))
|
||||
}
|
||||
if len(all[userName]) != 2 {
|
||||
t.Errorf("Expected 2 policies for user in LoadInlinePolicies, got %d", len(all[userName]))
|
||||
}
|
||||
|
||||
// Overwrite existing policy (upsert)
|
||||
updatedDoc := policy_engine.PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []policy_engine.PolicyStatement{
|
||||
{
|
||||
Effect: policy_engine.PolicyEffectDeny,
|
||||
Action: policy_engine.NewStringOrStringSlice("s3:GetObject"),
|
||||
Resource: policy_engine.NewStringOrStringSlicePtr("arn:aws:s3:::test-bucket/secret/*"),
|
||||
},
|
||||
},
|
||||
}
|
||||
if err := store.PutUserInlinePolicy(ctx, userName, policyName, updatedDoc); err != nil {
|
||||
t.Fatalf("PutUserInlinePolicy overwrite failed: %v", err)
|
||||
}
|
||||
overwritten, err := store.GetUserInlinePolicy(ctx, userName, policyName)
|
||||
if err != nil {
|
||||
t.Fatalf("GetUserInlinePolicy after overwrite failed: %v", err)
|
||||
}
|
||||
if overwritten.Statement[0].Effect != policy_engine.PolicyEffectDeny {
|
||||
t.Errorf("Expected Deny after overwrite, got %s", overwritten.Statement[0].Effect)
|
||||
}
|
||||
|
||||
// Delete one policy
|
||||
if err := store.DeleteUserInlinePolicy(ctx, userName, policyName); err != nil {
|
||||
t.Fatalf("DeleteUserInlinePolicy failed: %v", err)
|
||||
}
|
||||
deleted, err := store.GetUserInlinePolicy(ctx, userName, policyName)
|
||||
if err != nil {
|
||||
t.Fatalf("GetUserInlinePolicy after delete failed: %v", err)
|
||||
}
|
||||
if deleted != nil {
|
||||
t.Error("Expected nil after delete")
|
||||
}
|
||||
|
||||
// Remaining policy still there
|
||||
remaining, err := store.ListUserInlinePolicies(ctx, userName)
|
||||
if err != nil {
|
||||
t.Fatalf("ListUserInlinePolicies after delete failed: %v", err)
|
||||
}
|
||||
if len(remaining) != 1 {
|
||||
t.Errorf("Expected 1 remaining policy, got %d", len(remaining))
|
||||
}
|
||||
|
||||
// Delete last policy — user entry should be cleaned up
|
||||
if err := store.DeleteUserInlinePolicy(ctx, userName, "write-bucket"); err != nil {
|
||||
t.Fatalf("DeleteUserInlinePolicy last policy failed: %v", err)
|
||||
}
|
||||
allAfter, err := store.LoadInlinePolicies(ctx)
|
||||
if err != nil {
|
||||
t.Fatalf("LoadInlinePolicies after full cleanup failed: %v", err)
|
||||
}
|
||||
if len(allAfter) != 0 {
|
||||
t.Errorf("Expected empty LoadInlinePolicies after cleanup, got %d users", len(allAfter))
|
||||
}
|
||||
}
|
||||
|
||||
// TestMemoryRenameUserMovesIdentityAndPolicies exercises the new
|
||||
// credential.UserRenamer path on the memory store: the identity row,
|
||||
// its access keys, and any inline policies all have to land under the
|
||||
// new name in a single operation.
|
||||
func TestMemoryRenameUserMovesIdentityAndPolicies(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
|
||||
cm, err := credential.NewCredentialManager(credential.StoreTypeMemory, nil, "")
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to create credential manager: %v", err)
|
||||
}
|
||||
|
||||
const (
|
||||
oldName = "renameme"
|
||||
newName = "renamed"
|
||||
policyName = "ReadBucket"
|
||||
)
|
||||
|
||||
cred := &iam_pb.Credential{AccessKey: "AKIA-RENAME", SecretKey: "secret"}
|
||||
if err := cm.CreateUser(ctx, &iam_pb.Identity{
|
||||
Name: oldName,
|
||||
Credentials: []*iam_pb.Credential{cred},
|
||||
}); err != nil {
|
||||
t.Fatalf("CreateUser failed: %v", err)
|
||||
}
|
||||
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/*"),
|
||||
}},
|
||||
}
|
||||
if err := cm.PutUserInlinePolicy(ctx, oldName, policyName, doc); err != nil {
|
||||
t.Fatalf("PutUserInlinePolicy failed: %v", err)
|
||||
}
|
||||
|
||||
supported, err := cm.RenameUser(ctx, oldName, newName)
|
||||
if err != nil {
|
||||
t.Fatalf("RenameUser failed: %v", err)
|
||||
}
|
||||
if !supported {
|
||||
t.Fatal("memory store should implement credential.UserRenamer")
|
||||
}
|
||||
|
||||
if _, err := cm.GetUser(ctx, oldName); err == nil {
|
||||
t.Errorf("expected old user %q to be gone after rename", oldName)
|
||||
}
|
||||
got, err := cm.GetUser(ctx, newName)
|
||||
if err != nil {
|
||||
t.Fatalf("GetUser(%q) after rename failed: %v", newName, err)
|
||||
}
|
||||
if got.Name != newName {
|
||||
t.Errorf("renamed identity name = %q, want %q", got.Name, newName)
|
||||
}
|
||||
if len(got.Credentials) != 1 || got.Credentials[0].AccessKey != cred.AccessKey {
|
||||
t.Errorf("renamed identity should still own its access key, got %+v", got.Credentials)
|
||||
}
|
||||
|
||||
gotByKey, err := cm.GetUserByAccessKey(ctx, cred.AccessKey)
|
||||
if err != nil {
|
||||
t.Fatalf("GetUserByAccessKey failed: %v", err)
|
||||
}
|
||||
if gotByKey == nil || gotByKey.Name != newName {
|
||||
t.Errorf("access key should resolve to %q, got %+v", newName, gotByKey)
|
||||
}
|
||||
|
||||
gotPolicy, err := cm.GetUserInlinePolicy(ctx, newName, policyName)
|
||||
if err != nil {
|
||||
t.Fatalf("GetUserInlinePolicy under new name failed: %v", err)
|
||||
}
|
||||
if gotPolicy == nil {
|
||||
t.Fatal("inline policy should be readable under the new name")
|
||||
}
|
||||
if gotPolicy.Statement[0].Effect != policy_engine.PolicyEffectAllow {
|
||||
t.Errorf("policy effect: got %q want %q", gotPolicy.Statement[0].Effect, policy_engine.PolicyEffectAllow)
|
||||
}
|
||||
stalePolicy, err := cm.GetUserInlinePolicy(ctx, oldName, policyName)
|
||||
if err != nil {
|
||||
t.Fatalf("GetUserInlinePolicy under old name failed: %v", err)
|
||||
}
|
||||
if stalePolicy != nil {
|
||||
t.Errorf("inline policy should be gone from the old name, got %+v", stalePolicy)
|
||||
}
|
||||
|
||||
// Clean up — NewCredentialManager hands out a shared MemoryStore singleton
|
||||
// so leftover state would leak into TestMemoryStoreIntegration.
|
||||
if err := cm.DeleteUserInlinePolicy(ctx, newName, policyName); err != nil {
|
||||
t.Fatalf("DeleteUserInlinePolicy cleanup failed: %v", err)
|
||||
}
|
||||
if err := cm.DeleteUser(ctx, newName); err != nil {
|
||||
t.Fatalf("DeleteUser cleanup failed: %v", err)
|
||||
}
|
||||
}
|
||||
@@ -6,8 +6,14 @@ import (
|
||||
)
|
||||
|
||||
var (
|
||||
PolicyNamePattern = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
|
||||
ServiceAccountIdPattern = regexp.MustCompile(`^sa:[A-Za-z0-9_-]+:[a-z0-9-]+$`)
|
||||
PolicyNamePattern = regexp.MustCompile(`^[A-Za-z0-9_-]+$`)
|
||||
// ServiceAccountIdPattern matches sa:<parent-user>:<uuid>. The parent-user
|
||||
// segment accepts every character allowed in an AWS IAM username
|
||||
// (`[\w+=,.@-]+` per
|
||||
// https://docs.aws.amazon.com/IAM/latest/APIReference/API_User.html)
|
||||
// so service accounts created for users with e.g. `user@example.com`
|
||||
// don't fail validation at the persistence layer.
|
||||
ServiceAccountIdPattern = regexp.MustCompile(`^sa:[A-Za-z0-9_+=,.@-]+:[a-z0-9-]+$`)
|
||||
)
|
||||
|
||||
func ValidatePolicyName(name string) error {
|
||||
|
||||
@@ -0,0 +1,49 @@
|
||||
package credential
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestValidateServiceAccountId(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
id string
|
||||
wantErr bool
|
||||
}{
|
||||
{"simple", "sa:alice:abcdef0123456789", false},
|
||||
{"uppercase parent", "sa:ALICE:abcdef0123456789", false},
|
||||
{"hyphenated uuid suffix", "sa:alice:123e4567-e89b-12d3-a456-426614174000", false},
|
||||
{"with hyphen", "sa:test-user:abcdef0123456789", false},
|
||||
{"with underscore", "sa:test_user:abcdef0123456789", false},
|
||||
|
||||
// AWS IAM usernames accept `+=,.@-` in addition to alphanumerics
|
||||
// and underscore. Service account IDs must accept them too, or
|
||||
// callers with realistic usernames hit a validation error at the
|
||||
// persistence layer. See
|
||||
// https://docs.aws.amazon.com/IAM/latest/APIReference/API_User.html
|
||||
{"email-style", "sa:alice@example.com:abcdef0123456789", false},
|
||||
{"with dot", "sa:first.last:abcdef0123456789", false},
|
||||
{"with plus", "sa:user+tag:abcdef0123456789", false},
|
||||
{"with equals", "sa:user=prod:abcdef0123456789", false},
|
||||
{"with comma", "sa:a,b:abcdef0123456789", false},
|
||||
|
||||
{"empty", "", true},
|
||||
{"missing prefix", "alice:abcdef0123456789", true},
|
||||
{"wrong prefix", "svc:alice:abcdef0123456789", true},
|
||||
{"uppercase uuid", "sa:alice:ABCDEF0123456789", true},
|
||||
{"missing uuid", "sa:alice:", true},
|
||||
{"missing user", "sa::abcdef0123456789", true},
|
||||
// Colon is not in the AWS IAM username set, and would break
|
||||
// the colon-separated layout.
|
||||
{"colon in user", "sa:a:b:abcdef0123456789", true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := ValidateServiceAccountId(tc.id)
|
||||
if tc.wantErr && err == nil {
|
||||
t.Fatalf("expected error for %q, got nil", tc.id)
|
||||
}
|
||||
if !tc.wantErr && err != nil {
|
||||
t.Fatalf("unexpected error for %q: %v", tc.id, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -2,49 +2,13 @@ package postgres
|
||||
|
||||
import (
|
||||
"database/sql"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/stdlib"
|
||||
"github.com/seaweedfs/seaweedfs/weed/util/pgxutil"
|
||||
)
|
||||
|
||||
// OpenPGXDB parses the given DSN into a pgx ConnConfig, applies PgBouncer
|
||||
// compatibility settings when requested, opens a *sql.DB via
|
||||
// stdlib.OpenDB, and verifies it with Ping.
|
||||
//
|
||||
// In pgx/v5 the prefer_simple_protocol DSN parameter was removed, so simple
|
||||
// protocol mode must be configured on the ConnConfig via
|
||||
// DefaultQueryExecMode. We use stdlib.OpenDB(config) rather than
|
||||
// RegisterConnConfig + sql.Open so we don't leak entries in stdlib's global
|
||||
// connection config map on either success or failure paths.
|
||||
//
|
||||
// adaptedSqlUrl is used only for error messages (the caller is expected to
|
||||
// have redacted any password).
|
||||
// OpenPGXDB is a thin alias kept for callers (notably the postgres2 filer
|
||||
// store) that already depend on this entry point. New code should use
|
||||
// pgxutil.OpenDB directly.
|
||||
func OpenPGXDB(sqlUrl, adaptedSqlUrl string, pgbouncerCompatible bool, maxIdle, maxOpen, maxLifetimeSeconds int) (*sql.DB, error) {
|
||||
connConfig, parseErr := pgx.ParseConfig(sqlUrl)
|
||||
if parseErr != nil {
|
||||
return nil, fmt.Errorf("can not parse connection config for %s error:%v", adaptedSqlUrl, parseErr)
|
||||
}
|
||||
|
||||
// PgBouncer compatibility: use the simple query protocol and disable
|
||||
// statement caching. This avoids prepared statement issues with
|
||||
// PgBouncer's transaction pooling mode.
|
||||
if pgbouncerCompatible {
|
||||
connConfig.DefaultQueryExecMode = pgx.QueryExecModeSimpleProtocol
|
||||
connConfig.StatementCacheCapacity = 0
|
||||
connConfig.DescriptionCacheCapacity = 0
|
||||
}
|
||||
|
||||
db := stdlib.OpenDB(*connConfig)
|
||||
db.SetMaxIdleConns(maxIdle)
|
||||
db.SetMaxOpenConns(maxOpen)
|
||||
db.SetConnMaxLifetime(time.Duration(maxLifetimeSeconds) * time.Second)
|
||||
|
||||
if err := db.Ping(); err != nil {
|
||||
db.Close()
|
||||
return nil, fmt.Errorf("connect to %s error:%v", adaptedSqlUrl, err)
|
||||
}
|
||||
|
||||
return db, nil
|
||||
return pgxutil.OpenDB(sqlUrl, adaptedSqlUrl, pgbouncerCompatible, maxIdle, maxOpen, maxLifetimeSeconds)
|
||||
}
|
||||
@@ -2,109 +2,14 @@ package redis3
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"strconv"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
"github.com/stvp/tempredis"
|
||||
)
|
||||
|
||||
var names = []string{
|
||||
"cassandra.in.sh",
|
||||
"cassandra",
|
||||
"debug-cql.bat",
|
||||
"nodetool",
|
||||
"nodetool.bat",
|
||||
"source-conf.ps1",
|
||||
"sstableloader",
|
||||
"sstableloader.bat",
|
||||
"sstablescrub",
|
||||
"sstablescrub.bat",
|
||||
"sstableupgrade",
|
||||
"sstableupgrade.bat",
|
||||
"sstableutil",
|
||||
"sstableutil.bat",
|
||||
"sstableverify",
|
||||
"sstableverify.bat",
|
||||
"stop-server",
|
||||
"stop-server.bat",
|
||||
"stop-server.ps1",
|
||||
"cassandra.in.bat",
|
||||
"cqlsh.py",
|
||||
"cqlsh",
|
||||
"cassandra.ps1",
|
||||
"cqlsh.bat",
|
||||
"debug-cql",
|
||||
"cassandra.bat",
|
||||
}
|
||||
|
||||
func yTestNameList(t *testing.T) {
|
||||
server, err := tempredis.Start(tempredis.Config{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer server.Term()
|
||||
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Network: "unix",
|
||||
Addr: server.Socket(),
|
||||
})
|
||||
|
||||
store := newSkipListElementStore("/yyy/bin", client)
|
||||
var data []byte
|
||||
for _, name := range names {
|
||||
nameList := LoadItemList(data, "/yyy/bin", client, store, maxNameBatchSizeLimit)
|
||||
nameList.WriteName(name)
|
||||
|
||||
nameList.ListNames("", func(name string) bool {
|
||||
println(name)
|
||||
return true
|
||||
})
|
||||
|
||||
if nameList.HasChanges() {
|
||||
data = nameList.ToBytes()
|
||||
}
|
||||
println()
|
||||
}
|
||||
|
||||
nameList := LoadItemList(data, "/yyy/bin", client, store, maxNameBatchSizeLimit)
|
||||
nameList.ListNames("", func(name string) bool {
|
||||
println(name)
|
||||
return true
|
||||
})
|
||||
|
||||
}
|
||||
|
||||
func yBenchmarkNameList(b *testing.B) {
|
||||
|
||||
server, err := tempredis.Start(tempredis.Config{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer server.Term()
|
||||
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Network: "unix",
|
||||
Addr: server.Socket(),
|
||||
})
|
||||
|
||||
store := newSkipListElementStore("/yyy/bin", client)
|
||||
var data []byte
|
||||
for i := 0; i < b.N; i++ {
|
||||
nameList := LoadItemList(data, "/yyy/bin", client, store, maxNameBatchSizeLimit)
|
||||
|
||||
nameList.WriteName(strconv.Itoa(i) + "namexxxxxxxxxxxxxxxxxxx")
|
||||
|
||||
if nameList.HasChanges() {
|
||||
data = nameList.ToBytes()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func BenchmarkRedis(b *testing.B) {
|
||||
|
||||
server, err := tempredis.Start(tempredis.Config{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
@@ -120,92 +25,3 @@ func BenchmarkRedis(b *testing.B) {
|
||||
client.ZAddNX(context.Background(), "/yyy/bin", redis.Z{Score: 0, Member: strconv.Itoa(i) + "namexxxxxxxxxxxxxxxxxxx"})
|
||||
}
|
||||
}
|
||||
|
||||
func xTestNameListAdd(t *testing.T) {
|
||||
|
||||
server, err := tempredis.Start(tempredis.Config{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer server.Term()
|
||||
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
Password: "",
|
||||
DB: 0,
|
||||
})
|
||||
|
||||
client.FlushAll(context.Background())
|
||||
|
||||
N := 364800
|
||||
|
||||
ts0 := time.Now()
|
||||
store := newSkipListElementStore("/y", client)
|
||||
var data []byte
|
||||
nameList := LoadItemList(data, "/y", client, store, 100000)
|
||||
for i := 0; i < N; i++ {
|
||||
nameList.WriteName(fmt.Sprintf("%8d", i))
|
||||
}
|
||||
|
||||
ts1 := time.Now()
|
||||
|
||||
for i := 0; i < N; i++ {
|
||||
client.ZAddNX(context.Background(), "/x", redis.Z{Score: 0, Member: fmt.Sprintf("name %8d", i)})
|
||||
}
|
||||
ts2 := time.Now()
|
||||
|
||||
fmt.Printf("%v %v", ts1.Sub(ts0), ts2.Sub(ts1))
|
||||
|
||||
/*
|
||||
keys := client.Keys(context.Background(), "/*m").Val()
|
||||
for _, k := range keys {
|
||||
println("key", k)
|
||||
for i, v := range client.ZRangeByLex(context.Background(), k, &redis.ZRangeBy{
|
||||
Min: "-",
|
||||
Max: "+",
|
||||
}).Val() {
|
||||
println(" ", i, v)
|
||||
}
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
func xBenchmarkNameList(b *testing.B) {
|
||||
|
||||
server, err := tempredis.Start(tempredis.Config{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer server.Term()
|
||||
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
Password: "",
|
||||
DB: 0,
|
||||
})
|
||||
|
||||
store := newSkipListElementStore("/yyy/bin", client)
|
||||
var data []byte
|
||||
for i := 0; i < b.N; i++ {
|
||||
nameList := LoadItemList(data, "/yyy/bin", client, store, maxNameBatchSizeLimit)
|
||||
|
||||
nameList.WriteName(fmt.Sprintf("name %8d", i))
|
||||
|
||||
if nameList.HasChanges() {
|
||||
data = nameList.ToBytes()
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func xBenchmarkRedis(b *testing.B) {
|
||||
|
||||
client := redis.NewClient(&redis.Options{
|
||||
Addr: "localhost:6379",
|
||||
Password: "",
|
||||
DB: 0,
|
||||
})
|
||||
|
||||
for i := 0; i < b.N; i++ {
|
||||
client.ZAddNX(context.Background(), "/xxx/bin", redis.Z{Score: 0, Member: fmt.Sprintf("name %8d", i)})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
package policy
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
// TestStringifyClaimValue covers the scalar types that can appear in
|
||||
// RequestContext so that both JSON-decoded (float64, json.Number) and typed
|
||||
// (int8..int64, uint..uint64, bool) values substitute correctly.
|
||||
func TestStringifyClaimValue(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
value interface{}
|
||||
want string
|
||||
wantOk bool
|
||||
}{
|
||||
{name: "string", value: "alice", want: "alice", wantOk: true},
|
||||
{name: "bool true", value: true, want: "true", wantOk: true},
|
||||
{name: "bool false", value: false, want: "false", wantOk: true},
|
||||
{name: "float64 integer", value: float64(301), want: "301", wantOk: true},
|
||||
{name: "float64 fraction", value: 1.5, want: "1.5", wantOk: true},
|
||||
{name: "float32", value: float32(2.25), want: "2.25", wantOk: true},
|
||||
{name: "int", value: int(42), want: "42", wantOk: true},
|
||||
{name: "int8", value: int8(-5), want: "-5", wantOk: true},
|
||||
{name: "int16", value: int16(32000), want: "32000", wantOk: true},
|
||||
{name: "int32", value: int32(-123456), want: "-123456", wantOk: true},
|
||||
{name: "int64", value: int64(9999999999), want: "9999999999", wantOk: true},
|
||||
{name: "uint", value: uint(7), want: "7", wantOk: true},
|
||||
{name: "uint8", value: uint8(255), want: "255", wantOk: true},
|
||||
{name: "uint16", value: uint16(65535), want: "65535", wantOk: true},
|
||||
{name: "uint32", value: uint32(4000000000), want: "4000000000", wantOk: true},
|
||||
{name: "uint64", value: uint64(18000000000000000000), want: "18000000000000000000", wantOk: true},
|
||||
{name: "json.Number int", value: json.Number("301"), want: "301", wantOk: true},
|
||||
{name: "json.Number float", value: json.Number("1.5"), want: "1.5", wantOk: true},
|
||||
{name: "nil", value: nil, want: "", wantOk: false},
|
||||
{name: "slice unsupported", value: []string{"a", "b"}, want: "", wantOk: false},
|
||||
{name: "map unsupported", value: map[string]string{"a": "b"}, want: "", wantOk: false},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
got, ok := stringifyClaimValue(tt.value)
|
||||
assert.Equal(t, tt.wantOk, ok)
|
||||
assert.Equal(t, tt.want, got)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestExpandPolicyVariablesDynamicJWTClaims verifies that arbitrary JWT claims
|
||||
// (not only the hardcoded jwt:sub/jwt:iss/jwt:aud/jwt:preferred_username)
|
||||
// can be substituted in policy patterns when present in the request context.
|
||||
// Reproduces the scenario in https://github.com/seaweedfs/seaweedfs/issues/9214
|
||||
// where ${jwt:project_path} was left unsubstituted.
|
||||
func TestExpandPolicyVariablesDynamicJWTClaims(t *testing.T) {
|
||||
evalCtx := &EvaluationContext{
|
||||
RequestContext: map[string]interface{}{
|
||||
"jwt:project_path": "some/namespace/project",
|
||||
"jwt:namespace_path": "some/namespace",
|
||||
"jwt:user_login": "mat",
|
||||
// JSON-decoded numeric claim
|
||||
"jwt:project_id": float64(301),
|
||||
// Dynamic SAML/OIDC claims
|
||||
"saml:department": "engineering",
|
||||
"oidc:tenant": "acme",
|
||||
},
|
||||
}
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
pattern string
|
||||
expected string
|
||||
}{
|
||||
{
|
||||
name: "dynamic jwt claim substituted in resource arn",
|
||||
pattern: "arn:aws:s3:::softs/${jwt:project_path}/*",
|
||||
expected: "arn:aws:s3:::softs/some/namespace/project/*",
|
||||
},
|
||||
{
|
||||
name: "multiple dynamic jwt claims in one pattern",
|
||||
pattern: "${jwt:namespace_path}/${jwt:user_login}/data",
|
||||
expected: "some/namespace/mat/data",
|
||||
},
|
||||
{
|
||||
name: "dynamic numeric jwt claim is stringified",
|
||||
pattern: "projects/${jwt:project_id}/uploads",
|
||||
expected: "projects/301/uploads",
|
||||
},
|
||||
{
|
||||
name: "dynamic saml claim substituted",
|
||||
pattern: "dept/${saml:department}/*",
|
||||
expected: "dept/engineering/*",
|
||||
},
|
||||
{
|
||||
name: "dynamic oidc claim substituted",
|
||||
pattern: "tenants/${oidc:tenant}/data",
|
||||
expected: "tenants/acme/data",
|
||||
},
|
||||
{
|
||||
name: "missing jwt claim leaves placeholder intact",
|
||||
pattern: "softs/${jwt:missing_claim}/*",
|
||||
expected: "softs/${jwt:missing_claim}/*",
|
||||
},
|
||||
{
|
||||
name: "non-identity prefix is not substituted",
|
||||
pattern: "foo/${custom:project_path}/*",
|
||||
expected: "foo/${custom:project_path}/*",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
result := expandPolicyVariables(tt.pattern, evalCtx)
|
||||
assert.Equal(t, tt.expected, result)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitLabProjectUploadPolicy reproduces the GitLab OIDC policy from issue
|
||||
// #9214 end-to-end against the policy engine, proving that jwt:project_path
|
||||
// (a non-hardcoded JWT claim) is now substituted in Resource patterns so that
|
||||
// each project only gets access under its own prefix.
|
||||
func TestGitLabProjectUploadPolicy(t *testing.T) {
|
||||
engine := NewPolicyEngine()
|
||||
require.NoError(t, engine.Initialize(&PolicyEngineConfig{
|
||||
DefaultEffect: "Deny",
|
||||
StoreType: "memory",
|
||||
}))
|
||||
|
||||
policyDoc := &PolicyDocument{
|
||||
Version: "2012-10-17",
|
||||
Statement: []Statement{
|
||||
{
|
||||
Sid: "AllowPutInOwnFolder",
|
||||
Effect: "Allow",
|
||||
Action: []string{"s3:PutObject"},
|
||||
Resource: []string{"arn:aws:s3:::softs/${jwt:project_path}/*"},
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
require.NoError(t, engine.AddPolicy("", "GitlabProjectUploadPolicy", policyDoc))
|
||||
|
||||
ctx := context.Background()
|
||||
|
||||
mat := map[string]interface{}{
|
||||
"jwt:project_path": "some/namespace/project",
|
||||
}
|
||||
other := map[string]interface{}{
|
||||
"jwt:project_path": "other/namespace/project",
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
action string
|
||||
resource string
|
||||
reqCtx map[string]interface{}
|
||||
want Effect
|
||||
}{
|
||||
{
|
||||
name: "user writes into own project folder - allowed",
|
||||
action: "s3:PutObject",
|
||||
resource: "arn:aws:s3:::softs/some/namespace/project/build.zip",
|
||||
reqCtx: mat,
|
||||
want: EffectAllow,
|
||||
},
|
||||
{
|
||||
name: "user tries to write into another project - falls through to default Deny",
|
||||
action: "s3:PutObject",
|
||||
resource: "arn:aws:s3:::softs/other/namespace/project/build.zip",
|
||||
reqCtx: mat,
|
||||
want: EffectDeny,
|
||||
},
|
||||
{
|
||||
name: "different user writes into their own project - allowed",
|
||||
action: "s3:PutObject",
|
||||
resource: "arn:aws:s3:::softs/other/namespace/project/build.zip",
|
||||
reqCtx: other,
|
||||
want: EffectAllow,
|
||||
},
|
||||
{
|
||||
name: "user tries to GetObject - only PutObject allowed, default Deny",
|
||||
action: "s3:GetObject",
|
||||
resource: "arn:aws:s3:::softs/some/namespace/project/build.zip",
|
||||
reqCtx: mat,
|
||||
want: EffectDeny,
|
||||
},
|
||||
{
|
||||
name: "missing project_path claim - placeholder prevents match, default Deny",
|
||||
action: "s3:PutObject",
|
||||
resource: "arn:aws:s3:::softs/some/namespace/project/build.zip",
|
||||
reqCtx: map[string]interface{}{},
|
||||
want: EffectDeny,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
evalCtx := &EvaluationContext{
|
||||
Principal: "user",
|
||||
Action: tc.action,
|
||||
Resource: tc.resource,
|
||||
RequestContext: tc.reqCtx,
|
||||
}
|
||||
|
||||
result, err := engine.Evaluate(ctx, "", evalCtx, []string{"GitlabProjectUploadPolicy"})
|
||||
require.NoError(t, err)
|
||||
assert.Equal(t, tc.want, result.Effect,
|
||||
"matching statements: %+v", result.MatchingStatements)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -23,7 +23,11 @@ const (
|
||||
|
||||
var (
|
||||
policyVariablePattern = regexp.MustCompile(`\$\{([^}]+)\}`)
|
||||
safePolicyVariables = map[string]bool{
|
||||
// safePolicyVariables is the explicit allowlist of fixed-name variables.
|
||||
// Identity claims published under jwt:/saml:/oidc: are additionally accepted
|
||||
// as dynamic variables (see isSafePolicyVariable) so that any claim from a
|
||||
// cryptographically verified federated token can be used in policies.
|
||||
safePolicyVariables = map[string]bool{
|
||||
// AWS standard identity variables
|
||||
"aws:username": true,
|
||||
"aws:userid": true,
|
||||
@@ -32,20 +36,6 @@ var (
|
||||
"aws:principaltype": true,
|
||||
"aws:FederatedProvider": true,
|
||||
"aws:PrincipalServiceName": true,
|
||||
// SAML identity variables
|
||||
"saml:username": true,
|
||||
"saml:sub": true,
|
||||
"saml:aud": true,
|
||||
"saml:iss": true,
|
||||
// OIDC/JWT identity variables
|
||||
"oidc:sub": true,
|
||||
"oidc:aud": true,
|
||||
"oidc:iss": true,
|
||||
// JWT identity variables
|
||||
"jwt:preferred_username": true,
|
||||
"jwt:sub": true,
|
||||
"jwt:iss": true,
|
||||
"jwt:aud": true,
|
||||
// AWS request context (not from headers)
|
||||
"aws:SourceIp": true,
|
||||
"aws:SecureTransport": true,
|
||||
@@ -56,6 +46,20 @@ var (
|
||||
}
|
||||
)
|
||||
|
||||
// isSafePolicyVariable reports whether a policy variable may be substituted
|
||||
// with a value from RequestContext. The fixed allowlist covers AWS-defined
|
||||
// variables; any jwt:/saml:/oidc: claim is also allowed because those come
|
||||
// from a validated identity token (the STS session JWT or federated assertion)
|
||||
// and the claim set is controlled by the trusted identity provider.
|
||||
func isSafePolicyVariable(variable string) bool {
|
||||
if safePolicyVariables[variable] {
|
||||
return true
|
||||
}
|
||||
return strings.HasPrefix(variable, "jwt:") ||
|
||||
strings.HasPrefix(variable, "saml:") ||
|
||||
strings.HasPrefix(variable, "oidc:")
|
||||
}
|
||||
|
||||
// PolicyEngine evaluates policies against requests
|
||||
type PolicyEngine struct {
|
||||
config *PolicyEngineConfig
|
||||
@@ -1240,25 +1244,77 @@ func expandPolicyVariables(pattern string, evalCtx *EvaluationContext) string {
|
||||
// Extract variable name from ${variable}
|
||||
variable := match[2 : len(match)-1]
|
||||
|
||||
// Only substitute if variable is in the safe allowlist
|
||||
if !safePolicyVariables[variable] {
|
||||
return match // Leave unsafe variables as-is
|
||||
// Only substitute if the variable is in the allowlist or is a dynamic
|
||||
// identity-claim variable (jwt:/saml:/oidc:)
|
||||
if !isSafePolicyVariable(variable) {
|
||||
return match // Leave unrecognised variables as-is
|
||||
}
|
||||
|
||||
// Get value from request context
|
||||
if value, exists := evalCtx.RequestContext[variable]; exists {
|
||||
if str, ok := value.(string); ok {
|
||||
return str
|
||||
}
|
||||
value, exists := evalCtx.RequestContext[variable]
|
||||
if !exists {
|
||||
return match // Variable not supplied: leave placeholder so statement won't match
|
||||
}
|
||||
|
||||
// Variable not found or not a string, leave as-is
|
||||
if str, ok := stringifyClaimValue(value); ok {
|
||||
return str
|
||||
}
|
||||
|
||||
// Value is a non-scalar (array/object) we can't meaningfully substitute
|
||||
return match
|
||||
})
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
// stringifyClaimValue converts a claim value to its string form for policy
|
||||
// variable substitution. Returns (value, true) for scalar types that a JWT
|
||||
// claim can produce after JSON decoding, and ("", false) for slices/maps/nil.
|
||||
// JSON's generic decoder only produces float64 / json.Number for numbers, but
|
||||
// RequestContext can also be populated from typed sources (e.g., custom
|
||||
// providers or internal code), so all common integer widths — signed and
|
||||
// unsigned — are handled explicitly.
|
||||
func stringifyClaimValue(value interface{}) (string, bool) {
|
||||
switch v := value.(type) {
|
||||
case string:
|
||||
return v, true
|
||||
case bool:
|
||||
return strconv.FormatBool(v), true
|
||||
case float64:
|
||||
// JSON-decoded numbers are float64; render integers without a decimal point
|
||||
if v == float64(int64(v)) {
|
||||
return strconv.FormatInt(int64(v), 10), true
|
||||
}
|
||||
return strconv.FormatFloat(v, 'g', -1, 64), true
|
||||
case float32:
|
||||
return strconv.FormatFloat(float64(v), 'g', -1, 32), true
|
||||
case int:
|
||||
return strconv.FormatInt(int64(v), 10), true
|
||||
case int8:
|
||||
return strconv.FormatInt(int64(v), 10), true
|
||||
case int16:
|
||||
return strconv.FormatInt(int64(v), 10), true
|
||||
case int32:
|
||||
return strconv.FormatInt(int64(v), 10), true
|
||||
case int64:
|
||||
return strconv.FormatInt(v, 10), true
|
||||
case uint:
|
||||
return strconv.FormatUint(uint64(v), 10), true
|
||||
case uint8:
|
||||
return strconv.FormatUint(uint64(v), 10), true
|
||||
case uint16:
|
||||
return strconv.FormatUint(uint64(v), 10), true
|
||||
case uint32:
|
||||
return strconv.FormatUint(uint64(v), 10), true
|
||||
case uint64:
|
||||
return strconv.FormatUint(v, 10), true
|
||||
case json.Number:
|
||||
return v.String(), true
|
||||
default:
|
||||
return "", false
|
||||
}
|
||||
}
|
||||
|
||||
// evaluateStringConditionIgnoreCase evaluates string conditions with case insensitivity
|
||||
func (e *PolicyEngine) evaluateStringConditionIgnoreCase(block map[string]interface{}, evalCtx *EvaluationContext, shouldMatch bool, useWildcard bool, forAllValues bool) bool {
|
||||
for key, expectedValues := range block {
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
package iam
|
||||
|
||||
import "net/url"
|
||||
|
||||
// sensitiveFormKeys is the set of IAM request form parameters whose values
|
||||
// must never be written to logs. Matching is case-sensitive and uses the
|
||||
// exact AWS IAM parameter name. Extend this when adding IAM actions that
|
||||
// accept credentials, passwords, session tokens, or private keys.
|
||||
var sensitiveFormKeys = map[string]struct{}{
|
||||
"SecretAccessKey": {},
|
||||
"Password": {},
|
||||
"NewPassword": {},
|
||||
"OldPassword": {},
|
||||
"PrivateKey": {},
|
||||
"SessionToken": {},
|
||||
}
|
||||
|
||||
// RedactSensitiveFormValues returns a shallow copy of values with every
|
||||
// sensitive key (see sensitiveFormKeys) replaced by "[REDACTED]". Intended
|
||||
// for debug-level logging of IAM request forms so secrets do not leak into
|
||||
// log sinks.
|
||||
func RedactSensitiveFormValues(values url.Values) url.Values {
|
||||
safe := make(url.Values, len(values))
|
||||
for k, v := range values {
|
||||
if _, sensitive := sensitiveFormKeys[k]; sensitive {
|
||||
safe[k] = []string{"[REDACTED]"}
|
||||
} else {
|
||||
safe[k] = v
|
||||
}
|
||||
}
|
||||
return safe
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
package iam
|
||||
|
||||
import (
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestRedactSensitiveFormValues(t *testing.T) {
|
||||
in := url.Values{
|
||||
"Action": []string{"CreateAccessKey"},
|
||||
"UserName": []string{"alice"},
|
||||
"AccessKeyId": []string{"AKIAALICE1"},
|
||||
"SecretAccessKey": []string{"very-secret"},
|
||||
"Password": []string{"hunter2"},
|
||||
"NewPassword": []string{"new-hunter2"},
|
||||
"OldPassword": []string{"old-hunter2"},
|
||||
"PrivateKey": []string{"-----BEGIN-----"},
|
||||
"SessionToken": []string{"tok"},
|
||||
}
|
||||
out := RedactSensitiveFormValues(in)
|
||||
|
||||
assert.Equal(t, []string{"CreateAccessKey"}, out["Action"])
|
||||
assert.Equal(t, []string{"alice"}, out["UserName"])
|
||||
assert.Equal(t, []string{"AKIAALICE1"}, out["AccessKeyId"])
|
||||
for _, k := range []string{"SecretAccessKey", "Password", "NewPassword", "OldPassword", "PrivateKey", "SessionToken"} {
|
||||
assert.Equal(t, []string{"[REDACTED]"}, out[k], "key %q should be redacted", k)
|
||||
}
|
||||
|
||||
// Input is not mutated.
|
||||
assert.Equal(t, []string{"very-secret"}, in["SecretAccessKey"])
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
package iam
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
)
|
||||
|
||||
// ValidateCallerSuppliedAccessKeyId checks that a caller-supplied AccessKeyId
|
||||
// is 4 to 128 ASCII alphanumeric characters. Returns nil if valid.
|
||||
//
|
||||
// The alphanumeric restriction avoids characters that would break SigV4
|
||||
// canonicalization (e.g. '/' and '=' appear as delimiters in Credential
|
||||
// headers), so this is a stricter superset of the rule AWS enforces.
|
||||
func ValidateCallerSuppliedAccessKeyId(accessKeyId string) error {
|
||||
if len(accessKeyId) < 4 || len(accessKeyId) > 128 {
|
||||
return fmt.Errorf("AccessKeyId must be 4 to 128 alphanumeric characters")
|
||||
}
|
||||
for _, r := range accessKeyId {
|
||||
if !((r >= 'A' && r <= 'Z') || (r >= 'a' && r <= 'z') || (r >= '0' && r <= '9')) {
|
||||
return fmt.Errorf("AccessKeyId must be 4 to 128 alphanumeric characters")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// ValidateCallerSuppliedSecretAccessKey checks that a caller-supplied
|
||||
// SecretAccessKey is 8 to 128 characters. Returns nil if valid.
|
||||
func ValidateCallerSuppliedSecretAccessKey(secretAccessKey string) error {
|
||||
if len(secretAccessKey) < 8 || len(secretAccessKey) > 128 {
|
||||
return fmt.Errorf("SecretAccessKey must be between 8 and 128 characters")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// AccessKeyOwner identifies which entity in an S3ApiConfiguration already owns
|
||||
// a given AccessKeyId. Returned by FindAccessKeyOwner for collision checks on
|
||||
// caller-supplied credentials.
|
||||
type AccessKeyOwner struct {
|
||||
// Type is "user" or "service account".
|
||||
Type string
|
||||
// Name is the identity's Name (for users) or the service account's Id.
|
||||
Name string
|
||||
}
|
||||
|
||||
// FindAccessKeyOwner scans s3cfg for an identity or service account whose
|
||||
// credentials already contain accessKeyId. Returns nil if the key is free.
|
||||
//
|
||||
// Callers should log Name only at debug level — error responses returned to
|
||||
// the caller should not include owner identity to avoid information leaks.
|
||||
func FindAccessKeyOwner(s3cfg *iam_pb.S3ApiConfiguration, accessKeyId string) *AccessKeyOwner {
|
||||
if s3cfg == nil || accessKeyId == "" {
|
||||
return nil
|
||||
}
|
||||
for _, ident := range s3cfg.Identities {
|
||||
for _, cred := range ident.Credentials {
|
||||
if cred.AccessKey == accessKeyId {
|
||||
return &AccessKeyOwner{Type: "user", Name: ident.Name}
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, sa := range s3cfg.ServiceAccounts {
|
||||
if sa.Credential != nil && sa.Credential.AccessKey == accessKeyId {
|
||||
return &AccessKeyOwner{Type: "service account", Name: sa.Id}
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
package iam
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/seaweedfs/seaweedfs/weed/pb/iam_pb"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func TestValidateCallerSuppliedAccessKeyId(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
input string
|
||||
wantErr bool
|
||||
}{
|
||||
{"empty", "", true},
|
||||
{"three chars", "abc", true},
|
||||
{"four chars ok", "abcd", false},
|
||||
{"mixed case alnum", "MyAppKey123", false},
|
||||
{"128 chars ok", strings.Repeat("a", 128), false},
|
||||
{"129 chars too long", strings.Repeat("a", 129), true},
|
||||
{"slash rejected", "foo/bar", true},
|
||||
{"equals rejected", "foo=bar", true},
|
||||
{"dash rejected", "foo-bar", true},
|
||||
{"underscore rejected", "foo_bar", true},
|
||||
{"unicode rejected", "fooö123", true},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := ValidateCallerSuppliedAccessKeyId(tc.input)
|
||||
if tc.wantErr {
|
||||
assert.Error(t, err)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateCallerSuppliedSecretAccessKey(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
input string
|
||||
wantErr bool
|
||||
}{
|
||||
{"empty", "", true},
|
||||
{"seven chars", "abcdefg", true},
|
||||
{"eight chars ok", "abcdefgh", false},
|
||||
{"128 chars ok", strings.Repeat("a", 128), false},
|
||||
{"129 chars too long", strings.Repeat("a", 129), true},
|
||||
{"non-alnum allowed in secret", "sec/ret=1", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
err := ValidateCallerSuppliedSecretAccessKey(tc.input)
|
||||
if tc.wantErr {
|
||||
assert.Error(t, err)
|
||||
} else {
|
||||
assert.NoError(t, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestFindAccessKeyOwner(t *testing.T) {
|
||||
s3cfg := &iam_pb.S3ApiConfiguration{
|
||||
Identities: []*iam_pb.Identity{
|
||||
{
|
||||
Name: "alice",
|
||||
Credentials: []*iam_pb.Credential{
|
||||
{AccessKey: "AKIAALICE1", SecretKey: "s"},
|
||||
},
|
||||
},
|
||||
{Name: "bob"},
|
||||
},
|
||||
ServiceAccounts: []*iam_pb.ServiceAccount{
|
||||
{Id: "svc-1", Credential: &iam_pb.Credential{AccessKey: "SVCKEY1"}},
|
||||
{Id: "svc-2"},
|
||||
},
|
||||
}
|
||||
|
||||
t.Run("matches user", func(t *testing.T) {
|
||||
owner := FindAccessKeyOwner(s3cfg, "AKIAALICE1")
|
||||
assert.NotNil(t, owner)
|
||||
assert.Equal(t, "user", owner.Type)
|
||||
assert.Equal(t, "alice", owner.Name)
|
||||
})
|
||||
t.Run("matches service account", func(t *testing.T) {
|
||||
owner := FindAccessKeyOwner(s3cfg, "SVCKEY1")
|
||||
assert.NotNil(t, owner)
|
||||
assert.Equal(t, "service account", owner.Type)
|
||||
assert.Equal(t, "svc-1", owner.Name)
|
||||
})
|
||||
t.Run("no match", func(t *testing.T) {
|
||||
assert.Nil(t, FindAccessKeyOwner(s3cfg, "NOTTAKEN"))
|
||||
})
|
||||
t.Run("empty key", func(t *testing.T) {
|
||||
assert.Nil(t, FindAccessKeyOwner(s3cfg, ""))
|
||||
})
|
||||
t.Run("nil config", func(t *testing.T) {
|
||||
assert.Nil(t, FindAccessKeyOwner(nil, "anything"))
|
||||
})
|
||||
}
|
||||
@@ -929,13 +929,38 @@ func (iama *IamApiServer) CreateAccessKey(s3cfg *iam_pb.S3ApiConfiguration, valu
|
||||
userName := values.Get("UserName")
|
||||
status := iam.StatusTypeActive
|
||||
|
||||
accessKeyId, err := StringWithCharset(21, charsetUpper)
|
||||
if err != nil {
|
||||
return resp, &IamError{Code: iam.ErrCodeServiceFailureException, Error: fmt.Errorf("failed to generate access key: %w", err)}
|
||||
accessKeyId := values.Get("AccessKeyId")
|
||||
secretAccessKey := values.Get("SecretAccessKey")
|
||||
if accessKeyId != "" {
|
||||
if err := iamlib.ValidateCallerSuppliedAccessKeyId(accessKeyId); err != nil {
|
||||
return resp, &IamError{Code: iam.ErrCodeInvalidInputException, Error: err}
|
||||
}
|
||||
}
|
||||
secretAccessKey, err := StringWithCharset(42, charset)
|
||||
if err != nil {
|
||||
return resp, &IamError{Code: iam.ErrCodeServiceFailureException, Error: fmt.Errorf("failed to generate secret key: %w", err)}
|
||||
if secretAccessKey != "" {
|
||||
if err := iamlib.ValidateCallerSuppliedSecretAccessKey(secretAccessKey); err != nil {
|
||||
return resp, &IamError{Code: iam.ErrCodeInvalidInputException, Error: err}
|
||||
}
|
||||
}
|
||||
if (accessKeyId != "") != (secretAccessKey != "") {
|
||||
return resp, &IamError{Code: iam.ErrCodeInvalidInputException, Error: fmt.Errorf("AccessKeyId and SecretAccessKey must be supplied together")}
|
||||
}
|
||||
if owner := iamlib.FindAccessKeyOwner(s3cfg, accessKeyId); owner != nil {
|
||||
glog.V(4).Infof("CreateAccessKey: supplied AccessKeyId already in use by %s %s", owner.Type, owner.Name)
|
||||
return resp, &IamError{Code: iam.ErrCodeEntityAlreadyExistsException, Error: fmt.Errorf("AccessKeyId is already in use")}
|
||||
}
|
||||
if accessKeyId == "" {
|
||||
var err error
|
||||
accessKeyId, err = StringWithCharset(21, charsetUpper)
|
||||
if err != nil {
|
||||
return resp, &IamError{Code: iam.ErrCodeServiceFailureException, Error: fmt.Errorf("failed to generate access key: %w", err)}
|
||||
}
|
||||
}
|
||||
if secretAccessKey == "" {
|
||||
var err error
|
||||
secretAccessKey, err = StringWithCharset(42, charset)
|
||||
if err != nil {
|
||||
return resp, &IamError{Code: iam.ErrCodeServiceFailureException, Error: fmt.Errorf("failed to generate secret key: %w", err)}
|
||||
}
|
||||
}
|
||||
|
||||
resp.CreateAccessKeyResult.AccessKey.AccessKeyId = &accessKeyId
|
||||
@@ -1085,7 +1110,7 @@ func (iama *IamApiServer) DoActions(w http.ResponseWriter, r *http.Request) {
|
||||
return
|
||||
}
|
||||
|
||||
glog.V(4).Infof("DoActions: %+v", values)
|
||||
glog.V(4).Infof("DoActions: %+v", iamlib.RedactSensitiveFormValues(values))
|
||||
var response iamlib.RequestIDSetter
|
||||
changed := true
|
||||
switch r.Form.Get("Action") {
|
||||
|
||||
Loaded 100 of 194 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user