diff --git a/examples/backups/kafka/01-create-strategy.sh b/examples/backups/kafka/01-create-strategy.sh index 7c57c1f65..686ec0449 100755 --- a/examples/backups/kafka/01-create-strategy.sh +++ b/examples/backups/kafka/01-create-strategy.sh @@ -137,45 +137,65 @@ spec: *) BASE="https://\${S3_ENDPOINT}" ;; esac - # Split the endpoint into scheme/host/port. The Strimzi image ships - # curl 7.76.1, whose --aws-sigv4 has a bug fixed only in 7.87.0: it - # omits a non-default port from the SigV4 canonical Host even though - # it sends the port in the Host header. seaweedfs recomputes the - # signature from the received "host:port" and so rejects the PUT - # with 403 whenever the endpoint carries a non-default port (the - # e2e harness points S3_ENDPOINT at the :8333 in-cluster Service). - # Strip the port from the signed/sent URL and redirect the - # connection to the real port with --connect-to, so the signed, - # sent and server-side Host all agree on the bare host. This is - # also correct on curl >= 7.87, which drops the default port too. - # Demo-scope parse: handles the "scheme://host[:port]" that - # BucketInfo advertises. An IPv6 literal ([::1]:8333) or an - # endpoint carrying a path prefix would be mis-split - out of - # scope here. + # Split the endpoint into scheme/host/port. Demo-scope parse: + # handles the "scheme://host[:port]" that BucketInfo advertises. + # An IPv6 literal ([::1]:8333) or an endpoint carrying a path + # prefix would be mis-split - out of scope here. SCHEME="\${BASE%%://*}" HOSTPORT="\${BASE#*://}"; HOSTPORT="\${HOSTPORT%%/*}" HOST="\${HOSTPORT%%:*}" PORT="\${HOSTPORT##*:}" if [ "\${PORT}" = "\${HOSTPORT}" ]; then PORT=""; fi if [ "\${SCHEME}" = http ]; then DEFPORT=80; else DEFPORT=443; fi - CONNECT_TO="" - if [ -n "\${PORT}" ] && [ "\${PORT}" != "\${DEFPORT}" ]; then - CONNECT_TO="--connect-to \${HOST}:\${DEFPORT}:\${HOST}:\${PORT}" - fi + # The Host header curl sends, which is what gets signed: curl + # leaves the port out exactly when it is the scheme's default. + AUTHORITY="\${HOST}" + if [ -n "\${PORT}" ] && [ "\${PORT}" != "\${DEFPORT}" ]; then AUTHORITY="\${HOST}:\${PORT}"; fi if [ "\${MODE}" = backup ]; then SRC="\${SRC_BACKUP}"; else SRC="\${SRC_RESTORE}"; fi KEY="\${SRC_NAMESPACE}/\${SRC}/kafka-topics.tar" - OBJ_URL="\${SCHEME}://\${HOST}/\${S3_BUCKET}/\${KEY}" + # Namespace and application names are DNS labels, so the path + # needs no percent-encoding to be its own canonical URI. + OBJ_PATH="/\${S3_BUCKET}/\${KEY}" + OBJ_URL="\${SCHEME}://\${AUTHORITY}\${OBJ_PATH}" - # curl --aws-sigv4 signs the request (SigV4) so no separate S3 - # client image is needed. The certificate is verified: against the - # CA projected from the Secret when it carries one, else - # against the image's trust store. \${CA_OPT} and \${CONNECT_TO} - # are deliberately unquoted so an empty value expands to no - # argument. + # The request is SigV4-signed here, with openssl and sha256sum, + # so no separate S3 client image is needed. It is not left to curl + # --aws-sigv4, because the curl in the Strimzi image cannot sign + # for S3: 7.76.1-40.el9 (Strimzi 1.2) signs the Host without a + # non-default port while sending it with one, and 7.76.1-43.el9 + # (Strimzi 1.3.1) carries a RHEL backport of the S3 payload + # handling that lists x-amz-content-sha256 in SignedHeaders + # without ever sending the header. Either way seaweedfs answers + # 403. The certificate is verified: against the CA projected from + # the Secret when it carries one, else against the image's trust + # store. \${CA_OPT} is deliberately unquoted so an empty value + # expands to no argument. CA_OPT="" if [ -s "\${CA_FILE}" ]; then CA_OPT="--cacert \${CA_FILE}"; fi - s3() { curl -fsS \${CA_OPT} \${CONNECT_TO} --aws-sigv4 "aws:amz:\${S3_REGION}:s3" --user "\${AWS_ACCESS_KEY_ID}:\${AWS_SECRET_ACCESS_KEY}" "\$@"; } + EMPTY_SHA256=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 + hmac() { printf '%s' "\$2" | openssl dgst -sha256 -mac HMAC -macopt "\$1" -r | cut -d' ' -f1; } + # s3 METHOD PAYLOAD_SHA256 [curl args...] + s3() { + local method=\$1 payload=\$2 now day scope creq sts k sig + shift 2 + now=\$(date -u +%Y%m%dT%H%M%SZ) + day=\${now%%T*} + scope="\${day}/\${S3_REGION}/s3/aws4_request" + creq=\$(printf '%s\n%s\n\nhost:%s\nx-amz-content-sha256:%s\nx-amz-date:%s\n\nhost;x-amz-content-sha256;x-amz-date\n%s' \\ + "\${method}" "\${OBJ_PATH}" "\${AUTHORITY}" "\${payload}" "\${now}" "\${payload}") + sts=\$(printf 'AWS4-HMAC-SHA256\n%s\n%s\n%s' "\${now}" "\${scope}" "\$(printf '%s' "\${creq}" | sha256sum | cut -d' ' -f1)") + k=\$(hmac "key:AWS4\${AWS_SECRET_ACCESS_KEY}" "\${day}") + k=\$(hmac "hexkey:\${k}" "\${S3_REGION}") + k=\$(hmac "hexkey:\${k}" s3) + k=\$(hmac "hexkey:\${k}" aws4_request) + sig=\$(hmac "hexkey:\${k}" "\${sts}") + curl -fsS \${CA_OPT} -X "\${method}" \\ + -H "x-amz-date: \${now}" \\ + -H "x-amz-content-sha256: \${payload}" \\ + -H "Authorization: AWS4-HMAC-SHA256 Credential=\${AWS_ACCESS_KEY_ID}/\${scope}, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=\${sig}" \\ + "\$@" "\${OBJ_URL}" + } # Records a topic currently holds, summed over its partitions as # end - begin. kafka-get-offsets prints only the partitions whose @@ -346,11 +366,11 @@ spec: echo " \${t}: \${pc} partition(s), replication factor \${rf}" done tar -C "\${WORK}" -cf "\${TARBALL}" . - s3 -X PUT --upload-file "\${TARBALL}" "\${OBJ_URL}" + s3 PUT "\$(sha256sum < "\${TARBALL}" | cut -d' ' -f1)" --upload-file "\${TARBALL}" echo "uploaded s3://\${S3_BUCKET}/\${KEY}" else echo "restoring topics into \${BOOT} from s3://\${S3_BUCKET}/\${KEY}" - s3 -o "\${TARBALL}" "\${OBJ_URL}" + s3 GET "\${EMPTY_SHA256}" -o "\${TARBALL}" tar -C "\${WORK}" -xf "\${TARBALL}" [ -f "\${WORK}/manifest.txt" ] || { echo "manifest missing in backup" >&2; exit 1; } # The manifest arrives inside the downloaded tarball, so treat it diff --git a/examples/backups/kafka/90-scenario-admin-prepare.md b/examples/backups/kafka/90-scenario-admin-prepare.md index 42bc1d697..f04a8438b 100644 --- a/examples/backups/kafka/90-scenario-admin-prepare.md +++ b/examples/backups/kafka/90-scenario-admin-prepare.md @@ -21,7 +21,7 @@ A cluster administrator performs the cluster-level preparation once. Tenant admi | Resource | Scope | Purpose | |---|---|---| -| `Job.strategy.backups.cozystack.io/kafka-job` | Cluster | PodTemplateSpec for a `quay.io/strimzi/kafka` Pod that drains the topics with `kafka-console-consumer`, replays them with `kafka-console-producer`, and moves a tarball to/from S3 with `curl --aws-sigv4` | +| `Job.strategy.backups.cozystack.io/kafka-job` | Cluster | PodTemplateSpec for a `quay.io/strimzi/kafka` Pod that drains the topics with `kafka-console-consumer`, replays them with `kafka-console-producer`, and moves a tarball to/from S3 with `curl`, SigV4-signed by the script | | `BackupClass/kafka-backup` | Cluster | Maps `apps.cozystack.io/Kafka` to the strategy. `parameters.topics` selects the topics (empty = every non-internal topic); `parameters.replicationFactor`, when set, overrides the replication factor the backup captured when restore recreates a topic | ## How the strategy template gets rendered diff --git a/examples/backups/kafka/91-scenario-user-backup.md b/examples/backups/kafka/91-scenario-user-backup.md index 9bff52ee3..b8b2c9f6c 100644 --- a/examples/backups/kafka/91-scenario-user-backup.md +++ b/examples/backups/kafka/91-scenario-user-backup.md @@ -39,7 +39,7 @@ The user's own action here, at the tenant admin level, is the `BackupJob` in ste - writes a manifest (`topic partition begin end replicationFactor` per line), `tar`s everything and `PUT`s it to `s3://///kafka-topics.tar` using - `curl --aws-sigv4`, verified against the CA from the Secret. + `curl` with a SigV4 signature the script computes, verified against the CA from the Secret. 4. The controller watches the Job's terminal condition. On `Complete` it creates a `Backup` CR in the same namespace, recording the BackupClass parameters under `spec.driverMetadata` (the `parameter/` prefix), so a later diff --git a/examples/backups/kafka/README.md b/examples/backups/kafka/README.md index 0a70558cd..5bed1b110 100644 --- a/examples/backups/kafka/README.md +++ b/examples/backups/kafka/README.md @@ -5,7 +5,7 @@ This directory shows how to back up and restore the **topic data** of a Cozystac - **backup**: freeze each partition's end offset, drain `[begin, end)` with `kafka-console-consumer` → `tar` → `PUT` the tarball to S3. - **restore**: `GET` the tarball from S3 → `tar -x` → recreate the topics with their original partition count and replication factor → replay every partition file with `kafka-console-producer`. -The same `PodTemplateSpec` serves both directions. The strategy engine templates each string field independently — it cannot add or remove containers per mode — so the single image branches at runtime on `{{ .Mode }}` (rendered into the `MODE` env var). Backup pushes to a key scoped by the source app (`{{ .Release.Name }}`); restore reads the key scoped by the backup's source (`{{ .Backup.ApplicationRef.Name }}`), so a to-copy restore lands the source's data into a differently-named target. The upload uses `curl --aws-sigv4`, so no purpose-built backup image is needed — a stock client image plus a shell script is the whole driver. +The same `PodTemplateSpec` serves both directions. The strategy engine templates each string field independently — it cannot add or remove containers per mode — so the single image branches at runtime on `{{ .Mode }}` (rendered into the `MODE` env var). Backup pushes to a key scoped by the source app (`{{ .Release.Name }}`); restore reads the key scoped by the backup's source (`{{ .Backup.ApplicationRef.Name }}`), so a to-copy restore lands the source's data into a differently-named target. The upload is a `curl` request the script SigV4-signs itself with `openssl` and `sha256sum`, so no purpose-built backup image is needed — a stock client image plus a shell script is the whole driver. It does not use `curl --aws-sigv4`: the curl in the Strimzi images cannot sign for S3 (see the comment above `s3()` in `01-create-strategy.sh`). ## Consistency model diff --git a/hack/kafka-backup-script.bats b/hack/kafka-backup-script.bats index e0b594ea4..74ec6a7d9 100644 --- a/hack/kafka-backup-script.bats +++ b/hack/kafka-backup-script.bats @@ -18,10 +18,10 @@ # $(...) capture (set -e makes a failed command fail the test). # # Each named guard below corresponds to a mutation the script must not survive: -# \Q literal-match on describe and alter, the --connect-to port workaround with -# no -k (keyed off the request host in both addressing modes), the fail-closed -# --list, the comma-value bracket grouping, the replication-factor divergence -# guard, and the cleanup delete's HTTP handling. +# \Q literal-match on describe and alter, the SigV4 signature (held to one +# botocore computes for the same request, in both addressing modes) with no -k, +# the fail-closed --list, the comma-value bracket grouping, the +# replication-factor divergence guard, and the cleanup delete's HTTP handling. load test_helper @@ -150,7 +150,14 @@ if [ -n "\$out" ]; then fi exit 0 STUB - chmod +x "$BINDIR"/*.sh "$PATHDIR/curl" + # date stub: a fixed signing time, so a request's signature is a constant the + # S3 signing tests can compare with an independently computed one. + cat > "$PATHDIR/date" <<'STUB' +#!/usr/bin/env bash +if [ "$*" = "-u +%Y%m%dT%H%M%SZ" ]; then echo 20261120T120000Z; exit 0; fi +exec /bin/date "$@" +STUB + chmod +x "$BINDIR"/*.sh "$PATHDIR/curl" "$PATHDIR/date" export BIN="$BINDIR" export PATH="$PATHDIR:$PATH" @@ -208,12 +215,26 @@ expect_fail() { grep -qxF "$(printf 'C\torders\tcleanup.policy\tcompact,delete')" "$STATE/s3_object" } -# ---- S3 signing (curl 7.76.1 port workaround, no -k) ----------------------- +# ---- S3 signing (SigV4 computed by the script, no -k) ------------------------ +# +# The expected signatures were computed with botocore 1.35.99 (S3SigV4Auth, +# payload signing on) for the same request: credentials k/s, region us-east-1 +# and the date stub's 20261120T120000Z. A signer that drifts from SigV4 — a +# wrong canonical Host, a key encoded twice or not at all, a header signed and +# not sent — produces a different signature and goes red here. -@test "ported endpoint signs with --connect-to and never -k" { - init_stubs; seed_three - MODE=backup S3_ENDPOINT="https://s3.example.org:8333" bash "$SCRIPT" - grep -qF -- '--connect-to s3.example.org:443:s3.example.org:8333' "$STATE/curl_args" +# expect_signed : the request went to , signed as botocore +# signs it. +expect_signed() { + grep -qF -- "$1" "$STATE/curl_args" || { echo "no request to $1: $(cat "$STATE/curl_args")" >&2; return 1; } + grep -qF -- "Signature=$2" "$STATE/curl_args" || { echo "signature is not botocore's $2: $(cat "$STATE/curl_args")" >&2; return 1; } +} + +@test "a ported endpoint signs the host:port curl sends, and never passes -k" { + init_stubs + MODE=cleanup S3_ENDPOINT="https://s3.example.org:8333" bash "$SCRIPT" + expect_signed https://s3.example.org:8333/bkt/ns/app/run/kafka-metadata.txt \ + 429859e912b812c5f16a50f45186ddaedffa32d7d6b89a0f3c781832f692046c # Positive form, not `! grep`: hack/cozytest.sh wraps each @test in `set -e` # + a trailing `return 0`, and bash exempts a `!`-negated command from errexit, # so a `! grep` guard can never fail under the runner CI uses (only real bats). @@ -222,22 +243,25 @@ expect_fail() { fi } -@test "default-port endpoint needs no --connect-to" { - init_stubs; seed_three - MODE=backup S3_ENDPOINT="https://s3.example.org" bash "$SCRIPT" - # Positive form (see the -k note above): a `! grep` is vacuous under cozytest. - if grep -qF -- '--connect-to' "$STATE/curl_args"; then - echo "unexpected --connect-to on a default-port endpoint: $(cat "$STATE/curl_args")" >&2; return 1 - fi +@test "a default-port endpoint signs the bare host and percent-encodes the key once" { + init_stubs + MODE=cleanup ARTIFACT_URI="s3://bkt/ns/app/run 1/ü+x.txt" S3_ENDPOINT="https://s3.example.org" bash "$SCRIPT" + expect_signed https://s3.example.org/bkt/ns/app/run%201/%C3%BC%2Bx.txt \ + 56ecae2ddc534434d56e410177f89d10795d5e29fefa5011ea38134d6e089d8e } -@test "virtual-hosted ported endpoint keys --connect-to off the bucket host" { +@test "a virtual-hosted ported endpoint signs the bucket host" { + init_stubs + MODE=cleanup S3_FORCE_PATH_STYLE=false S3_ENDPOINT="https://s3.example.org:8333" bash "$SCRIPT" + expect_signed https://bkt.s3.example.org:8333/ns/app/run/kafka-metadata.txt \ + 998307c7101ca8b4506f54fa3ecd06602d1b25565409a5754e3a19b067b747c7 +} + +@test "the upload declares the SHA-256 of the object it sends" { init_stubs; seed_three - MODE=backup S3_FORCE_PATH_STYLE=false S3_ENDPOINT="https://s3.example.org:8333" bash "$SCRIPT" - # HOST1 must be the request host (bkt.s3.example.org), else curl never - # redirects and the request hits the wrong port. - grep -qF -- '--connect-to bkt.s3.example.org:443:s3.example.org:8333' "$STATE/curl_args" - grep -qF 'https://bkt.s3.example.org/ns/app/run/kafka-metadata.txt' "$STATE/curl_args" + MODE=backup S3_ENDPOINT="https://s3.example.org" bash "$SCRIPT" + sum=$(sha256sum < "$STATE/s3_object" | cut -d' ' -f1) + grep -qF -- "x-amz-content-sha256: $sum" "$STATE/curl_args" } # ---- restore -------------------------------------------------------------- diff --git a/hack/kafka-topic-backup-strategy.bats b/hack/kafka-topic-backup-strategy.bats index 57830d8a7..c1dc0469f 100644 --- a/hack/kafka-topic-backup-strategy.bats +++ b/hack/kafka-topic-backup-strategy.bats @@ -179,7 +179,14 @@ if [ -n "$up" ]; then cp "$up" "$S3DIR/$key"; exit 0; fi [ -f "$S3DIR/$key" ] || { echo "curl: (22) The requested URL returned error: 404" >&2; exit 22; } cp "$S3DIR/$key" "$out" STUB - chmod +x "$BINDIR"/*.sh "$PATHDIR/curl" + # date stub: a fixed signing time, so a request's signature is a constant the + # S3 transport test can compare with an independently computed one. + cat > "$PATHDIR/date" <<'STUB' +#!/usr/bin/env bash +if [ "$*" = "-u +%Y%m%dT%H%M%SZ" ]; then echo 20261120T120000Z; exit 0; fi +exec /bin/date "$@" +STUB + chmod +x "$BINDIR"/*.sh "$PATHDIR/curl" "$PATHDIR/date" } # run_strategy [VAR=value ...]: runs the rendered script against the @@ -419,11 +426,26 @@ repack() { init_stubs; seed_broker "$STATE/broker" printf 'STUB PEM\n' > "$STATE/ca.crt" run_strategy backup - grep -qF -- "--cacert $STATE/ca.crt --connect-to seaweedfs-s3.tenant-root.svc:443:seaweedfs-s3.tenant-root.svc:8333 --aws-sigv4" "$STATE/curl_args" + grep -qF -- "-fsS --cacert $STATE/ca.crt -X PUT" "$STATE/curl_args" rm -f "$STATE/ca.crt" "$STATE/curl_args" run_strategy backup - grep -qF -- "-fsS --connect-to seaweedfs-s3.tenant-root.svc:443" "$STATE/curl_args" + grep -qF -- "-fsS -X PUT" "$STATE/curl_args" if grep -qE -- '(^| )-k( |$)|--cacert' "$STATE/curl_args"; then echo "unexpected TLS flags without a CA file: $(cat "$STATE/curl_args")" >&2; return 1 fi } + +# The expected signature was computed with botocore 1.35.99 (S3SigV4Auth, +# payload signing on) for the same GET: credentials k/s, region us-east-1 and +# the date stub's 20261120T120000Z. The endpoint carries the e2e harness's +# non-default :8333, which the signed Host has to keep. +@test "the restore download is SigV4-signed for the host:port curl sends" { + init_stubs; backup_then_target + : > "$STATE/curl_args" + BROKER="$STATE/tgt" run_strategy restore + grep -qF -- "-X GET" "$STATE/curl_args" + grep -qF -- "https://seaweedfs-s3.tenant-root.svc:8333/bkt/tenant-root/kafka-test/kafka-topics.tar" "$STATE/curl_args" + grep -qF -- "Signature=4069e37c9241b1687649dffba4a7515ee5e5100b96f48fd685a442509e695ea2" "$STATE/curl_args" || { + echo "signature is not botocore's: $(cat "$STATE/curl_args")" >&2; return 1 + } +} diff --git a/packages/system/backupstrategy-controller/files/kafka-backup.sh b/packages/system/backupstrategy-controller/files/kafka-backup.sh index 21419f0a4..e0b2ac18c 100644 --- a/packages/system/backupstrategy-controller/files/kafka-backup.sh +++ b/packages/system/backupstrategy-controller/files/kafka-backup.sh @@ -44,32 +44,67 @@ case "${hostport}" in *) host="${hostport%%:*}"; port="${hostport##*:}"; [ "${port}" = "${hostport}" ] && port="" ;; esac if [ "${scheme}" = http ]; then defport=80; else defport=443; fi -# curl 7.76.1 (this image) omits a NON-default port from the SigV4 canonical -# host but still sends it in the Host header, so the backend recomputes a -# different signature and 403s every request (fixed in curl 7.86.0). Sign and -# send a portless URL and redirect the connection to the real port with -# --connect-to, so signed, sent and server-side host all agree; correct on -# curl >= 7.86 too (which drops the default port anyway). No -k: TLS is -# verified against the endpoint's certificate (the platform endpoint is the -# ACME-valid ingress), matching strategy-rabbitmq-default.yaml. if [ "${S3_FORCE_PATH_STYLE}" = "false" ]; then reqhost="${bucket}.${host}" - obj_url="${scheme}://${reqhost}${pathpart}/${key}" + objpath="${pathpart}/${key}" else reqhost="${host}" - obj_url="${scheme}://${reqhost}${pathpart}/${bucket}/${key}" + objpath="${pathpart}/${bucket}/${key}" fi -# --connect-to matches HOST1 against the request host, which differs between -# path-style (${host}) and virtual-hosted (${bucket}.${host}) — key it off the -# host the URL actually uses so the redirect fires in both modes; the real -# connection target stays ${host}:${port}. -connect_to="" -if [ -n "${port}" ] && [ "${port}" != "${defport}" ]; then - connect_to="--connect-to ${reqhost}:${defport}:${host}:${port}" -fi -# ${connect_to} is unquoted so an empty value expands to no argument. -s3() { curl -fsS ${connect_to} --aws-sigv4 "aws:amz:${S3_REGION}:s3" \ - --user "${AWS_ACCESS_KEY_ID}:${AWS_SECRET_ACCESS_KEY}" "$@"; } +# The Host header curl sends, which is what gets signed: curl leaves the port +# out exactly when it is the scheme's default. +authority="${reqhost}" +if [ -n "${port}" ] && [ "${port}" != "${defport}" ]; then authority="${reqhost}:${port}"; fi + +# S3 canonical URI: every byte but the unreserved ones and "/" percent-encoded, +# once. The masked value keeps bash 3.2 from sign-extending a byte above 0x7f. +uri_path() { + local LC_ALL=C s=$1 out='' c i + for ((i = 0; i < ${#s}; i++)); do + c=${s:i:1} + case "${c}" in + [A-Za-z0-9._~/-]) out+=${c} ;; + *) printf -v c '%d' "'${c}"; printf -v c '%%%02X' "$((c & 255))"; out+=${c} ;; + esac + done + printf '%s' "${out}" +} +objpath=$(uri_path "${objpath}") +obj_url="${scheme}://${authority}${objpath}" + +EMPTY_SHA256=e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855 +hmac() { printf '%s' "$2" | openssl dgst -sha256 -mac HMAC -macopt "$1" -r | cut -d' ' -f1; } +# s3 METHOD PAYLOAD_SHA256 [curl args...] sends one SigV4-signed request for +# the object. The signature is computed here, not by curl --aws-sigv4, because +# the curl in the Strimzi image cannot sign for S3: 7.76.1-40.el9 (Strimzi +# 1.2) signs the Host without a non-default port while sending it with one, +# and 7.76.1-43.el9 (Strimzi 1.3.1) carries a RHEL backport of the S3 payload +# handling that lists x-amz-content-sha256 in SignedHeaders without ever +# sending the header. Either way the backend answers every request with 403. +# No -k: TLS is verified against the endpoint's certificate (the platform +# endpoint is the ACME-valid ingress), matching strategy-rabbitmq-default.yaml. +s3() { + local method=$1 payload=$2 now day scope creq sts k sig + shift 2 + now=$(date -u +%Y%m%dT%H%M%SZ) + day=${now%%T*} + scope="${day}/${S3_REGION}/s3/aws4_request" + creq=$(printf '%s\n%s\n\nhost:%s\nx-amz-content-sha256:%s\nx-amz-date:%s\n\nhost;x-amz-content-sha256;x-amz-date\n%s' \ + "${method}" "${objpath}" "${authority}" "${payload}" "${now}" "${payload}") + sts=$(printf 'AWS4-HMAC-SHA256\n%s\n%s\n%s' "${now}" "${scope}" "$(printf '%s' "${creq}" | sha256sum | cut -d' ' -f1)") + k=$(hmac "key:AWS4${AWS_SECRET_ACCESS_KEY}" "${day}") + k=$(hmac "hexkey:${k}" "${S3_REGION}") + k=$(hmac "hexkey:${k}" s3) + k=$(hmac "hexkey:${k}" aws4_request) + sig=$(hmac "hexkey:${k}" "${sts}") + # --path-as-is: curl would otherwise resolve dot segments in a key and send + # a path other than the one signed. + curl --path-as-is -X "${method}" \ + -H "x-amz-date: ${now}" \ + -H "x-amz-content-sha256: ${payload}" \ + -H "Authorization: AWS4-HMAC-SHA256 Credential=${AWS_ACCESS_KEY_ID}/${scope}, SignedHeaders=host;x-amz-content-sha256;x-amz-date, Signature=${sig}" \ + "$@" "${obj_url}" +} # Cleanup runs when the owning Backup is deleted: delete the object and exit # before any broker access (the source may already be gone). A missing object @@ -77,10 +112,7 @@ s3() { curl -fsS ${connect_to} --aws-sigv4 "aws:amz:${S3_REGION}:s3" \ # controller retries rather than orphaning the object. if [ "${MODE}" = cleanup ]; then echo "deleting ${ARTIFACT_URI}" - code=$(curl -sS -o /dev/null -w '%{http_code}' ${connect_to} \ - --aws-sigv4 "aws:amz:${S3_REGION}:s3" \ - --user "${AWS_ACCESS_KEY_ID}:${AWS_SECRET_ACCESS_KEY}" \ - -X DELETE "${obj_url}" || true) + code=$(s3 DELETE "${EMPTY_SHA256}" -sS -o /dev/null -w '%{http_code}' || true) case "${code}" in 2*|404) echo "deleted (HTTP ${code})"; exit 0 ;; *) echo "delete failed: HTTP ${code}" >&2; exit 1 ;; @@ -141,11 +173,11 @@ if [ "${MODE}" = backup ]; then fi echo " ${t}: partitions=${parts} rf=${rf}" done - s3 -X PUT --upload-file "${file}" "${obj_url}" + s3 PUT "$(sha256sum < "${file}" | cut -d' ' -f1)" -fsS --upload-file "${file}" echo "uploaded ${ARTIFACT_URI}" else echo "restoring Kafka topic metadata into ${BOOTSTRAP} from ${ARTIFACT_URI}" - s3 -o "${file}" "${obj_url}" + s3 GET "${EMPTY_SHA256}" -fsS -o "${file}" # Probe existence with --list, fail closed: a --describe under 2>/dev/null # cannot tell "topic absent" from "broker unreachable" (Kafka 3.9.1 exits 1 # for both, and the distinguishing text goes to stdout). --list instead fails