mirror of
https://github.com/pgsty/minio.git
synced 2026-11-27 17:44:06 +03:00
Compare commits
100 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| 770ccfc6ef | |||
| 14d89a9735 | |||
| 65090cfb59 | |||
| 67c5b5c49f | |||
| 9c50c34c44 | |||
| 04b097fd9f | |||
| ab3ae99ca3 | |||
| 5db7be4ee4 | |||
| ff44527a3c | |||
| c9ad746732 | |||
| f3438b2602 | |||
| 938603458d | |||
| d5e763b072 | |||
| 74c97d005d | |||
| 1be684ba29 | |||
| 1367364c40 | |||
| 5f44fe369c | |||
| c6cc136833 | |||
| 97e31af331 | |||
| 0507c3d56a | |||
| 87b9895bc0 | |||
| ca1f11b708 | |||
| 514a041f4a | |||
| f8106cd693 | |||
| b1ba685ac5 | |||
| bc7658f035 | |||
| f377b5c95b | |||
| 45381222b7 | |||
| 4d6e1ea8ea | |||
| 20aaefa89c | |||
| 82509ddc0a | |||
| f2ba439022 | |||
| 2ba1f38503 | |||
| 8d58343263 | |||
| 2b2e0d2a5d | |||
| e407dc58eb | |||
| 32b2aa49f1 | |||
| 8448512a1f | |||
| 150e7b5f9e | |||
| 21870fa2e7 | |||
| d4c8da162b | |||
| fc7bf7b295 | |||
| d28885d0e5 | |||
| c4fd97d0bf | |||
| b73581b05d | |||
| 474cd5801e | |||
| ee9252a608 | |||
| fb406fdc94 | |||
| dd3bdb8086 | |||
| 7c103389f5 | |||
| 3861f33cba | |||
| 07d92db523 | |||
| 5732930102 | |||
| 2aea7fe9c4 | |||
| ffb70eb373 | |||
| e73436c99d | |||
| 0b0ae2423a | |||
| 7e079ff05c | |||
| 229fe2b3c3 | |||
| 38ed9d1e1f | |||
| 47cd7807d3 | |||
| 04d3d316d2 | |||
| 4bb8c813ac | |||
| b6ef7e430c | |||
| 91d9091758 | |||
| 0eebc928f7 | |||
| 724f8703d8 | |||
| e4e3007da6 | |||
| 13e6458d90 | |||
| 590aeaa7d1 | |||
| 5d152416de | |||
| edc8be6ed1 | |||
| 49c8aeac40 | |||
| e9c5340be9 | |||
| 2e2377d1c6 | |||
| 58735ee382 | |||
| a96116b128 | |||
| c4b9d38d8a | |||
| 8d76a255c4 | |||
| c5bc57b7a3 | |||
| 3814818537 | |||
| 7a49a7a3da | |||
| ff3395d3c6 | |||
| ce4525632f | |||
| 1c9a2431fe | |||
| f2520f3346 | |||
| 05df6e70d7 | |||
| c0e7159771 | |||
| 56c67dacf1 | |||
| eee05a17c3 | |||
| 45eb2e423d | |||
| 6b0998157c | |||
| 7fea6d5a5f | |||
| 68eeb002f6 | |||
| c565987b9c | |||
| f1ba683582 | |||
| 43f4bb7ed4 | |||
| d014a12cff | |||
| 100e2e57a7 | |||
| 6e20e74774 |
@@ -77,8 +77,10 @@ release:
|
||||
name: silo
|
||||
draft: true
|
||||
prerelease: false
|
||||
mode: append
|
||||
replace_existing_draft: true
|
||||
replace_existing_artifacts: false
|
||||
mode: replace
|
||||
# Draft replacement matches the release name; keep it identical to the tag.
|
||||
name_template: "{{ .Tag }}"
|
||||
|
||||
changelog:
|
||||
|
||||
@@ -23,7 +23,7 @@ permissions:
|
||||
artifact-metadata: write
|
||||
|
||||
concurrency:
|
||||
group: finalize-release
|
||||
group: release-${{ inputs.tag }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
|
||||
@@ -1,5 +1,10 @@
|
||||
name: Release
|
||||
|
||||
# Retry contract: an absent or single unfinalized Draft may be rebuilt from
|
||||
# scratch; a published release or a Draft carrying finalize's GPG-derived
|
||||
# provenance marker is terminal for this lane. The per-tag lock serializes
|
||||
# workflows, but a maintainer must not publish the Draft while this job runs.
|
||||
|
||||
on:
|
||||
push:
|
||||
tags:
|
||||
@@ -16,6 +21,10 @@ permissions:
|
||||
attestations: write
|
||||
artifact-metadata: write
|
||||
|
||||
concurrency:
|
||||
group: release-${{ github.event_name == 'workflow_dispatch' && inputs.tag || github.ref_name }}
|
||||
cancel-in-progress: false
|
||||
|
||||
jobs:
|
||||
release:
|
||||
runs-on: ubuntu-latest
|
||||
@@ -78,6 +87,15 @@ jobs:
|
||||
echo "Invalid release tag format: ${TAG}" >&2
|
||||
exit 1
|
||||
fi
|
||||
if ! TAG_COMMIT="$(git rev-parse "${TAG}^{commit}" 2>/dev/null)"; then
|
||||
echo "Release tag ${TAG} does not resolve to a commit" >&2
|
||||
exit 1
|
||||
fi
|
||||
HEAD_COMMIT="$(git rev-parse HEAD)"
|
||||
if [ "${TAG_COMMIT}" != "${HEAD_COMMIT}" ]; then
|
||||
echo "Release tag ${TAG} resolves to ${TAG_COMMIT}, checkout is ${HEAD_COMMIT}" >&2
|
||||
exit 1
|
||||
fi
|
||||
VERSION_HYPHEN="${TAG#RELEASE.}"
|
||||
PKG_VERSION="$(echo "${VERSION_HYPHEN}" | sed -E 's/^([0-9]{4})-([0-9]{2})-([0-9]{2})T([0-9]{2})-([0-9]{2})-([0-9]{2})Z$/\1\2\3\4\5\6.0.0/')"
|
||||
VERSION_COLON="$(echo "${VERSION_HYPHEN}" | sed -E 's/T([0-9]{2})-([0-9]{2})-([0-9]{2})Z$/T\1:\2:\3Z/')"
|
||||
@@ -93,6 +111,13 @@ jobs:
|
||||
echo "Package version: ${PKG_VERSION}"
|
||||
echo "LDFLAGS: ${LDFLAGS}"
|
||||
|
||||
- name: Check existing release state
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
run: |
|
||||
set -euo pipefail
|
||||
buildscripts/check-release-state.sh "${RELEASE_TAG}"
|
||||
|
||||
# Both installer actions are pinned to immutable commits. The explicit
|
||||
# tool versions keep the release format reproducible across workflow
|
||||
# reruns while the installers verify the downloaded executables.
|
||||
@@ -113,6 +138,7 @@ jobs:
|
||||
args: release --clean --skip=validate --config .github/goreleaser.yml
|
||||
env:
|
||||
GITHUB_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
GORELEASER_CURRENT_TAG: ${{ env.RELEASE_TAG }}
|
||||
LDFLAGS: ${{ env.LDFLAGS }}
|
||||
PKG_VERSION: ${{ env.PKG_VERSION }}
|
||||
|
||||
@@ -189,6 +215,14 @@ jobs:
|
||||
test -s "${BUNDLE_PATH}"
|
||||
cp "${BUNDLE_PATH}" "dist/silo_${PKG_VERSION}_provenance.sigstore.json"
|
||||
|
||||
- name: Confirm unfinalized Draft release state
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
REQUIRE_DRAFT: "true"
|
||||
run: |
|
||||
set -euo pipefail
|
||||
buildscripts/check-release-state.sh "${RELEASE_TAG}"
|
||||
|
||||
- name: Upload nFPM packages to Draft release
|
||||
env:
|
||||
GH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
|
||||
|
||||
@@ -23,6 +23,8 @@ on:
|
||||
- "buildscripts/minio-upgrade.sh"
|
||||
- "buildscripts/sign-release-rpms.sh"
|
||||
- "buildscripts/verify-build-provenance.sh"
|
||||
- "buildscripts/check-release-state.sh"
|
||||
- "buildscripts/check-release-state_test.sh"
|
||||
- "buildscripts/verify-rebrand.sh"
|
||||
- "buildscripts/verify-helm-migration.sh"
|
||||
- "buildscripts/helm-migration-guard/**"
|
||||
@@ -479,6 +481,8 @@ jobs:
|
||||
bash -n buildscripts/minio-upgrade.sh
|
||||
bash -n buildscripts/sign-release-rpms.sh
|
||||
bash -n buildscripts/verify-build-provenance.sh
|
||||
bash -n buildscripts/check-release-state.sh
|
||||
bash -n buildscripts/check-release-state_test.sh
|
||||
bash -n buildscripts/verify-rebrand.sh
|
||||
bash -n buildscripts/verify-helm-migration.sh
|
||||
sh -n buildscripts/package/postinstall.sh
|
||||
@@ -493,9 +497,12 @@ jobs:
|
||||
test -x buildscripts/package-release.sh
|
||||
test -x buildscripts/sign-release-rpms.sh
|
||||
test -x buildscripts/verify-build-provenance.sh
|
||||
test -x buildscripts/check-release-state.sh
|
||||
test -x buildscripts/check-release-state_test.sh
|
||||
test -x buildscripts/verify-rebrand.sh
|
||||
test -x buildscripts/verify-helm-migration.sh
|
||||
test -x buildscripts/package/postinstall.sh
|
||||
test -x buildscripts/package/preremove.sh
|
||||
test -x buildscripts/package/lifecycle_test.sh
|
||||
test -x dockerscripts/docker-entrypoint_test.sh
|
||||
buildscripts/check-release-state_test.sh
|
||||
|
||||
@@ -29,7 +29,7 @@ jobs:
|
||||
|
||||
- name: Install govulncheck
|
||||
run: |
|
||||
go install golang.org/x/vuln/cmd/govulncheck@v1.6.0
|
||||
go install golang.org/x/vuln/cmd/govulncheck@v1.7.0
|
||||
echo "$(go env GOPATH)/bin" >> "${GITHUB_PATH}"
|
||||
|
||||
- name: Run govulncheck
|
||||
|
||||
@@ -59,6 +59,9 @@ formatters:
|
||||
exclusions:
|
||||
generated: lax
|
||||
paths:
|
||||
# gofumpt v0.11.0 and Go 1.27's gofmt disagree on the indentation of
|
||||
# multiple composite literals returned from a single statement.
|
||||
- internal/ioutil/wait_pipe\.go$
|
||||
- third_party$
|
||||
- builtin$
|
||||
- examples$
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
# Contributors
|
||||
|
||||
Silo is maintained by the Pigsty community. This file records the people who have contributed to
|
||||
this fork since it was established in 2026 — merged code, proposed changes, and the bug reports and
|
||||
compatibility findings that shaped the releases.
|
||||
|
||||
It is maintained by hand and updated at each release. GitHub's own contributor graph is unavailable
|
||||
here because `pgsty/silo` is a fork, so this file — not that page — is the project's attribution
|
||||
record. Contributors are listed by GitHub handle. Authorship of every merged commit is preserved in
|
||||
the Git history and can be verified with `git log --format='%an <%ae>'`.
|
||||
|
||||
Upstream MinIO authorship is recorded separately: this fork derives from
|
||||
[`minio/minio`](https://github.com/minio/minio), [`NOTICE`](NOTICE) retains the upstream product
|
||||
notice, and the Git history carries the full upstream commit record.
|
||||
|
||||
## Code
|
||||
|
||||
Contributors whose changes are merged into `main`.
|
||||
|
||||
| Contributor | Change | Pull request | Commit |
|
||||
| :-- | :-- | :-- | :-- |
|
||||
| [@ZouhairCharef](https://github.com/ZouhairCharef) | Upgraded `go-jose` to v4.1.4 to patch CVE-2026-34986 | [#18](https://github.com/pgsty/silo/pull/18) | [`68e0ba9`](https://github.com/pgsty/silo/commit/68e0ba997) |
|
||||
| [@mfredenhagen](https://github.com/mfredenhagen) | Bumped `go.opentelemetry.io` to address CVE-2026-39883 | [#19](https://github.com/pgsty/silo/pull/19) | [`1869bd3`](https://github.com/pgsty/silo/commit/1869bd30b) |
|
||||
| [@pinginfo](https://github.com/pinginfo) | Implemented `Flush` on `trackingResponseWriter`, repairing bucket notification streaming | [#34](https://github.com/pgsty/silo/pull/34) | [`65795ee`](https://github.com/pgsty/silo/commit/65795ee1f) |
|
||||
| [@waterkip](https://github.com/waterkip) | Repointed documentation links from the upstream domain to the Silo portal | [#41](https://github.com/pgsty/silo/pull/41) | [`d495d30`](https://github.com/pgsty/silo/commit/d495d30d5) |
|
||||
|
||||
## Proposed changes
|
||||
|
||||
Pull requests that are open for review, or that were closed after informing work that shipped
|
||||
differently.
|
||||
|
||||
| Contributor | Change | Pull request | Status |
|
||||
| :-- | :-- | :-- | :-- |
|
||||
| [@magicxor](https://github.com/magicxor) | `DELETE` precondition checks for the `If-Match` header | [#12](https://github.com/pgsty/silo/pull/12) | Open, queued for review |
|
||||
| [@ycjlin](https://github.com/ycjlin) | `ListObjects` should return `NoSuchBucket` for a prefix on a missing bucket | [#37](https://github.com/pgsty/silo/pull/37) | Open, queued for review |
|
||||
| [@davinkevin](https://github.com/davinkevin) | Distroless-based Docker image variant | [#21](https://github.com/pgsty/silo/pull/21) | Superseded by the distroless variant shipped in RELEASE.2026-08-06, which the PR anticipated by four months |
|
||||
| [@lem21h](https://github.com/lem21h) | Assorted fixes and improvements | [#36](https://github.com/pgsty/silo/pull/36) | Closed |
|
||||
| [@sulin37392](https://github.com/sulin37392) | Dependency updates against the fork | [#8](https://github.com/pgsty/silo/pull/8) | Closed |
|
||||
|
||||
## Reports
|
||||
|
||||
Bug reports, compatibility findings, and proposals filed against this fork. Several shipped fixes
|
||||
trace directly back to these: the bundled-client guarantee (#4, #9), the LDAP-over-TLS repair (#15),
|
||||
the completed native package payload (#33), GPG-signed RPMs (#43), and the upstream migration guide
|
||||
(#42).
|
||||
|
||||
| Contributor | Reported |
|
||||
| :-- | :-- |
|
||||
| [@mosesdd](https://github.com/mosesdd) | [#1](https://github.com/pgsty/silo/issues/1) Helm chart availability |
|
||||
| [@Xavier-777](https://github.com/Xavier-777) | [#2](https://github.com/pgsty/silo/issues/2) Console bucket lifecycle management · [#17](https://github.com/pgsty/silo/issues/17) Log and XML file preview |
|
||||
| [@jiadzh](https://github.com/jiadzh) | [#3](https://github.com/pgsty/silo/issues/3) Windows build guidance |
|
||||
| [@TLINDEN](https://github.com/TLINDEN) | [#4](https://github.com/pgsty/silo/issues/4) `mc` missing from released tarballs |
|
||||
| [@AntonOfTheWoods](https://github.com/AntonOfTheWoods) | [#5](https://github.com/pgsty/silo/issues/5) Upstream Helm chart and operator options |
|
||||
| [@zylpsrs](https://github.com/zylpsrs) | [#6](https://github.com/pgsty/silo/issues/6) Console missing Tiering and Site Replication |
|
||||
| [@nsanitate](https://github.com/nsanitate) | [#7](https://github.com/pgsty/silo/issues/7) CNCF Sandbox governance proposal |
|
||||
| [@makinikm](https://github.com/makinikm) | [#9](https://github.com/pgsty/silo/issues/9) `mc` missing from the Docker image |
|
||||
| [@magicxor](https://github.com/magicxor) | [#10](https://github.com/pgsty/silo/issues/10) `DeleteObject` ignores the `If-Match` header |
|
||||
| [@spaceg00se-r](https://github.com/spaceg00se-r) | [#11](https://github.com/pgsty/silo/issues/11) `cpuv1` support · [#14](https://github.com/pgsty/silo/issues/14) Project workflow token failure |
|
||||
| [@heroes1412](https://github.com/heroes1412) | [#13](https://github.com/pgsty/silo/issues/13) Profile option unusable |
|
||||
| [@vampywiz17](https://github.com/vampywiz17) | [#15](https://github.com/pgsty/silo/issues/15) LDAP TLS regression breaking Console login on Kubernetes |
|
||||
| [@davinkevin](https://github.com/davinkevin) | [#20](https://github.com/pgsty/silo/issues/20) Renovate for automated dependency updates |
|
||||
| [@chalukyaj](https://github.com/chalukyaj) | [#30](https://github.com/pgsty/silo/issues/30) Silo Operator discoverability |
|
||||
| [@cbornet](https://github.com/cbornet) | [#31](https://github.com/pgsty/silo/issues/31) Multipart uploads with `FULL_OBJECT` CRC32 · [#32](https://github.com/pgsty/silo/issues/32) `ListObjects` bucket-existence semantics |
|
||||
| [@jvasile](https://github.com/jvasile) | [#33](https://github.com/pgsty/silo/issues/33) `.deb` missing user, group, and default files |
|
||||
| [@Kesavaambati](https://github.com/Kesavaambati) | [#35](https://github.com/pgsty/silo/issues/35) Community support for the Docker images |
|
||||
| [@redfoxfox](https://github.com/redfoxfox) | [#38](https://github.com/pgsty/silo/issues/38) Chinese documentation site unreachable |
|
||||
| [@kuldeep-link11](https://github.com/kuldeep-link11) | [#39](https://github.com/pgsty/silo/issues/39) `notify_nats` rejects JWT credentials files · [#40](https://github.com/pgsty/silo/issues/40) `notify_nats` target changes require a restart |
|
||||
| [@meesudzu](https://github.com/meesudzu) | [#42](https://github.com/pgsty/silo/issues/42) Migration guide from upstream MinIO |
|
||||
| [@pmezhuev](https://github.com/pmezhuev) | [#43](https://github.com/pgsty/silo/issues/43) RPM package missing its GPG signature |
|
||||
| [@kh0mka](https://github.com/kh0mka) | [#51](https://github.com/pgsty/silo/issues/51) Inter-node I/O timeout in `ReadFileStreamHandler` |
|
||||
|
||||
## Adding yourself
|
||||
|
||||
Contributions are accepted inbound=outbound under AGPL-3.0-or-later with no CLA; see
|
||||
[`CONTRIBUTING.md`](CONTRIBUTING.md). Merged pull requests are added here at the next release. If a
|
||||
contribution is missing or recorded incorrectly, open an issue or say so on the pull request and it
|
||||
will be fixed.
|
||||
@@ -3396,7 +3396,7 @@ SOFTWARE.
|
||||
github.com/cheggaaa/pb
|
||||
https://github.com/cheggaaa/pb
|
||||
----------------------------------------------------------------
|
||||
Copyright (c) 2012-2015, Sergey Cherepanov
|
||||
Copyright (c) 2012-2024, Sergey Cherepanov
|
||||
All rights reserved.
|
||||
|
||||
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
|
||||
@@ -6218,203 +6218,6 @@ SOFTWARE.
|
||||
|
||||
================================================================
|
||||
|
||||
github.com/go-ini/ini
|
||||
https://github.com/go-ini/ini
|
||||
----------------------------------------------------------------
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction, and
|
||||
distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by the copyright
|
||||
owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all other entities
|
||||
that control, are controlled by, or are under common control with that entity.
|
||||
For the purposes of this definition, "control" means (i) the power, direct or
|
||||
indirect, to cause the direction or management of such entity, whether by
|
||||
contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity exercising
|
||||
permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications, including
|
||||
but not limited to software source code, documentation source, and configuration
|
||||
files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical transformation or
|
||||
translation of a Source form, including but not limited to compiled object code,
|
||||
generated documentation, and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or Object form, made
|
||||
available under the License, as indicated by a copyright notice that is included
|
||||
in or attached to the work (an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object form, that
|
||||
is based on (or derived from) the Work and for which the editorial revisions,
|
||||
annotations, elaborations, or other modifications represent, as a whole, an
|
||||
original work of authorship. For the purposes of this License, Derivative Works
|
||||
shall not include works that remain separable from, or merely link (or bind by
|
||||
name) to the interfaces of, the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including the original version
|
||||
of the Work and any modifications or additions to that Work or Derivative Works
|
||||
thereof, that is intentionally submitted to Licensor for inclusion in the Work
|
||||
by the copyright owner or by an individual or Legal Entity authorized to submit
|
||||
on behalf of the copyright owner. For the purposes of this definition,
|
||||
"submitted" means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems, and
|
||||
issue tracking systems that are managed by, or on behalf of, the Licensor for
|
||||
the purpose of discussing and improving the Work, but excluding communication
|
||||
that is conspicuously marked or otherwise designated in writing by the copyright
|
||||
owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
|
||||
of whom a Contribution has been received by Licensor and subsequently
|
||||
incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License.
|
||||
|
||||
Subject to the terms and conditions of this License, each Contributor hereby
|
||||
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
||||
irrevocable copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the Work and such
|
||||
Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License.
|
||||
|
||||
Subject to the terms and conditions of this License, each Contributor hereby
|
||||
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
||||
irrevocable (except as stated in this section) patent license to make, have
|
||||
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
|
||||
such license applies only to those patent claims licensable by such Contributor
|
||||
that are necessarily infringed by their Contribution(s) alone or by combination
|
||||
of their Contribution(s) with the Work to which such Contribution(s) was
|
||||
submitted. If You institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
|
||||
Contribution incorporated within the Work constitutes direct or contributory
|
||||
patent infringement, then any patent licenses granted to You under this License
|
||||
for that Work shall terminate as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution.
|
||||
|
||||
You may reproduce and distribute copies of the Work or Derivative Works thereof
|
||||
in any medium, with or without modifications, and in Source or Object form,
|
||||
provided that You meet the following conditions:
|
||||
|
||||
You must give any other recipients of the Work or Derivative Works a copy of
|
||||
this License; and
|
||||
You must cause any modified files to carry prominent notices stating that You
|
||||
changed the files; and
|
||||
You must retain, in the Source form of any Derivative Works that You distribute,
|
||||
all copyright, patent, trademark, and attribution notices from the Source form
|
||||
of the Work, excluding those notices that do not pertain to any part of the
|
||||
Derivative Works; and
|
||||
If the Work includes a "NOTICE" text file as part of its distribution, then any
|
||||
Derivative Works that You distribute must include a readable copy of the
|
||||
attribution notices contained within such NOTICE file, excluding those notices
|
||||
that do not pertain to any part of the Derivative Works, in at least one of the
|
||||
following places: within a NOTICE text file distributed as part of the
|
||||
Derivative Works; within the Source form or documentation, if provided along
|
||||
with the Derivative Works; or, within a display generated by the Derivative
|
||||
Works, if and wherever such third-party notices normally appear. The contents of
|
||||
the NOTICE file are for informational purposes only and do not modify the
|
||||
License. You may add Your own attribution notices within Derivative Works that
|
||||
You distribute, alongside or as an addendum to the NOTICE text from the Work,
|
||||
provided that such additional attribution notices cannot be construed as
|
||||
modifying the License.
|
||||
You may add Your own copyright statement to Your modifications and may provide
|
||||
additional or different license terms and conditions for use, reproduction, or
|
||||
distribution of Your modifications, or for any such Derivative Works as a whole,
|
||||
provided Your use, reproduction, and distribution of the Work otherwise complies
|
||||
with the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions.
|
||||
|
||||
Unless You explicitly state otherwise, any Contribution intentionally submitted
|
||||
for inclusion in the Work by You to the Licensor shall be under the terms and
|
||||
conditions of this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify the terms of
|
||||
any separate license agreement you may have executed with Licensor regarding
|
||||
such Contributions.
|
||||
|
||||
6. Trademarks.
|
||||
|
||||
This License does not grant permission to use the trade names, trademarks,
|
||||
service marks, or product names of the Licensor, except as required for
|
||||
reasonable and customary use in describing the origin of the Work and
|
||||
reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty.
|
||||
|
||||
Unless required by applicable law or agreed to in writing, Licensor provides the
|
||||
Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
|
||||
including, without limitation, any warranties or conditions of TITLE,
|
||||
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
|
||||
solely responsible for determining the appropriateness of using or
|
||||
redistributing the Work and assume any risks associated with Your exercise of
|
||||
permissions under this License.
|
||||
|
||||
8. Limitation of Liability.
|
||||
|
||||
In no event and under no legal theory, whether in tort (including negligence),
|
||||
contract, or otherwise, unless required by applicable law (such as deliberate
|
||||
and grossly negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special, incidental,
|
||||
or consequential damages of any character arising as a result of this License or
|
||||
out of the use or inability to use the Work (including but not limited to
|
||||
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
|
||||
any and all other commercial damages or losses), even if such Contributor has
|
||||
been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability.
|
||||
|
||||
While redistributing the Work or Derivative Works thereof, You may choose to
|
||||
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
|
||||
other liability obligations and/or rights consistent with this License. However,
|
||||
in accepting such obligations, You may act only on Your own behalf and on Your
|
||||
sole responsibility, not on behalf of any other Contributor, and only if You
|
||||
agree to indemnify, defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason of your
|
||||
accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work
|
||||
|
||||
To apply the Apache License to your work, attach the following boilerplate
|
||||
notice, with the fields enclosed by brackets "[]" replaced with your own
|
||||
identifying information. (Don't include the brackets!) The text should be
|
||||
enclosed in the appropriate comment syntax for the file format. We also
|
||||
recommend that a file or class name and description of purpose be included on
|
||||
the same "printed page" as the copyright notice for easier identification within
|
||||
third-party archives.
|
||||
|
||||
Copyright 2014 Unknwon
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
================================================================
|
||||
|
||||
github.com/go-jose/go-jose/v4
|
||||
https://github.com/go-jose/go-jose/v4
|
||||
----------------------------------------------------------------
|
||||
@@ -16641,33 +16444,6 @@ SOFTWARE.
|
||||
|
||||
================================================================
|
||||
|
||||
github.com/lestrrat-go/option
|
||||
https://github.com/lestrrat-go/option
|
||||
----------------------------------------------------------------
|
||||
MIT License
|
||||
|
||||
Copyright (c) 2021 lestrrat-go
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all
|
||||
copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
||||
SOFTWARE.
|
||||
|
||||
================================================================
|
||||
|
||||
github.com/lestrrat-go/option/v2
|
||||
https://github.com/lestrrat-go/option/v2
|
||||
----------------------------------------------------------------
|
||||
@@ -21713,6 +21489,14 @@ separate copyright notices and license terms. Your use of the source
|
||||
code for the these subcomponents is subject to the terms and conditions
|
||||
of the following licenses.
|
||||
|
||||
===
|
||||
|
||||
This distribution (pgsty/mc, shipped as "mcli") is a community-maintained
|
||||
fork of the MinIO Client, modified by the Silo project
|
||||
(https://silo.pgsty.com/). It is not affiliated with, endorsed by, or
|
||||
sponsored by MinIO, Inc. Modifications are Copyright (c) 2025-2026 PGSTY
|
||||
and are licensed under the GNU AGPL v3.0 or later.
|
||||
|
||||
================================================================
|
||||
|
||||
github.com/minio/md5-simd
|
||||
@@ -21923,8 +21707,8 @@ https://github.com/minio/md5-simd
|
||||
|
||||
================================================================
|
||||
|
||||
github.com/minio/minio-go/v7
|
||||
https://github.com/minio/minio-go/v7
|
||||
github.com/minio/minio-go/v7 (replaced by github.com/pgsty/silo-go/v7)
|
||||
https://github.com/pgsty/silo-go/v7
|
||||
----------------------------------------------------------------
|
||||
|
||||
Apache License
|
||||
@@ -28982,7 +28766,7 @@ https://go.etcd.io/etcd/api/v3
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
Copyright 2020 The etcd Authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
@@ -29190,7 +28974,7 @@ https://go.etcd.io/etcd/client/pkg/v3
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
Copyright 2020 The etcd Authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
@@ -29398,7 +29182,7 @@ https://go.etcd.io/etcd/client/v3
|
||||
same "printed page" as the copyright notice for easier
|
||||
identification within third-party archives.
|
||||
|
||||
Copyright [yyyy] [name of copyright owner]
|
||||
Copyright 2020 The etcd Authors
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
@@ -33091,6 +32875,203 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
|
||||
================================================================
|
||||
|
||||
gopkg.in/ini.v1
|
||||
https://gopkg.in/ini.v1
|
||||
----------------------------------------------------------------
|
||||
Apache License
|
||||
Version 2.0, January 2004
|
||||
http://www.apache.org/licenses/
|
||||
|
||||
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
||||
|
||||
1. Definitions.
|
||||
|
||||
"License" shall mean the terms and conditions for use, reproduction, and
|
||||
distribution as defined by Sections 1 through 9 of this document.
|
||||
|
||||
"Licensor" shall mean the copyright owner or entity authorized by the copyright
|
||||
owner that is granting the License.
|
||||
|
||||
"Legal Entity" shall mean the union of the acting entity and all other entities
|
||||
that control, are controlled by, or are under common control with that entity.
|
||||
For the purposes of this definition, "control" means (i) the power, direct or
|
||||
indirect, to cause the direction or management of such entity, whether by
|
||||
contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
||||
outstanding shares, or (iii) beneficial ownership of such entity.
|
||||
|
||||
"You" (or "Your") shall mean an individual or Legal Entity exercising
|
||||
permissions granted by this License.
|
||||
|
||||
"Source" form shall mean the preferred form for making modifications, including
|
||||
but not limited to software source code, documentation source, and configuration
|
||||
files.
|
||||
|
||||
"Object" form shall mean any form resulting from mechanical transformation or
|
||||
translation of a Source form, including but not limited to compiled object code,
|
||||
generated documentation, and conversions to other media types.
|
||||
|
||||
"Work" shall mean the work of authorship, whether in Source or Object form, made
|
||||
available under the License, as indicated by a copyright notice that is included
|
||||
in or attached to the work (an example is provided in the Appendix below).
|
||||
|
||||
"Derivative Works" shall mean any work, whether in Source or Object form, that
|
||||
is based on (or derived from) the Work and for which the editorial revisions,
|
||||
annotations, elaborations, or other modifications represent, as a whole, an
|
||||
original work of authorship. For the purposes of this License, Derivative Works
|
||||
shall not include works that remain separable from, or merely link (or bind by
|
||||
name) to the interfaces of, the Work and Derivative Works thereof.
|
||||
|
||||
"Contribution" shall mean any work of authorship, including the original version
|
||||
of the Work and any modifications or additions to that Work or Derivative Works
|
||||
thereof, that is intentionally submitted to Licensor for inclusion in the Work
|
||||
by the copyright owner or by an individual or Legal Entity authorized to submit
|
||||
on behalf of the copyright owner. For the purposes of this definition,
|
||||
"submitted" means any form of electronic, verbal, or written communication sent
|
||||
to the Licensor or its representatives, including but not limited to
|
||||
communication on electronic mailing lists, source code control systems, and
|
||||
issue tracking systems that are managed by, or on behalf of, the Licensor for
|
||||
the purpose of discussing and improving the Work, but excluding communication
|
||||
that is conspicuously marked or otherwise designated in writing by the copyright
|
||||
owner as "Not a Contribution."
|
||||
|
||||
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf
|
||||
of whom a Contribution has been received by Licensor and subsequently
|
||||
incorporated within the Work.
|
||||
|
||||
2. Grant of Copyright License.
|
||||
|
||||
Subject to the terms and conditions of this License, each Contributor hereby
|
||||
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
||||
irrevocable copyright license to reproduce, prepare Derivative Works of,
|
||||
publicly display, publicly perform, sublicense, and distribute the Work and such
|
||||
Derivative Works in Source or Object form.
|
||||
|
||||
3. Grant of Patent License.
|
||||
|
||||
Subject to the terms and conditions of this License, each Contributor hereby
|
||||
grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free,
|
||||
irrevocable (except as stated in this section) patent license to make, have
|
||||
made, use, offer to sell, sell, import, and otherwise transfer the Work, where
|
||||
such license applies only to those patent claims licensable by such Contributor
|
||||
that are necessarily infringed by their Contribution(s) alone or by combination
|
||||
of their Contribution(s) with the Work to which such Contribution(s) was
|
||||
submitted. If You institute patent litigation against any entity (including a
|
||||
cross-claim or counterclaim in a lawsuit) alleging that the Work or a
|
||||
Contribution incorporated within the Work constitutes direct or contributory
|
||||
patent infringement, then any patent licenses granted to You under this License
|
||||
for that Work shall terminate as of the date such litigation is filed.
|
||||
|
||||
4. Redistribution.
|
||||
|
||||
You may reproduce and distribute copies of the Work or Derivative Works thereof
|
||||
in any medium, with or without modifications, and in Source or Object form,
|
||||
provided that You meet the following conditions:
|
||||
|
||||
You must give any other recipients of the Work or Derivative Works a copy of
|
||||
this License; and
|
||||
You must cause any modified files to carry prominent notices stating that You
|
||||
changed the files; and
|
||||
You must retain, in the Source form of any Derivative Works that You distribute,
|
||||
all copyright, patent, trademark, and attribution notices from the Source form
|
||||
of the Work, excluding those notices that do not pertain to any part of the
|
||||
Derivative Works; and
|
||||
If the Work includes a "NOTICE" text file as part of its distribution, then any
|
||||
Derivative Works that You distribute must include a readable copy of the
|
||||
attribution notices contained within such NOTICE file, excluding those notices
|
||||
that do not pertain to any part of the Derivative Works, in at least one of the
|
||||
following places: within a NOTICE text file distributed as part of the
|
||||
Derivative Works; within the Source form or documentation, if provided along
|
||||
with the Derivative Works; or, within a display generated by the Derivative
|
||||
Works, if and wherever such third-party notices normally appear. The contents of
|
||||
the NOTICE file are for informational purposes only and do not modify the
|
||||
License. You may add Your own attribution notices within Derivative Works that
|
||||
You distribute, alongside or as an addendum to the NOTICE text from the Work,
|
||||
provided that such additional attribution notices cannot be construed as
|
||||
modifying the License.
|
||||
You may add Your own copyright statement to Your modifications and may provide
|
||||
additional or different license terms and conditions for use, reproduction, or
|
||||
distribution of Your modifications, or for any such Derivative Works as a whole,
|
||||
provided Your use, reproduction, and distribution of the Work otherwise complies
|
||||
with the conditions stated in this License.
|
||||
|
||||
5. Submission of Contributions.
|
||||
|
||||
Unless You explicitly state otherwise, any Contribution intentionally submitted
|
||||
for inclusion in the Work by You to the Licensor shall be under the terms and
|
||||
conditions of this License, without any additional terms or conditions.
|
||||
Notwithstanding the above, nothing herein shall supersede or modify the terms of
|
||||
any separate license agreement you may have executed with Licensor regarding
|
||||
such Contributions.
|
||||
|
||||
6. Trademarks.
|
||||
|
||||
This License does not grant permission to use the trade names, trademarks,
|
||||
service marks, or product names of the Licensor, except as required for
|
||||
reasonable and customary use in describing the origin of the Work and
|
||||
reproducing the content of the NOTICE file.
|
||||
|
||||
7. Disclaimer of Warranty.
|
||||
|
||||
Unless required by applicable law or agreed to in writing, Licensor provides the
|
||||
Work (and each Contributor provides its Contributions) on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied,
|
||||
including, without limitation, any warranties or conditions of TITLE,
|
||||
NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are
|
||||
solely responsible for determining the appropriateness of using or
|
||||
redistributing the Work and assume any risks associated with Your exercise of
|
||||
permissions under this License.
|
||||
|
||||
8. Limitation of Liability.
|
||||
|
||||
In no event and under no legal theory, whether in tort (including negligence),
|
||||
contract, or otherwise, unless required by applicable law (such as deliberate
|
||||
and grossly negligent acts) or agreed to in writing, shall any Contributor be
|
||||
liable to You for damages, including any direct, indirect, special, incidental,
|
||||
or consequential damages of any character arising as a result of this License or
|
||||
out of the use or inability to use the Work (including but not limited to
|
||||
damages for loss of goodwill, work stoppage, computer failure or malfunction, or
|
||||
any and all other commercial damages or losses), even if such Contributor has
|
||||
been advised of the possibility of such damages.
|
||||
|
||||
9. Accepting Warranty or Additional Liability.
|
||||
|
||||
While redistributing the Work or Derivative Works thereof, You may choose to
|
||||
offer, and charge a fee for, acceptance of support, warranty, indemnity, or
|
||||
other liability obligations and/or rights consistent with this License. However,
|
||||
in accepting such obligations, You may act only on Your own behalf and on Your
|
||||
sole responsibility, not on behalf of any other Contributor, and only if You
|
||||
agree to indemnify, defend, and hold each Contributor harmless for any liability
|
||||
incurred by, or claims asserted against, such Contributor by reason of your
|
||||
accepting any such warranty or additional liability.
|
||||
|
||||
END OF TERMS AND CONDITIONS
|
||||
|
||||
APPENDIX: How to apply the Apache License to your work
|
||||
|
||||
To apply the Apache License to your work, attach the following boilerplate
|
||||
notice, with the fields enclosed by brackets "[]" replaced with your own
|
||||
identifying information. (Don't include the brackets!) The text should be
|
||||
enclosed in the appropriate comment syntax for the file format. We also
|
||||
recommend that a file or class name and description of purpose be included on
|
||||
the same "printed page" as the copyright notice for easier identification within
|
||||
third-party archives.
|
||||
|
||||
Copyright 2014 Unknwon
|
||||
|
||||
Licensed under the Apache License, Version 2.0 (the "License");
|
||||
you may not use this file except in compliance with the License.
|
||||
You may obtain a copy of the License at
|
||||
|
||||
http://www.apache.org/licenses/LICENSE-2.0
|
||||
|
||||
Unless required by applicable law or agreed to in writing, software
|
||||
distributed under the License is distributed on an "AS IS" BASIS,
|
||||
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
||||
See the License for the specific language governing permissions and
|
||||
limitations under the License.
|
||||
|
||||
================================================================
|
||||
|
||||
gopkg.in/yaml.v2
|
||||
https://gopkg.in/yaml.v2
|
||||
----------------------------------------------------------------
|
||||
|
||||
@@ -1,4 +1,4 @@
|
||||
FROM golang:1.26.5-alpine AS build
|
||||
FROM golang:1.27.0-alpine AS build
|
||||
|
||||
ARG TARGETARCH
|
||||
|
||||
|
||||
@@ -4,7 +4,7 @@ LDFLAGS := $(shell go run buildscripts/gen-ldflags.go)
|
||||
|
||||
GOOS ?= $(shell go env GOOS)
|
||||
GOARCH ?= $(shell go env GOARCH)
|
||||
GOLANGCI_VERSION ?= v2.11.3
|
||||
GOLANGCI_VERSION ?= v2.13.1
|
||||
|
||||
VERSION ?= $(shell git describe --tags)
|
||||
REPO ?= docker.io/pgsty
|
||||
@@ -48,7 +48,7 @@ credits: ## regenerate CREDITS from the licenses of Go modules linked into the b
|
||||
|
||||
check-gen: ## check for updated autogenerated files
|
||||
@go generate ./... >/dev/null
|
||||
@go mod tidy -compat=1.26
|
||||
@go mod tidy -compat=1.27
|
||||
@env bash $(PWD)/buildscripts/gen-credits.sh
|
||||
@changed=$$(git diff --name-only -- '*_gen.go' '*_gen_test.go' '*_msgp_test.go' '*_string.go' go.mod go.sum CREDITS); \
|
||||
if [ -n "$$changed" ]; then \
|
||||
|
||||
@@ -6,15 +6,17 @@
|
||||
|
||||
|
||||
<p align="center">
|
||||
<strong>S3-compatible object storage — a MinIO fork maintained by PIGSTY</strong>
|
||||
<strong>S3-compatible object storage — a MinIO fork maintained by PGSTY</strong>
|
||||
</p>
|
||||
|
||||
|
||||
<p align="center">
|
||||
<a href="https://silo.pgsty.com/">Website</a> ·
|
||||
<a href="https://silo.pgsty.com/docs/">Documentation</a> ·
|
||||
<a href="https://silo.pgsty.com/download/">Download</a> ·
|
||||
<a href="https://silo.pgsty.com/tags/silo/">Release Notes</a> ·
|
||||
<a href="https://silo.pgsty.com/compatibility/server/">Compatibility</a> ·
|
||||
<a href="https://silo.pgsty.com/about/manifesto/">Manifesto</a> ·
|
||||
<a href="SECURITY.md">Security</a> ·
|
||||
<a href="README_ZH.md">中文</a>
|
||||
</p>
|
||||
@@ -28,239 +30,132 @@
|
||||
</p>
|
||||
|
||||
> [!IMPORTANT]
|
||||
> Silo is an independent, community-maintained fork of the open-source MinIO server, published by [Pigsty](https://pigsty.io) from [`pgsty/silo`](https://github.com/pgsty/silo). It is not affiliated with, endorsed by, or sponsored by MinIO, Inc. “MinIO” is used only to identify the upstream project and compatibility lineage.
|
||||
> **PGSTY Silo** (hereinafter “Silo”) is an independent, community-maintained fork of the open-source MinIO server, published by [Pigsty](https://pigsty.io) from [`pgsty/silo`](https://github.com/pgsty/silo). It is not affiliated with, endorsed by, or sponsored by MinIO, Inc. “MinIO” is used only to identify the upstream project and compatibility lineage.
|
||||
|
||||
> [!NOTE]
|
||||
> This repository was renamed from `pgsty/minio` to `pgsty/silo`, and its default branch from `master` to `main`, on 2026-08-06. If you need the artifacts maintained under the original MinIO identity, they are on the archived [`minio`](https://github.com/pgsty/silo/tree/minio) branch and in the releases up to [`RELEASE.2026-08-04T00-00-00Z`](https://github.com/pgsty/silo/releases/tag/RELEASE.2026-08-04T00-00-00Z); those assets and the `docker.io/pgsty/minio` image stay published and unmodified. The rename changed product and artifact names only — `MINIO_*` variables, `minio_*` metrics, `x-minio-*` headers, `/minio/*` routes, and the on-disk format are unchanged.
|
||||
> Renamed from `pgsty/minio` to `pgsty/silo`, default branch `master` → `main`, on 2026-08-06. Artifacts under the original MinIO identity stay published on the archived [`minio`](https://github.com/pgsty/silo/tree/minio) branch and in releases up to [`RELEASE.2026-08-04T00-00-00Z`](https://github.com/pgsty/silo/releases/tag/RELEASE.2026-08-04T00-00-00Z).
|
||||
|
||||
## Overview
|
||||
|
||||
Silo maintains one downstream release line derived from the open-source MinIO server. It provides maintained builds and release artifacts for existing MinIO-compatible deployments after upstream community distribution ended. Pigsty uses Silo for object storage, including as an optional PostgreSQL backup repository.
|
||||
PGSTY SILO keeps one maintained release line of the open-source MinIO server alive after upstream ended community distribution: builds, packages, multi-arch images, security fixes, and the full web console. Pigsty runs it in production as its PostgreSQL backup repository.
|
||||
|
||||
The fork follows one rule: **the product and its delivery surfaces are renamed; the protocol and your data are not.** The `silo` executable, packages, service, and container image carry the new name, while the S3 API, `MINIO_*` variables, `minio_*` metrics, `x-minio-*` headers, reserved routes, and the on-disk format stay unchanged. The differences are recorded in the [compatibility notes](https://silo.pgsty.com/compatibility/server/).
|
||||
It follows one rule — **the product and its delivery surfaces are renamed; the protocol and your data are not.** Everything else lives on [silo.pgsty.com](https://silo.pgsty.com/).
|
||||
|
||||
The official project portal is [silo.pgsty.com](https://silo.pgsty.com/). It brings documentation, downloads, release and security notes, and project background together.
|
||||
**Related:** [`pgsty/mc`](https://github.com/pgsty/mc) client (shipped as `mcli`) · [`pgsty/silo-console`](https://github.com/pgsty/silo-console) · [`pgsty/silo-pkg`](https://github.com/pgsty/silo-pkg) · [`pgsty/pigsty`](https://github.com/pgsty/pigsty)
|
||||
|
||||
## Find the Right Resource
|
||||
|
||||
| Looking for | Canonical location |
|
||||
| :-- | :-- |
|
||||
| Project overview and navigation | [Silo Website](https://silo.pgsty.com/) |
|
||||
| Installation methods and downloads | [Download & Install](https://silo.pgsty.com/download/) |
|
||||
| Operations, administration, development, and reference | [Documentation](https://silo.pgsty.com/docs/) |
|
||||
| Release notes for this server | [Silo release notes](https://silo.pgsty.com/tags/silo/) |
|
||||
| Differences from upstream MinIO | [Silo vs. MinIO compatibility notes](https://silo.pgsty.com/compatibility/server/) |
|
||||
| Project news and security advisories | [Blog](https://silo.pgsty.com/blog/) · [release](https://silo.pgsty.com/blog/release/) and [security](https://silo.pgsty.com/blog/security/) notes |
|
||||
| Versioned binaries, checksums, and source archives | [GitHub Releases](https://github.com/pgsty/silo/releases) |
|
||||
| Bug reports and feature discussions | [GitHub Issues](https://github.com/pgsty/silo/issues) |
|
||||
| Vulnerability reporting | [`SECURITY.md`](SECURITY.md) and [`VULNERABILITY_REPORT.md`](VULNERABILITY_REPORT.md) |
|
||||
| License, attribution, and trademark information | [`LICENSE`](LICENSE) · [`NOTICE`](NOTICE) · [`CREDITS`](CREDITS) · portal [license](https://silo.pgsty.com/about/license/), [attribution](https://silo.pgsty.com/about/attribution/), and [trademark](https://silo.pgsty.com/about/trademark/) pages |
|
||||
|
||||
## Related Projects
|
||||
|
||||
| Repository | Description |
|
||||
| :-- | :-- |
|
||||
| [`pgsty/silo`](https://github.com/pgsty/silo) | This repository — the Silo object storage server, an S3-compatible MinIO fork |
|
||||
| [`pgsty/mc`](https://github.com/pgsty/mc) | The Silo command-line client, shipped as `mcli` with the `mc` command name |
|
||||
| [`pgsty/silo-console`](https://github.com/pgsty/silo-console) | Admin web console, embedded in the server build |
|
||||
| [`pgsty/silo-pkg`](https://github.com/pgsty/silo-pkg) | Shared Go packages maintained for the Silo forks |
|
||||
| [`pgsty/pigsty`](https://github.com/pgsty/pigsty) | Pigsty — the PostgreSQL distribution that ships Silo as its object storage |
|
||||
|
||||
## Maintenance Policy
|
||||
|
||||
The active release line covers:
|
||||
|
||||
- build and dependency maintenance;
|
||||
- applicable security fixes and advisories;
|
||||
- focused fixes for reproducible defects;
|
||||
- versioned binaries, packages, checksums, and multi-architecture images;
|
||||
- the web console, client, documentation, and Pigsty integration.
|
||||
|
||||
Changes are kept narrow and tested where practical. Maintenance is best effort; no response, remediation, or release schedule is guaranteed.
|
||||
|
||||
### Out of scope
|
||||
|
||||
- a separate product roadmap, new storage engine, or speculative S3 features;
|
||||
- broad rewrites or changes that materially expand the downstream delta;
|
||||
- historical releases or multiple support branches;
|
||||
- commercial support, SLAs, 24×7 coverage, or SUBNET access;
|
||||
- deployment design, access control, monitoring, backup, or recovery.
|
||||
|
||||
## Governance
|
||||
|
||||
The server, client, console, and shared packages are maintained under one release process: DCO-signed commits, reviewed pull requests, and versioned `RELEASE.YYYY-MM-DDTHH-MM-SSZ` tags whose artifacts ship with checksums, SPDX SBOMs, Sigstore-signed manifests, and GitHub build attestations. Each release is announced with a [release note](https://silo.pgsty.com/tags/silo/) on the portal; security handling follows [`SECURITY.md`](SECURITY.md) and the [advisory log](docs/security/advisories.md). Upstream copyright, license, and third-party notices are preserved in [`LICENSE`](LICENSE), [`NOTICE`](NOTICE), and [`CREDITS`](CREDITS).
|
||||
|
||||
## Compatibility
|
||||
|
||||
Silo aims to preserve:
|
||||
|
||||
- the `github.com/minio/minio` module path and `github.com/minio/*` import paths;
|
||||
- MinIO-compatible S3 APIs, wire behavior, `MINIO_*` environment variables, metrics, protocol headers, reserved routes, and storage metadata;
|
||||
- `RELEASE.YYYY-MM-DDTHH-MM-SSZ` tags and legacy `minio …` container argv translation.
|
||||
|
||||
Silo-owned delivery surfaces use the `silo` executable, package, service, Helm chart, and `pgsty/silo` container image. Native artifacts intentionally do not install a `minio` binary alias.
|
||||
|
||||
Compatibility is the default constraint. Silo preserves existing wire, client, configuration, and operational behavior whenever doing so remains safe. Compatibility is broken only when necessary to close a major security issue, and the release notes must identify the affected behavior and migration path. Treat each release as a downstream upgrade: pin versions, review the [release notes](https://silo.pgsty.com/tags/silo/), [compatibility notes](https://silo.pgsty.com/compatibility/server/), and [security advisories](docs/security/advisories.md), keep a rollback path, and test before production use.
|
||||
|
||||
## Downloads and Release Artifacts
|
||||
|
||||
Use [Download & Install](https://silo.pgsty.com/download/) to choose an installation method. GitHub Releases remains the source for versioned server binaries, checksums, and source archives.
|
||||
|
||||
| Artifact | Location |
|
||||
| :-- | :-- |
|
||||
| Source | [`github.com/pgsty/silo`](https://github.com/pgsty/silo) |
|
||||
| Container image | [`pgsty/silo`](https://hub.docker.com/r/pgsty/silo), multi-arch for `linux/amd64` and `linux/arm64` |
|
||||
| Server binaries and checksums | [GitHub Releases](https://github.com/pgsty/silo/releases) for Linux, macOS, and Windows on `amd64` and `arm64` |
|
||||
| Linux packages | RPM, DEB, and APK artifacts, also distributed through the [Pigsty repository](https://pigsty.io/docs/repo/) |
|
||||
| Client | [`pgsty/mc`](https://github.com/pgsty/mc), bundled in the container as `mcli` with an `mc` compatibility alias |
|
||||
| Console | [`pgsty/silo-console`](https://github.com/pgsty/silo-console), embedded through the compatibility import path `github.com/minio/console` |
|
||||
| Shared library | [`pgsty/silo-pkg`](https://github.com/pgsty/silo-pkg) v3.11.0, consumed through a `replace` directive while preserving the `github.com/minio/pkg/v3` import path |
|
||||
|
||||
Each new release publishes per-archive and per-package SPDX JSON SBOMs. The archive and package checksum manifests have detached keyless Sigstore bundles, while GitHub artifact attestations record signed provenance for every downloadable artifact and the multi-architecture container image.
|
||||
|
||||
After downloading an archive and its release files, verify integrity, the
|
||||
published SBOM, the signed manifest, and build provenance independently:
|
||||
|
||||
```bash
|
||||
# Integrity: choose the line for the artifact you downloaded.
|
||||
grep -F ' silo_<version>_linux_amd64.tar.gz' \
|
||||
silo_<version>_checksums.txt | sha256sum --check
|
||||
|
||||
# The archive SBOM is a separate checksummed release artifact.
|
||||
grep -F ' silo_<version>_linux_amd64.tar.gz.sbom.json' \
|
||||
silo_<version>_checksums.txt | sha256sum --check
|
||||
|
||||
# Signature over the archive/SBOM checksum manifest.
|
||||
cosign verify-blob \
|
||||
--bundle silo_<version>_checksums.txt.sigstore.json \
|
||||
--certificate-identity-regexp \
|
||||
'^https://github.com/pgsty/(minio|silo)/\.github/workflows/release\.yml@refs/(tags/RELEASE\..+|heads/(master|main))$' \
|
||||
--certificate-oidc-issuer https://token.actions.githubusercontent.com \
|
||||
silo_<version>_checksums.txt
|
||||
|
||||
# Signed build provenance (online verification against this repository).
|
||||
gh attestation verify silo_<version>_linux_amd64.tar.gz \
|
||||
--repo pgsty/silo
|
||||
```
|
||||
|
||||
For packages, use `silo_<version>_packages_checksums.txt` and its adjacent
|
||||
Sigstore bundle with the same identity and issuer constraints. Inspect the
|
||||
verified SPDX JSON SBOM with your preferred SPDX tooling. Verify the
|
||||
multi-architecture container provenance by digest:
|
||||
|
||||
```bash
|
||||
gh attestation verify \
|
||||
oci://index.docker.io/pgsty/silo@sha256:<manifest-digest> \
|
||||
--repo pgsty/silo
|
||||
```
|
||||
|
||||
The platform SBOM attestations are attached to the `amd64` and `arm64` image
|
||||
digests rather than the multi-architecture manifest. Verify each one explicitly:
|
||||
|
||||
```bash
|
||||
gh attestation verify \
|
||||
oci://index.docker.io/pgsty/silo@sha256:<platform-digest> \
|
||||
--repo pgsty/silo \
|
||||
--predicate-type https://spdx.dev/Document/v2.3
|
||||
```
|
||||
|
||||
Verification by digest avoids trusting a mutable image tag.
|
||||
|
||||
### Native package migration
|
||||
|
||||
The `silo` RPM, DEB, and APK do not declare `Provides`, `Obsoletes`,
|
||||
`Replaces`, or package-level `Conflicts` against `minio`. They can therefore be
|
||||
installed beside an existing MinIO package without silently replacing it. The
|
||||
two systemd units conflict at runtime, so switch them explicitly rather than
|
||||
starting both.
|
||||
|
||||
Before switching, record the old unit's enabled/active state and `User`/`Group`,
|
||||
and back up `/etc/default/minio`. Silo reads that legacy defaults file first and
|
||||
then `/etc/default/silo`; administrator-set values in the latter take
|
||||
precedence. If the existing data must continue to run under its original
|
||||
UID/GID, create `/etc/systemd/system/silo.service.d/10-legacy-user.conf`:
|
||||
|
||||
```ini
|
||||
[Service]
|
||||
User=<legacy-user>
|
||||
Group=<legacy-group>
|
||||
```
|
||||
|
||||
Run `systemctl daemon-reload`, then disable and stop `minio.service` before
|
||||
enabling and starting `silo.service`. Verify health, S3, Admin API, metrics, and
|
||||
logs before masking or uninstalling the old service. Do not recursively change
|
||||
data ownership as part of the package migration; keep the old package and unit
|
||||
available during the rollback window.
|
||||
<p align="center">
|
||||
<img src="https://silo.pgsty.com/images/silo-console/console-metrics-simple.webp" alt="Silo Console">
|
||||
</p>
|
||||
|
||||
## Quick Start
|
||||
|
||||
For local evaluation:
|
||||
|
||||
```bash
|
||||
mkdir -p data
|
||||
|
||||
export MINIO_ROOT_USER=minioadmin
|
||||
export MINIO_ROOT_PASSWORD=change-me-long-password
|
||||
|
||||
docker run -d --name silo \
|
||||
-p 9000:9000 \
|
||||
-p 9001:9001 \
|
||||
-e MINIO_ROOT_USER \
|
||||
-e MINIO_ROOT_PASSWORD \
|
||||
docker run -d --name silo -p 9000:9000 -p 9001:9001 \
|
||||
-e MINIO_ROOT_USER=minioadmin \
|
||||
-e MINIO_ROOT_PASSWORD=change-me-long-password \
|
||||
-v "$PWD/data:/data" \
|
||||
docker.io/pgsty/silo:latest server /data --console-address ":9001"
|
||||
```
|
||||
|
||||
Open the console at <http://localhost:9001>; the S3 API listens on <http://localhost:9000>.
|
||||
<p align="center">
|
||||
<img src="https://silo.pgsty.com/images/silo-console/console-login.webp" alt="Silo Console">
|
||||
</p>
|
||||
|
||||
The image includes the compatible client as `mcli`:
|
||||
Console on <http://localhost:9001>, S3 API on <http://localhost:9000>. The image bundles the client as `mcli`:
|
||||
|
||||
```bash
|
||||
docker exec silo mcli alias set local http://127.0.0.1:9000 \
|
||||
"$MINIO_ROOT_USER" "$MINIO_ROOT_PASSWORD"
|
||||
docker exec silo mcli mb local/demo
|
||||
docker exec silo mcli ls local
|
||||
docker exec silo mcli alias set local http://127.0.0.1:9000 minioadmin change-me-long-password
|
||||
docker exec silo mcli mb local/demo && docker exec silo mcli ls local
|
||||
```
|
||||
|
||||
> [!WARNING]
|
||||
> For production, pin a release, use unique credentials and TLS, monitor the service, keep independent backups, and test recovery.
|
||||
> For production, pin a release, use unique credentials and TLS, monitor the service, keep independent backups, and test recovery. Start from the [documentation](https://silo.pgsty.com/docs/).
|
||||
|
||||
Build the server from source:
|
||||
## Install
|
||||
|
||||
```bash
|
||||
go build -o silo .
|
||||
./silo --version
|
||||
```
|
||||
| Method | Where |
|
||||
| :-- | :-- |
|
||||
| Container | [`pgsty/silo`](https://hub.docker.com/r/pgsty/silo), multi-arch for `linux/amd64` and `linux/arm64` |
|
||||
| Binaries | [GitHub Releases](https://github.com/pgsty/silo/releases) — Linux, macOS, Windows on `amd64` and `arm64` |
|
||||
| Packages | RPM, DEB, and APK, also via the [Pigsty repository](https://pigsty.io/docs/repo/) |
|
||||
| Kubernetes | Helm chart, see [Download & Install](https://silo.pgsty.com/download/) |
|
||||
| Source | `go build -o silo . && ./silo --version` |
|
||||
|
||||
For other installation paths—including native packages, binaries, Podman, Kubernetes, source, and Pigsty Ansible—use [Download & Install](https://silo.pgsty.com/download/). For production deployment and administration, start with the [Silo documentation](https://silo.pgsty.com/docs/). Pigsty users can also use the [Pigsty MinIO module](https://pigsty.io/docs/minio/).
|
||||
Every release ships checksums, SPDX SBOMs, Sigstore-signed manifests, and GitHub build attestations. Installation methods and verification commands are documented at [Download & Install](https://silo.pgsty.com/download/); migrating from upstream MinIO — taking over an existing `minio.service` and its `/etc/default/minio`, and keeping data ownership stable with a `/etc/systemd/system/silo.service.d/10-legacy-user.conf` drop-in — is covered by the [migration guide](https://silo.pgsty.com/compatibility/migration/) and the [binary & service notes](https://silo.pgsty.com/compatibility/binary/).
|
||||
|
||||
## Security
|
||||
## Compatibility
|
||||
|
||||
Security fixes target the active development branch and are recorded in the [advisory log](docs/security/advisories.md) and the portal's [security notes](https://silo.pgsty.com/blog/security/). Report vulnerabilities privately as described in [`SECURITY.md`](SECURITY.md) and [`VULNERABILITY_REPORT.md`](VULNERABILITY_REPORT.md). Report issues that also affect upstream MinIO there as well.
|
||||
The S3 API, `MINIO_*` variables, `minio_*` metrics, `x-minio-*` headers, `/minio/*` routes, the `github.com/minio/*` import paths, and the on-disk format (including `.minio.sys`) are preserved and held in place by a CI compatibility check. Only Silo-owned delivery surfaces change: the `silo` executable, package, service, Helm chart, and container image — no `minio` binary alias is installed.
|
||||
|
||||
## Contributing
|
||||
Every divergence from upstream is listed in the code-verified [compatibility audit](https://silo.pgsty.com/compatibility/server/). Treat each release as a downstream upgrade: pin versions, read the [release notes](https://silo.pgsty.com/tags/silo/), and keep a rollback path.
|
||||
|
||||
Useful contributions include security and dependency updates, reproducible bug fixes, tests, release automation, packaging, and documentation.
|
||||
## Security & Contributing
|
||||
|
||||
Issues and pull requests should include the affected version, reproduction steps, impact, expected behavior, tests, and compatibility notes. Discuss large changes in an issue first.
|
||||
Report vulnerabilities privately as described in [`SECURITY.md`](SECURITY.md); every fix ships with a public [advisory](https://silo.pgsty.com/blog/security/). Contributions are accepted inbound=outbound under AGPL-3.0-or-later with no CLA — only DCO sign-off (`git commit -s`) is required; see [`CONTRIBUTING.md`](CONTRIBUTING.md).
|
||||
|
||||
There is no CLA: contributions are accepted inbound=outbound under the project license (AGPL-3.0-or-later) and contributors keep their copyright. Every commit must be signed off (`git commit -s`) per the [Developer Certificate of Origin](https://developercertificate.org/); see [`CONTRIBUTING.md`](CONTRIBUTING.md).
|
||||
## Contributors
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center" width="150">
|
||||
<a href="https://github.com/ZouhairCharef"><img src="https://github.com/ZouhairCharef.png?size=100" width="72" alt="ZouhairCharef"><br><sub><b>@ZouhairCharef</b></sub></a><br><sub>CVE-2026-34986</sub>
|
||||
</td>
|
||||
<td align="center" width="150">
|
||||
<a href="https://github.com/mfredenhagen"><img src="https://github.com/mfredenhagen.png?size=100" width="72" alt="mfredenhagen"><br><sub><b>@mfredenhagen</b></sub></a><br><sub>CVE-2026-39883</sub>
|
||||
</td>
|
||||
<td align="center" width="150">
|
||||
<a href="https://github.com/pinginfo"><img src="https://github.com/pinginfo.png?size=100" width="72" alt="pinginfo"><br><sub><b>@pinginfo</b></sub></a><br><sub>Notification streaming</sub>
|
||||
</td>
|
||||
<td align="center" width="150">
|
||||
<a href="https://github.com/waterkip"><img src="https://github.com/waterkip.png?size=100" width="72" alt="waterkip"><br><sub><b>@waterkip</b></sub></a><br><sub>Documentation links</sub>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<p>
|
||||
<a href="https://github.com/magicxor"><img src="https://github.com/magicxor.png?size=64" width="44" alt="magicxor" title="@magicxor"></a>
|
||||
<a href="https://github.com/ycjlin"><img src="https://github.com/ycjlin.png?size=64" width="44" alt="ycjlin" title="@ycjlin"></a>
|
||||
<a href="https://github.com/davinkevin"><img src="https://github.com/davinkevin.png?size=64" width="44" alt="davinkevin" title="@davinkevin"></a>
|
||||
<a href="https://github.com/lem21h"><img src="https://github.com/lem21h.png?size=64" width="44" alt="lem21h" title="@lem21h"></a>
|
||||
<a href="https://github.com/sulin37392"><img src="https://github.com/sulin37392.png?size=64" width="44" alt="sulin37392" title="@sulin37392"></a>
|
||||
<a href="https://github.com/mosesdd"><img src="https://github.com/mosesdd.png?size=64" width="44" alt="mosesdd" title="@mosesdd"></a>
|
||||
<a href="https://github.com/Xavier-777"><img src="https://github.com/Xavier-777.png?size=64" width="44" alt="Xavier-777" title="@Xavier-777"></a>
|
||||
<a href="https://github.com/jiadzh"><img src="https://github.com/jiadzh.png?size=64" width="44" alt="jiadzh" title="@jiadzh"></a>
|
||||
<a href="https://github.com/TLINDEN"><img src="https://github.com/TLINDEN.png?size=64" width="44" alt="TLINDEN" title="@TLINDEN"></a>
|
||||
<a href="https://github.com/AntonOfTheWoods"><img src="https://github.com/AntonOfTheWoods.png?size=64" width="44" alt="AntonOfTheWoods" title="@AntonOfTheWoods"></a>
|
||||
<a href="https://github.com/zylpsrs"><img src="https://github.com/zylpsrs.png?size=64" width="44" alt="zylpsrs" title="@zylpsrs"></a>
|
||||
<a href="https://github.com/nsanitate"><img src="https://github.com/nsanitate.png?size=64" width="44" alt="nsanitate" title="@nsanitate"></a>
|
||||
<a href="https://github.com/makinikm"><img src="https://github.com/makinikm.png?size=64" width="44" alt="makinikm" title="@makinikm"></a>
|
||||
<a href="https://github.com/spaceg00se-r"><img src="https://github.com/spaceg00se-r.png?size=64" width="44" alt="spaceg00se-r" title="@spaceg00se-r"></a>
|
||||
<a href="https://github.com/heroes1412"><img src="https://github.com/heroes1412.png?size=64" width="44" alt="heroes1412" title="@heroes1412"></a>
|
||||
<a href="https://github.com/vampywiz17"><img src="https://github.com/vampywiz17.png?size=64" width="44" alt="vampywiz17" title="@vampywiz17"></a>
|
||||
<a href="https://github.com/chalukyaj"><img src="https://github.com/chalukyaj.png?size=64" width="44" alt="chalukyaj" title="@chalukyaj"></a>
|
||||
<a href="https://github.com/cbornet"><img src="https://github.com/cbornet.png?size=64" width="44" alt="cbornet" title="@cbornet"></a>
|
||||
<a href="https://github.com/jvasile"><img src="https://github.com/jvasile.png?size=64" width="44" alt="jvasile" title="@jvasile"></a>
|
||||
<a href="https://github.com/Kesavaambati"><img src="https://github.com/Kesavaambati.png?size=64" width="44" alt="Kesavaambati" title="@Kesavaambati"></a>
|
||||
<a href="https://github.com/redfoxfox"><img src="https://github.com/redfoxfox.png?size=64" width="44" alt="redfoxfox" title="@redfoxfox"></a>
|
||||
<a href="https://github.com/kuldeep-link11"><img src="https://github.com/kuldeep-link11.png?size=64" width="44" alt="kuldeep-link11" title="@kuldeep-link11"></a>
|
||||
<a href="https://github.com/meesudzu"><img src="https://github.com/meesudzu.png?size=64" width="44" alt="meesudzu" title="@meesudzu"></a>
|
||||
<a href="https://github.com/pmezhuev"><img src="https://github.com/pmezhuev.png?size=64" width="44" alt="pmezhuev" title="@pmezhuev"></a>
|
||||
<a href="https://github.com/kh0mka"><img src="https://github.com/kh0mka.png?size=64" width="44" alt="kh0mka" title="@kh0mka"></a>
|
||||
</p>
|
||||
|
||||
GitHub does not generate a contributor graph for forks, so [`CONTRIBUTORS.md`](CONTRIBUTORS.md) — not the Insights page — is this project's attribution record. It names everyone alongside the change or report they contributed.
|
||||
|
||||
## Background
|
||||
|
||||
This project was created in response to changes in the upstream community distribution and maintenance model. The maintainer’s analysis, alternatives considered, and early maintenance record are documented below:
|
||||
Upstream wound down its community edition: the web console was cut back to a stub, prebuilt community binaries stopped, and the community repository was archived. Silo exists to keep those deployments running. The fork is a means, not an identity — if upstream restores its community edition, we will narrow our scope and offer the fixes back.
|
||||
|
||||
| Essay | Subject |
|
||||
| :-- | :-- |
|
||||
| [MinIO Is Dead](https://silo.pgsty.com/blog/post/minio-is-dead/) | Changes to the upstream project and distribution model |
|
||||
| [MinIO Is Dead, Who Takes Over?](https://silo.pgsty.com/blog/post/minio-alternative/) | Alternatives considered |
|
||||
| [MinIO Is Dead, Long Live MinIO](https://silo.pgsty.com/blog/post/minio-resurrect/) | Establishing the fork and its release pipeline |
|
||||
| [Two months into maintaining a MinIO fork](https://silo.pgsty.com/blog/post/minio-promise-kept/) | Initial security and maintenance work |
|
||||
The [**Manifesto**](https://silo.pgsty.com/about/manifesto/) is the project's public commitment in eleven articles, under one discipline: every article is either something already done with public evidence, or something explicitly refused. In short:
|
||||
|
||||
## License and Trademark
|
||||
- **Compatibility contract** — the protocol and your data do not change, and every release documents its tested rollback target and path.
|
||||
- **The license cannot change** — AGPLv3, no CLA, no copyright aggregation; nobody here, ourselves included, holds enough copyright to relicense on everyone else's behalf.
|
||||
- **The never list**, append-only — no paywalling existing features, no registration wall on downloads, no telemetry (upstream's phone-home paths are removed outright), no CLA, no license change, no trademark enforcement against normal use.
|
||||
- **Security and release discipline** — a public advisory for every fix, and a release every one to two months, at most a quarter apart. Judge both against the public record.
|
||||
|
||||
The server source is distributed under the [GNU Affero General Public License v3.0 or later](LICENSE). This fork derives from [`minio/minio`](https://github.com/minio/minio): [`NOTICE`](NOTICE) retains the upstream product notice, [`CREDITS`](CREDITS) records licenses and notices for included third-party components, and the Git history records downstream modifications.
|
||||
Essays: [MinIO Is Dead](https://silo.pgsty.com/blog/post/minio-is-dead/) · [Who Takes Over?](https://silo.pgsty.com/blog/post/minio-alternative/) · [Long Live MinIO](https://silo.pgsty.com/blog/post/minio-resurrect/) · [Promise Kept](https://silo.pgsty.com/blog/post/minio-promise-kept/)
|
||||
|
||||
MinIO is a trademark of MinIO, Inc. The name is used here only to identify the upstream project and compatibility lineage. Pigsty, Silo, and `pgsty/silo` are independent community efforts and are not affiliated with, endorsed by, or sponsored by MinIO, Inc.
|
||||
## License & Trademark
|
||||
|
||||
The portal separately publishes the project [license summary](https://silo.pgsty.com/about/license/), [documentation attribution](https://silo.pgsty.com/about/attribution/), and [trademark notice](https://silo.pgsty.com/about/trademark/).
|
||||
Silo is [AGPL-3.0-or-later](LICENSE), derived from [`minio/minio`](https://github.com/minio/minio) with upstream copyright and third-party notices preserved in [`NOTICE`](NOTICE) and [`CREDITS`](CREDITS). MinIO is a trademark of MinIO, Inc.; the name is used here only to identify the upstream project and compatibility lineage.
|
||||
|
||||
Details: [license](https://silo.pgsty.com/about/license/) · [attribution](https://silo.pgsty.com/about/attribution/) · [trademark](https://silo.pgsty.com/about/trademark/)
|
||||
|
||||
+95
-195
@@ -1,20 +1,22 @@
|
||||
<h1 align="center">
|
||||
<a href="https://silo.pgsty.com/zh/">
|
||||
<img src=".github/silo-logo.svg" alt="Silo" width="112"><br>
|
||||
<img src=".github/silo-logo.svg" alt="Silo" width="160">
|
||||
</a>
|
||||
</h1>
|
||||
|
||||
|
||||
<p align="center">
|
||||
<strong>S3 兼容对象存储 —— 由 PIGSTY 维护的 MinIO 社区分支</strong>
|
||||
<strong>S3 兼容对象存储 —— 由 PGSTY 维护的 MinIO 社区分支</strong>
|
||||
</p>
|
||||
|
||||
|
||||
<p align="center">
|
||||
<a href="https://silo.pgsty.com/zh/">官网</a> ·
|
||||
<a href="https://silo.pgsty.com/zh/docs/">文档</a> ·
|
||||
<a href="https://silo.pgsty.com/zh/download/">下载</a> ·
|
||||
<a href="https://silo.pgsty.com/zh/tags/silo/">版本说明</a> ·
|
||||
<a href="https://silo.pgsty.com/zh/compatibility/server/">兼容性</a> ·
|
||||
<a href="https://silo.pgsty.com/zh/about/manifesto/">宣言</a> ·
|
||||
<a href="SECURITY.md">安全策略</a> ·
|
||||
<a href="README.md">English</a>
|
||||
</p>
|
||||
@@ -28,234 +30,132 @@
|
||||
</p>
|
||||
|
||||
> [!IMPORTANT]
|
||||
> Silo 是由 [Pigsty](https://pigsty.cc) 独立维护、从 [`pgsty/silo`](https://github.com/pgsty/silo) 发布的开源 MinIO 社区分支。本项目与 MinIO, Inc. 不存在隶属、背书或赞助关系;文中使用 “MinIO” 仅用于说明上游项目及兼容谱系。
|
||||
> **PGSTY Silo**(以下简称 Silo)是由 [Pigsty](https://pigsty.cc) 独立维护、从 [`pgsty/silo`](https://github.com/pgsty/silo) 发布的开源 MinIO 社区分支。本项目与 MinIO, Inc. 不存在隶属、背书或赞助关系;文中使用 “MinIO” 仅用于说明上游项目及兼容谱系。
|
||||
|
||||
> [!NOTE]
|
||||
> 2026-08-06,本仓库由 `pgsty/minio` 更名为 `pgsty/silo`,默认分支由 `master` 更名为 `main`。如果你需要以原本 MinIO 形态维持的归档构件,它们位于归档的 [`minio`](https://github.com/pgsty/silo/tree/minio) 分支,以及截止到 [`RELEASE.2026-08-04T00-00-00Z`](https://github.com/pgsty/silo/releases/tag/RELEASE.2026-08-04T00-00-00Z) 的历次发布中;这些资产与 `docker.io/pgsty/minio` 镜像保持已发布状态且不做改动。本次更名只改变产品与交付物名称 —— `MINIO_*` 变量、`minio_*` 指标、`x-minio-*` 头、`/minio/*` 路由与磁盘格式均保持不变。
|
||||
> 2026-08-06,本仓库由 `pgsty/minio` 更名为 `pgsty/silo`,默认分支由 `master` 更名为 `main`。以原 MinIO 形态维持的归档构件仍位于归档的 [`minio`](https://github.com/pgsty/silo/tree/minio) 分支,以及截止 [`RELEASE.2026-08-04T00-00-00Z`](https://github.com/pgsty/silo/releases/tag/RELEASE.2026-08-04T00-00-00Z) 的历次发布中。
|
||||
|
||||
## 概述
|
||||
|
||||
Silo 维护一条源自开源 MinIO 服务端的下游版本线,为上游停止社区发行后仍在运行 MinIO 兼容部署的用户提供持续构建与发行产物。Pigsty 使用 Silo 提供对象存储,包括作为可选的 PostgreSQL 备份仓库。
|
||||
上游停止社区发行后,Silo 为开源 MinIO 服务端维护一条持续可用的版本线:构建、软件包、多架构镜像、安全修复与完整 Web 控制台。Pigsty 在生产环境中用它承载 PostgreSQL 备份存储。
|
||||
|
||||
本分支遵循一条原则:**改名的是产品与交付物,不是协议与你的数据。** `silo` 可执行文件、软件包、服务与容器镜像使用新名称,而 S3 API、`MINIO_*` 变量、`minio_*` 指标、`x-minio-*` 头、保留路由与磁盘格式保持不变。具体差异记录在[兼容性说明](https://silo.pgsty.com/zh/compatibility/server/)中。
|
||||
它只遵循一条原则:**改名的是产品与交付物,不是协议与你的数据。** 其余内容都在 [silo.pgsty.com](https://silo.pgsty.com/zh/)。
|
||||
|
||||
项目统一门户为 [silo.pgsty.com](https://silo.pgsty.com/zh/),集中提供文档、下载安装、版本与安全动态及项目背景。
|
||||
**相关项目:**[`pgsty/mc`](https://github.com/pgsty/mc) 客户端(以 `mcli` 发行) · [`pgsty/silo-console`](https://github.com/pgsty/silo-console) · [`pgsty/silo-pkg`](https://github.com/pgsty/silo-pkg) · [`pgsty/pigsty`](https://github.com/pgsty/pigsty)
|
||||
|
||||
## 按需求选择入口
|
||||
<p align="center">
|
||||
<img src="https://silo.pgsty.com/images/silo-console/console-metrics-simple.webp" alt="Silo 控制台">
|
||||
</p>
|
||||
|
||||
| 需求 | 权威入口 |
|
||||
| :-- | :-- |
|
||||
| 项目概览与全站导航 | [Silo 官网](https://silo.pgsty.com/zh/) |
|
||||
| 安装方式与软件下载 | [下载与安装](https://silo.pgsty.com/zh/download/) |
|
||||
| 运维、管理、开发与参考指南 | [文档](https://silo.pgsty.com/zh/docs/) |
|
||||
| 本服务端的版本说明 | [Silo 版本说明](https://silo.pgsty.com/zh/tags/silo/) |
|
||||
| 与上游 MinIO 的差异 | [Silo vs. MinIO 兼容性说明](https://silo.pgsty.com/zh/compatibility/server/) |
|
||||
| 项目动态与安全通告 | [博客](https://silo.pgsty.com/zh/blog/) · [版本发布](https://silo.pgsty.com/zh/blog/release/)与[安全通告](https://silo.pgsty.com/zh/blog/security/) |
|
||||
| 带版本的二进制、校验和与源码归档 | [GitHub Releases](https://github.com/pgsty/silo/releases) |
|
||||
| 缺陷报告与功能讨论 | [GitHub Issues](https://github.com/pgsty/silo/issues) |
|
||||
| 私密漏洞报告 | [`SECURITY.md`](SECURITY.md) 与 [`VULNERABILITY_REPORT.md`](VULNERABILITY_REPORT.md) |
|
||||
| 许可证、署名与商标信息 | [`LICENSE`](LICENSE) · [`NOTICE`](NOTICE) · [`CREDITS`](CREDITS) · 门户的[许可证](https://silo.pgsty.com/zh/about/license/)、[署名归属](https://silo.pgsty.com/zh/about/attribution/)与[商标政策](https://silo.pgsty.com/zh/about/trademark/)页面 |
|
||||
|
||||
## 相关项目
|
||||
|
||||
| 仓库 | 说明 |
|
||||
| :-- | :-- |
|
||||
| [`pgsty/silo`](https://github.com/pgsty/silo) | 本仓库 —— Silo 对象存储服务器,S3 兼容的 MinIO fork |
|
||||
| [`pgsty/mc`](https://github.com/pgsty/mc) | Silo 命令行客户端,以 `mcli` 发行、保留 `mc` 命令名 |
|
||||
| [`pgsty/silo-console`](https://github.com/pgsty/silo-console) | Web 管理控制台,内嵌于服务端构建 |
|
||||
| [`pgsty/silo-pkg`](https://github.com/pgsty/silo-pkg) | 为 Silo 系 fork 维护的共享 Go 包 |
|
||||
| [`pgsty/pigsty`](https://github.com/pgsty/pigsty) | Pigsty —— 内置 Silo 作为对象存储的 PostgreSQL 发行版 |
|
||||
|
||||
## 维护政策
|
||||
|
||||
活跃版本线的维护范围包括:
|
||||
|
||||
- 构建与依赖项维护;
|
||||
- 适用的安全修复与公告;
|
||||
- 针对可复现缺陷的范围明确的修复;
|
||||
- 带版本的二进制、软件包、校验和与多架构镜像;
|
||||
- Web Console、客户端、文档与 Pigsty 集成。
|
||||
|
||||
改动保持克制,并在可行时提供测试。所有维护均为尽力而为,不承诺固定的响应、修复或发布时间。
|
||||
|
||||
### 范围之外
|
||||
|
||||
- 独立产品路线图、新存储引擎或假设性的 S3 新特性;
|
||||
- 大规模重写或显著扩大下游差异的改动;
|
||||
- 历史版本或多条支持分支;
|
||||
- 商业支持、SLA、7×24 服务或 SUBNET 服务;
|
||||
- 部署设计、访问控制、监控、备份与恢复。
|
||||
|
||||
## 治理
|
||||
|
||||
服务端、客户端、控制台与共享包在同一套发布流程下共同维护:提交必须签署 DCO、Pull Request 经过评审、以 `RELEASE.YYYY-MM-DDTHH-MM-SSZ` 标签发布,产物附带校验和、SPDX SBOM、Sigstore 签名清单与 GitHub 构建证明。每个版本都会在门户发布[版本说明](https://silo.pgsty.com/zh/tags/silo/);安全问题按照 [`SECURITY.md`](SECURITY.md) 与仓库[安全公告](docs/security/advisories.md)处理。上游版权、许可证与第三方声明完整保留于 [`LICENSE`](LICENSE)、[`NOTICE`](NOTICE) 与 [`CREDITS`](CREDITS)。
|
||||
|
||||
## 兼容策略
|
||||
|
||||
Silo 尽量保留:
|
||||
|
||||
- `github.com/minio/minio` module path 与 `github.com/minio/*` 导入路径;
|
||||
- MinIO 兼容的 S3 API、线协议、`MINIO_*` 环境变量、指标、协议头、保留路由与存储元数据;
|
||||
- `RELEASE.YYYY-MM-DDTHH-MM-SSZ` 标签,以及容器入口对旧式 `minio …` 参数的转换。
|
||||
|
||||
Silo 自有交付面统一使用 `silo` 可执行文件、软件包、服务、Helm Chart 与 `pgsty/silo` 容器镜像;原生交付物不会安装 `minio` 二进制别名。
|
||||
|
||||
兼容性是默认约束。只要不会留下安全问题,Silo 就保留既有的协议、客户端、配置与运维行为;只有在修复重大安全问题确有必要时才会打破兼容,并在版本说明中明确受影响行为与迁移方式。每个版本仍应视为下游升级:锁定版本,阅读[版本说明](https://silo.pgsty.com/zh/tags/silo/)、[兼容性说明](https://silo.pgsty.com/zh/compatibility/server/)与[安全公告](docs/security/advisories.md),保留回滚路径,并在生产使用前完成测试。
|
||||
|
||||
## 下载与发行产物
|
||||
|
||||
请先在[下载与安装](https://silo.pgsty.com/zh/download/)页面选择合适的安装方式;GitHub Releases 仍是带版本服务端二进制、校验和与源码归档的获取位置。
|
||||
|
||||
| 产物 | 位置 |
|
||||
| :-- | :-- |
|
||||
| 源码 | [`github.com/pgsty/silo`](https://github.com/pgsty/silo) |
|
||||
| 容器镜像 | [`pgsty/silo`](https://hub.docker.com/r/pgsty/silo),支持 `linux/amd64` 与 `linux/arm64` 多架构清单 |
|
||||
| 服务端二进制与校验和 | [GitHub Releases](https://github.com/pgsty/silo/releases),覆盖 Linux、macOS、Windows 的 `amd64` 与 `arm64` |
|
||||
| Linux 软件包 | RPM、DEB、APK,并通过 [Pigsty 软件仓库](https://pigsty.cc/docs/repo/) 分发 |
|
||||
| 客户端 | [`pgsty/mc`](https://github.com/pgsty/mc),容器内以 `mcli` 提供,并保留 `mc` 兼容别名 |
|
||||
| 管理控制台 | [`pgsty/silo-console`](https://github.com/pgsty/silo-console),通过兼容导入路径 `github.com/minio/console` 嵌入服务端构建 |
|
||||
| 共享库 | [`pgsty/silo-pkg`](https://github.com/pgsty/silo-pkg) v3.11.0,通过 `replace` 指令使用,同时保留 `github.com/minio/pkg/v3` 导入路径 |
|
||||
|
||||
每个新版本都会为各平台归档和软件包发布 SPDX JSON SBOM。归档与软件包的校验和清单分别带有无长期密钥的 Sigstore 签名包;GitHub 制品证明则为全部可下载产物及多架构容器镜像记录已签名的构建来源。
|
||||
|
||||
下载归档及配套文件后,请分别验证完整性、已发布 SBOM、签名清单与构建来源:
|
||||
## 快速上手
|
||||
|
||||
```bash
|
||||
# 完整性:选择与你下载产物相符的一行。
|
||||
grep -F ' silo_<version>_linux_amd64.tar.gz' \
|
||||
silo_<version>_checksums.txt | sha256sum --check
|
||||
|
||||
# 归档 SBOM 是另一个独立校验的 Release 产物。
|
||||
grep -F ' silo_<version>_linux_amd64.tar.gz.sbom.json' \
|
||||
silo_<version>_checksums.txt | sha256sum --check
|
||||
|
||||
# 验证归档/SBOM 校验和清单的签名。
|
||||
cosign verify-blob \
|
||||
--bundle silo_<version>_checksums.txt.sigstore.json \
|
||||
--certificate-identity-regexp \
|
||||
'^https://github.com/pgsty/(minio|silo)/\.github/workflows/release\.yml@refs/(tags/RELEASE\..+|heads/(master|main))$' \
|
||||
--certificate-oidc-issuer https://token.actions.githubusercontent.com \
|
||||
silo_<version>_checksums.txt
|
||||
|
||||
# 在线验证本仓库签发的构建来源。
|
||||
gh attestation verify silo_<version>_linux_amd64.tar.gz \
|
||||
--repo pgsty/silo
|
||||
```
|
||||
|
||||
软件包使用 `silo_<version>_packages_checksums.txt` 及其相邻的 Sigstore
|
||||
签名包,并使用相同的 identity 与 issuer 约束;请用 SPDX 工具检查已验证的
|
||||
SPDX JSON SBOM。按 digest 验证多架构容器清单的构建来源:
|
||||
|
||||
```bash
|
||||
gh attestation verify \
|
||||
oci://index.docker.io/pgsty/silo@sha256:<manifest-digest> \
|
||||
--repo pgsty/silo
|
||||
```
|
||||
|
||||
分架构 SBOM 证明附在 `amd64` 与 `arm64` 平台镜像的 digest 上,而非多架构
|
||||
清单上,需要分别显式验证:
|
||||
|
||||
```bash
|
||||
gh attestation verify \
|
||||
oci://index.docker.io/pgsty/silo@sha256:<platform-digest> \
|
||||
--repo pgsty/silo \
|
||||
--predicate-type https://spdx.dev/Document/v2.3
|
||||
```
|
||||
|
||||
按 digest 验证可避免信任可变镜像标签。
|
||||
|
||||
### 原生软件包迁移
|
||||
|
||||
`silo` RPM、DEB 与 APK 不针对 `minio` 声明 `Provides`、`Obsoletes`、
|
||||
`Replaces` 或包级 `Conflicts`,因此可以与已有 MinIO 软件包并存安装,
|
||||
不会被普通升级静默替换。两个 systemd unit 在运行时互斥,应由管理员显式
|
||||
切换,不能同时启动。
|
||||
|
||||
切换前请记录旧 unit 的 enabled/active 状态与 `User`/`Group`,并备份
|
||||
`/etc/default/minio`。Silo 先读取该旧配置,再读取 `/etc/default/silo`;后者
|
||||
中由管理员设置的同名变量优先。如现有数据必须继续使用原 UID/GID,请创建
|
||||
`/etc/systemd/system/silo.service.d/10-legacy-user.conf`:
|
||||
|
||||
```ini
|
||||
[Service]
|
||||
User=<legacy-user>
|
||||
Group=<legacy-group>
|
||||
```
|
||||
|
||||
执行 `systemctl daemon-reload`,先停用并停止 `minio.service`,再启用并启动
|
||||
`silo.service`。确认健康检查、S3、Admin API、指标与日志后,才 mask 或卸载
|
||||
旧服务。软件包迁移期间不要递归修改数据属主;在回滚观察窗口内保留旧包与
|
||||
旧 unit。
|
||||
|
||||
## 快速开始
|
||||
|
||||
本地体验:
|
||||
|
||||
```bash
|
||||
mkdir -p data
|
||||
|
||||
export MINIO_ROOT_USER=minioadmin
|
||||
export MINIO_ROOT_PASSWORD=change-me-long-password
|
||||
|
||||
docker run -d --name silo \
|
||||
-p 9000:9000 \
|
||||
-p 9001:9001 \
|
||||
-e MINIO_ROOT_USER \
|
||||
-e MINIO_ROOT_PASSWORD \
|
||||
docker run -d --name silo -p 9000:9000 -p 9001:9001 \
|
||||
-e MINIO_ROOT_USER=minioadmin \
|
||||
-e MINIO_ROOT_PASSWORD=change-me-long-password \
|
||||
-v "$PWD/data:/data" \
|
||||
docker.io/pgsty/silo:latest server /data --console-address ":9001"
|
||||
```
|
||||
|
||||
管理控制台位于 <http://localhost:9001>,S3 API 位于 <http://localhost:9000>。
|
||||
<p align="center">
|
||||
<img src="https://silo.pgsty.com/images/silo-console/console-login.webp" alt="Silo 控制台">
|
||||
</p>
|
||||
|
||||
镜像内置兼容客户端 `mcli`:
|
||||
控制台位于 <http://localhost:9001>,S3 API 位于 <http://localhost:9000>。镜像内置客户端 `mcli`:
|
||||
|
||||
```bash
|
||||
docker exec silo mcli alias set local http://127.0.0.1:9000 \
|
||||
"$MINIO_ROOT_USER" "$MINIO_ROOT_PASSWORD"
|
||||
docker exec silo mcli mb local/demo
|
||||
docker exec silo mcli ls local
|
||||
docker exec silo mcli alias set local http://127.0.0.1:9000 minioadmin change-me-long-password
|
||||
docker exec silo mcli mb local/demo && docker exec silo mcli ls local
|
||||
```
|
||||
|
||||
> [!WARNING]
|
||||
> 生产环境应锁定版本,使用独立凭据与 TLS,配置监控,保留独立备份,并验证恢复流程。
|
||||
> 生产环境应锁定版本,使用独立凭据与 TLS,配置监控,保留独立备份,并验证恢复流程。请从[文档](https://silo.pgsty.com/zh/docs/)开始。
|
||||
|
||||
从源码构建服务端:
|
||||
## 安装
|
||||
|
||||
```bash
|
||||
go build -o silo .
|
||||
./silo --version
|
||||
```
|
||||
| 方式 | 位置 |
|
||||
| :-- | :-- |
|
||||
| 容器镜像 | [`pgsty/silo`](https://hub.docker.com/r/pgsty/silo),支持 `linux/amd64` 与 `linux/arm64` |
|
||||
| 二进制 | [GitHub Releases](https://github.com/pgsty/silo/releases),覆盖 Linux、macOS、Windows 的 `amd64` 与 `arm64` |
|
||||
| 软件包 | RPM、DEB、APK,也可通过 [Pigsty 软件仓库](https://pigsty.cc/docs/repo/) 安装 |
|
||||
| Kubernetes | Helm Chart,参见[下载与安装](https://silo.pgsty.com/zh/download/) |
|
||||
| 源码构建 | `go build -o silo . && ./silo --version` |
|
||||
|
||||
其他安装方式(包括原生软件包、二进制、Podman、Kubernetes、源码构建与 Pigsty Ansible)请前往[下载与安装](https://silo.pgsty.com/zh/download/);生产部署与管理请从 [Silo 文档](https://silo.pgsty.com/zh/docs/)开始。Pigsty 用户也可以直接使用 [Pigsty MinIO 模块](https://pigsty.cc/docs/minio/)。
|
||||
每个版本都附带校验和、SPDX SBOM、Sigstore 签名清单与 GitHub 构建证明。完整安装方式与验证命令见[下载与安装](https://silo.pgsty.com/zh/download/);从上游 MinIO 迁移 —— 接管既有 `minio.service` 与 `/etc/default/minio`,并用 `/etc/systemd/system/silo.service.d/10-legacy-user.conf` drop-in 保持数据属主不变 —— 见[迁移指南](https://silo.pgsty.com/zh/compatibility/migration/)与[二进制与服务说明](https://silo.pgsty.com/zh/compatibility/binary/)。
|
||||
|
||||
## 安全
|
||||
## 兼容性
|
||||
|
||||
安全修复面向当前活跃开发分支,并记录在仓库[安全公告](docs/security/advisories.md)与门户[安全通告](https://silo.pgsty.com/zh/blog/security/)中。请按照 [`SECURITY.md`](SECURITY.md) 与 [`VULNERABILITY_REPORT.md`](VULNERABILITY_REPORT.md) 私密报告漏洞;同时影响上游 MinIO 的问题也应向上游报告。
|
||||
S3 API、`MINIO_*` 环境变量、`minio_*` 指标、`x-minio-*` 头、`/minio/*` 路由、`github.com/minio/*` 导入路径与磁盘格式(含 `.minio.sys`)原样保留,并由 CI 兼容性门禁冻结。只有 Silo 自有交付面改名:`silo` 可执行文件、软件包、服务、Helm Chart 与容器镜像 —— 原生交付物不会安装 `minio` 二进制别名。
|
||||
|
||||
## 贡献
|
||||
与上游的全部分歧,以逐项核验代码的[兼容性审计](https://silo.pgsty.com/zh/compatibility/server/)形式维护。每个版本仍应视为下游升级:锁定版本,阅读[版本说明](https://silo.pgsty.com/zh/tags/silo/),并保留回滚路径。
|
||||
|
||||
欢迎安全与依赖项更新、可复现缺陷修复、测试、发布自动化、打包与文档改进。
|
||||
## 安全与贡献
|
||||
|
||||
Issue 与 Pull Request 应说明受影响版本、复现步骤、影响、预期行为、测试与兼容性说明。大型改动请先提交 Issue 讨论。
|
||||
请按照 [`SECURITY.md`](SECURITY.md) 私密报告漏洞;每项修复都会发布公开[安全公告](https://silo.pgsty.com/zh/blog/security/)。本项目不要求签署 CLA:贡献按 AGPL-3.0-or-later(inbound=outbound)接收,只需 DCO 签署(`git commit -s`),详见 [`CONTRIBUTING.md`](CONTRIBUTING.md)。
|
||||
|
||||
本项目不要求签署 CLA:贡献按项目许可证(AGPL-3.0-or-later,inbound=outbound)接收,贡献者保留自己的版权。每个提交都必须按照 [DCO](https://developercertificate.org/) 签署(`git commit -s`),详见 [`CONTRIBUTING.md`](CONTRIBUTING.md)。
|
||||
## 贡献者
|
||||
|
||||
<table>
|
||||
<tr>
|
||||
<td align="center" width="150">
|
||||
<a href="https://github.com/ZouhairCharef"><img src="https://github.com/ZouhairCharef.png?size=100" width="72" alt="ZouhairCharef"><br><sub><b>@ZouhairCharef</b></sub></a><br><sub>CVE-2026-34986</sub>
|
||||
</td>
|
||||
<td align="center" width="150">
|
||||
<a href="https://github.com/mfredenhagen"><img src="https://github.com/mfredenhagen.png?size=100" width="72" alt="mfredenhagen"><br><sub><b>@mfredenhagen</b></sub></a><br><sub>CVE-2026-39883</sub>
|
||||
</td>
|
||||
<td align="center" width="150">
|
||||
<a href="https://github.com/pinginfo"><img src="https://github.com/pinginfo.png?size=100" width="72" alt="pinginfo"><br><sub><b>@pinginfo</b></sub></a><br><sub>桶通知流式输出</sub>
|
||||
</td>
|
||||
<td align="center" width="150">
|
||||
<a href="https://github.com/waterkip"><img src="https://github.com/waterkip.png?size=100" width="72" alt="waterkip"><br><sub><b>@waterkip</b></sub></a><br><sub>文档链接修正</sub>
|
||||
</td>
|
||||
</tr>
|
||||
</table>
|
||||
<p>
|
||||
<a href="https://github.com/magicxor"><img src="https://github.com/magicxor.png?size=64" width="44" alt="magicxor" title="@magicxor"></a>
|
||||
<a href="https://github.com/ycjlin"><img src="https://github.com/ycjlin.png?size=64" width="44" alt="ycjlin" title="@ycjlin"></a>
|
||||
<a href="https://github.com/davinkevin"><img src="https://github.com/davinkevin.png?size=64" width="44" alt="davinkevin" title="@davinkevin"></a>
|
||||
<a href="https://github.com/lem21h"><img src="https://github.com/lem21h.png?size=64" width="44" alt="lem21h" title="@lem21h"></a>
|
||||
<a href="https://github.com/sulin37392"><img src="https://github.com/sulin37392.png?size=64" width="44" alt="sulin37392" title="@sulin37392"></a>
|
||||
<a href="https://github.com/mosesdd"><img src="https://github.com/mosesdd.png?size=64" width="44" alt="mosesdd" title="@mosesdd"></a>
|
||||
<a href="https://github.com/Xavier-777"><img src="https://github.com/Xavier-777.png?size=64" width="44" alt="Xavier-777" title="@Xavier-777"></a>
|
||||
<a href="https://github.com/jiadzh"><img src="https://github.com/jiadzh.png?size=64" width="44" alt="jiadzh" title="@jiadzh"></a>
|
||||
<a href="https://github.com/TLINDEN"><img src="https://github.com/TLINDEN.png?size=64" width="44" alt="TLINDEN" title="@TLINDEN"></a>
|
||||
<a href="https://github.com/AntonOfTheWoods"><img src="https://github.com/AntonOfTheWoods.png?size=64" width="44" alt="AntonOfTheWoods" title="@AntonOfTheWoods"></a>
|
||||
<a href="https://github.com/zylpsrs"><img src="https://github.com/zylpsrs.png?size=64" width="44" alt="zylpsrs" title="@zylpsrs"></a>
|
||||
<a href="https://github.com/nsanitate"><img src="https://github.com/nsanitate.png?size=64" width="44" alt="nsanitate" title="@nsanitate"></a>
|
||||
<a href="https://github.com/makinikm"><img src="https://github.com/makinikm.png?size=64" width="44" alt="makinikm" title="@makinikm"></a>
|
||||
<a href="https://github.com/spaceg00se-r"><img src="https://github.com/spaceg00se-r.png?size=64" width="44" alt="spaceg00se-r" title="@spaceg00se-r"></a>
|
||||
<a href="https://github.com/heroes1412"><img src="https://github.com/heroes1412.png?size=64" width="44" alt="heroes1412" title="@heroes1412"></a>
|
||||
<a href="https://github.com/vampywiz17"><img src="https://github.com/vampywiz17.png?size=64" width="44" alt="vampywiz17" title="@vampywiz17"></a>
|
||||
<a href="https://github.com/chalukyaj"><img src="https://github.com/chalukyaj.png?size=64" width="44" alt="chalukyaj" title="@chalukyaj"></a>
|
||||
<a href="https://github.com/cbornet"><img src="https://github.com/cbornet.png?size=64" width="44" alt="cbornet" title="@cbornet"></a>
|
||||
<a href="https://github.com/jvasile"><img src="https://github.com/jvasile.png?size=64" width="44" alt="jvasile" title="@jvasile"></a>
|
||||
<a href="https://github.com/Kesavaambati"><img src="https://github.com/Kesavaambati.png?size=64" width="44" alt="Kesavaambati" title="@Kesavaambati"></a>
|
||||
<a href="https://github.com/redfoxfox"><img src="https://github.com/redfoxfox.png?size=64" width="44" alt="redfoxfox" title="@redfoxfox"></a>
|
||||
<a href="https://github.com/kuldeep-link11"><img src="https://github.com/kuldeep-link11.png?size=64" width="44" alt="kuldeep-link11" title="@kuldeep-link11"></a>
|
||||
<a href="https://github.com/meesudzu"><img src="https://github.com/meesudzu.png?size=64" width="44" alt="meesudzu" title="@meesudzu"></a>
|
||||
<a href="https://github.com/pmezhuev"><img src="https://github.com/pmezhuev.png?size=64" width="44" alt="pmezhuev" title="@pmezhuev"></a>
|
||||
<a href="https://github.com/kh0mka"><img src="https://github.com/kh0mka.png?size=64" width="44" alt="kh0mka" title="@kh0mka"></a>
|
||||
</p>
|
||||
|
||||
GitHub 不为 fork 仓库生成贡献者图表,因此 [`CONTRIBUTORS.md`](CONTRIBUTORS.md)(而非 Insights 页面)才是本项目的署名记录,其中逐一记录了每个人对应的改动或报告。
|
||||
|
||||
## 背景
|
||||
|
||||
本项目源于上游社区发行与维护模式的变化。维护者对相关变化的分析、替代方案评估与早期维护记录见以下文章:
|
||||
本项目因上游收缩社区版而生:Web 控制台被削减为残桩、社区预编译制品停发、社区仓库被归档。Silo 的存在就是让这些部署继续跑下去。Fork 是手段,不是身份 —— 若上游恢复社区版承诺,我们乐意收缩范围,并把修复回馈上游。
|
||||
|
||||
| 文章 | 主题 |
|
||||
| :-- | :-- |
|
||||
| [MinIO已死](https://silo.pgsty.com/zh/blog/post/minio-is-dead/) | 上游项目与发行模式的变化 |
|
||||
| [MinIO已死,谁能接盘?](https://silo.pgsty.com/zh/blog/post/minio-alternative/) | 可选替代方案评估 |
|
||||
| [MinIO 已死,MinIO 复生](https://silo.pgsty.com/zh/blog/post/minio-resurrect/) | 建立分支及其发行流水线 |
|
||||
| [续命 MinIO:承诺兑现](https://silo.pgsty.com/zh/blog/post/minio-promise-kept/) | 初期安全与维护工作 |
|
||||
[**宣言**](https://silo.pgsty.com/zh/about/manifesto/)是项目的公开承诺,共十一条,通篇遵循一项纪律:**每一条,要么是已经在做且有公开证据的事实,要么是刻意拒绝的承诺。** 摘要:
|
||||
|
||||
- **兼容性合同** —— 协议与数据不改,每个版本都标注经过测试的回滚目标与路径。
|
||||
- **许可证无法变更** —— AGPLv3、无 CLA、不做版权聚合;包括我们自己在内,没有人握有足够版权代表所有贡献者重新授权。
|
||||
- **永不清单**(只增不减)—— 永不将既有功能移入付费墙、永不给下载设注册墙、永不加入遥测(上游回连路径已整体移除)、永不引入 CLA、永不变更许可证、永不以商标追究正常使用。
|
||||
- **安全与发布纪律** —— 每项安全修复配一篇公开公告;通常每一到两个月发布一版,最长不超过一个季度。请拿公开记录检验这两条。
|
||||
|
||||
延伸阅读:[MinIO已死](https://silo.pgsty.com/zh/blog/post/minio-is-dead/) · [谁能接盘?](https://silo.pgsty.com/zh/blog/post/minio-alternative/) · [MinIO 复生](https://silo.pgsty.com/zh/blog/post/minio-resurrect/) · [承诺兑现](https://silo.pgsty.com/zh/blog/post/minio-promise-kept/)
|
||||
|
||||
## 许可证与商标
|
||||
|
||||
服务端源码依据 [GNU Affero 通用公共许可证第 3 版或任何后续版本](LICENSE)分发。本分支衍生自 [`minio/minio`](https://github.com/minio/minio):[`NOTICE`](NOTICE) 保留上游产品声明,[`CREDITS`](CREDITS) 记录所含第三方组件的许可证与声明,Git 历史记录下游修改。
|
||||
Silo 采用 [AGPL-3.0-or-later](LICENSE),衍生自 [`minio/minio`](https://github.com/minio/minio),上游版权与第三方声明完整保留于 [`NOTICE`](NOTICE) 与 [`CREDITS`](CREDITS)。MinIO 是 MinIO, Inc. 的商标,此处使用仅为标识上游项目与兼容谱系。
|
||||
|
||||
MinIO 是 MinIO, Inc. 的商标;本文仅为标识上游项目与兼容谱系而使用该名称。Pigsty、Silo 与 `pgsty/silo` 均为独立社区项目,与 MinIO, Inc. 不存在隶属、背书或赞助关系。
|
||||
|
||||
门户另行发布项目的[许可证摘要](https://silo.pgsty.com/zh/about/license/)、[文档署名归属](https://silo.pgsty.com/zh/about/attribution/)与[商标声明](https://silo.pgsty.com/zh/about/trademark/)。
|
||||
详见:[许可证](https://silo.pgsty.com/zh/about/license/) · [署名归属](https://silo.pgsty.com/zh/about/attribution/) · [商标声明](https://silo.pgsty.com/zh/about/trademark/)
|
||||
|
||||
+19
@@ -10,6 +10,25 @@ Security fixes are tracked on the active development branch and summarized in
|
||||
[docs/security/advisories.md](docs/security/advisories.md). Only the current
|
||||
Silo release line is supported unless an advisory says otherwise.
|
||||
|
||||
## Inherited Fix Evidence
|
||||
|
||||
The canonical ledger also records security fixes inherited from upstream when
|
||||
they are part of the Silo release baseline. Source and fork commits are linked
|
||||
separately even when the fork preserves the original commit object and SHA.
|
||||
|
||||
- [CVE-2025-62506](https://github.com/advisories/GHSA-jjjj-jwhf-8rgr):
|
||||
upstream [PR #21642](https://github.com/minio/minio/pull/21642) merged as
|
||||
[`minio/minio@c1a49490`](https://github.com/minio/minio/commit/c1a49490c78e9c3ebcad86ba0662319138ace190),
|
||||
inherited unchanged as
|
||||
[`pgsty/silo@c1a49490`](https://github.com/pgsty/silo/commit/c1a49490c78e9c3ebcad86ba0662319138ace190),
|
||||
and is present in every Silo community release beginning with
|
||||
[`RELEASE.2025-12-03T12-00-00Z`](https://github.com/pgsty/silo/releases/tag/RELEASE.2025-12-03T12-00-00Z).
|
||||
The inherited [service-account](https://github.com/pgsty/silo/blob/c1a49490c78e9c3ebcad86ba0662319138ace190/cmd/admin-handlers-users_test.go#L211-L212)
|
||||
and [STS](https://github.com/pgsty/silo/blob/c1a49490c78e9c3ebcad86ba0662319138ace190/cmd/sts-handlers_test.go#L45-L46)
|
||||
regression groups remain part of `go test ./cmd`; see the
|
||||
[canonical ledger](docs/security/advisories.md#inherited-upstream-advisory-baseline)
|
||||
for the operator-facing record.
|
||||
|
||||
## Reporting a Vulnerability
|
||||
|
||||
For vulnerabilities in this fork:
|
||||
|
||||
Executable
+76
@@ -0,0 +1,76 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
# Fail closed before a release job can replace published or finalized assets.
|
||||
# An ordinary Draft is retry state; a finalized Draft contains GPG-derived
|
||||
# materials and must never be replaced by the build lane.
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
release_tag="${1:-}"
|
||||
fixture="${2:-}"
|
||||
repository="${GITHUB_REPOSITORY:-pgsty/silo}"
|
||||
require_draft="${REQUIRE_DRAFT:-false}"
|
||||
|
||||
if ! command -v jq >/dev/null 2>&1; then
|
||||
echo "jq is required to inspect GitHub release state" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [[ ! "${release_tag}" =~ ^RELEASE\.[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}-[0-9]{2}-[0-9]{2}Z$ ]]; then
|
||||
echo "Invalid release tag format: ${release_tag:-<empty>}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ -n "${fixture}" ]; then
|
||||
release_json="$(<"${fixture}")"
|
||||
else
|
||||
error_file="$(mktemp)"
|
||||
trap 'rm -f "${error_file}"' EXIT
|
||||
if ! release_json="$(
|
||||
gh api --paginate "repos/${repository}/releases?per_page=100" --jq '.[]' 2>"${error_file}" |
|
||||
jq --arg tag "${release_tag}" -s '[.[] | select(.tag_name == $tag)]'
|
||||
)"; then
|
||||
cat "${error_file}" >&2
|
||||
exit 1
|
||||
fi
|
||||
fi
|
||||
|
||||
if ! jq -e 'type == "array" and all(.[]; type == "object" and (.tag_name | type == "string") and (.draft | type == "boolean"))' \
|
||||
<<<"${release_json}" >/dev/null 2>&1; then
|
||||
echo "Invalid release state response for ${release_tag}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if ! jq -e --arg tag "${release_tag}" 'all(.[]; .tag_name == $tag)' \
|
||||
<<<"${release_json}" >/dev/null 2>&1; then
|
||||
echo "Release state returned a tag other than ${release_tag}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
release_count="$(jq 'length' <<<"${release_json}")"
|
||||
if [ "${release_count}" -eq 0 ]; then
|
||||
if [ "${require_draft}" = "true" ]; then
|
||||
echo "Expected one Draft release for ${release_tag}, found none" >&2
|
||||
exit 1
|
||||
fi
|
||||
echo "No existing release for ${release_tag}."
|
||||
exit 0
|
||||
fi
|
||||
|
||||
if [ "${release_count}" -ne 1 ]; then
|
||||
echo "Refusing to choose among ${release_count} releases for ${release_tag}; clean duplicate Drafts first" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
if [ "$(jq -r '.[0].draft' <<<"${release_json}")" != "true" ]; then
|
||||
echo "Refusing to overwrite published release ${release_tag}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
finalize_markers="$(jq '[.[0].assets[]? | select(.name | endswith("_packages_provenance.sigstore.json"))] | length' <<<"${release_json}")"
|
||||
if [ "${finalize_markers}" -ne 0 ]; then
|
||||
echo "Refusing to replace finalized Draft ${release_tag}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
echo "Existing unfinalized Draft ${release_tag} will be replaced from scratch."
|
||||
Executable
+68
@@ -0,0 +1,68 @@
|
||||
#!/usr/bin/env bash
|
||||
|
||||
set -euo pipefail
|
||||
|
||||
script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
|
||||
checker="${script_dir}/check-release-state.sh"
|
||||
tag="RELEASE.2026-08-29T00-00-00Z"
|
||||
fixture="$(mktemp)"
|
||||
stdout_file="$(mktemp)"
|
||||
stderr_file="$(mktemp)"
|
||||
trap 'rm -f "${fixture}" "${stdout_file}" "${stderr_file}"' EXIT
|
||||
|
||||
expect_success() {
|
||||
if ! "${checker}" "$@" >"${stdout_file}" 2>"${stderr_file}"; then
|
||||
cat "${stderr_file}" >&2
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
expect_failure() {
|
||||
if "${checker}" "$@" >"${stdout_file}" 2>"${stderr_file}"; then
|
||||
echo "Expected release-state check to fail: $*" >&2
|
||||
return 1
|
||||
fi
|
||||
}
|
||||
|
||||
printf '[]\n' >"${fixture}"
|
||||
expect_success "${tag}" "${fixture}"
|
||||
grep -qF "No existing release for ${tag}." "${stdout_file}"
|
||||
|
||||
if REQUIRE_DRAFT=true "${checker}" "${tag}" "${fixture}" >"${stdout_file}" 2>"${stderr_file}"; then
|
||||
echo "Expected required-Draft check to fail when no release exists" >&2
|
||||
exit 1
|
||||
fi
|
||||
grep -qF "Expected one Draft release for ${tag}, found none" "${stderr_file}"
|
||||
|
||||
printf '[{"tag_name":"%s","draft":true,"assets":[]}]\n' "${tag}" >"${fixture}"
|
||||
expect_success "${tag}" "${fixture}"
|
||||
grep -qF "Existing unfinalized Draft ${tag} will be replaced from scratch." "${stdout_file}"
|
||||
if ! REQUIRE_DRAFT=true "${checker}" "${tag}" "${fixture}" >"${stdout_file}" 2>"${stderr_file}"; then
|
||||
cat "${stderr_file}" >&2
|
||||
exit 1
|
||||
fi
|
||||
|
||||
printf '[{"tag_name":"%s","draft":true,"assets":[{"name":"silo_20260829000000.0.0_packages_provenance.sigstore.json"}]}]\n' "${tag}" >"${fixture}"
|
||||
expect_failure "${tag}" "${fixture}"
|
||||
grep -qF "Refusing to replace finalized Draft ${tag}" "${stderr_file}"
|
||||
|
||||
printf '[{"tag_name":"%s","draft":false}]\n' "${tag}" >"${fixture}"
|
||||
expect_failure "${tag}" "${fixture}"
|
||||
grep -qF "Refusing to overwrite published release ${tag}" "${stderr_file}"
|
||||
|
||||
printf '[{"tag_name":"%s","draft":true},{"tag_name":"%s","draft":true}]\n' "${tag}" "${tag}" >"${fixture}"
|
||||
expect_failure "${tag}" "${fixture}"
|
||||
grep -qF "Refusing to choose among 2 releases" "${stderr_file}"
|
||||
|
||||
printf '[{"tag_name":"RELEASE.2026-08-28T00-00-00Z","draft":true}]\n' >"${fixture}"
|
||||
expect_failure "${tag}" "${fixture}"
|
||||
grep -qF "other than ${tag}" "${stderr_file}"
|
||||
|
||||
printf '{not-json}\n' >"${fixture}"
|
||||
expect_failure "${tag}" "${fixture}"
|
||||
grep -qF "Invalid release state response for ${tag}" "${stderr_file}"
|
||||
|
||||
expect_failure "not-a-release-tag" "${fixture}"
|
||||
grep -qF "Invalid release tag format" "${stderr_file}"
|
||||
|
||||
echo "release-state decision tests passed"
|
||||
@@ -7,7 +7,7 @@ _init() {
|
||||
|
||||
## Minimum required versions for build dependencies
|
||||
GIT_VERSION="1.0"
|
||||
GO_VERSION="1.16"
|
||||
GO_VERSION="1.27.0"
|
||||
OSX_VERSION="10.8"
|
||||
KNAME=$(uname -s)
|
||||
ARCH=$(uname -m)
|
||||
|
||||
@@ -41,6 +41,7 @@
|
||||
"github.com/minio/minio/internal/auth",
|
||||
"github.com/minio/minio/internal/bpool",
|
||||
"github.com/minio/minio/internal/bucket/bandwidth",
|
||||
"github.com/minio/minio/internal/bucket/cors",
|
||||
"github.com/minio/minio/internal/bucket/encryption",
|
||||
"github.com/minio/minio/internal/bucket/lifecycle",
|
||||
"github.com/minio/minio/internal/bucket/object/lock",
|
||||
@@ -692,6 +693,7 @@
|
||||
"/%s/us-east-1/s3/aws4_request",
|
||||
"/*",
|
||||
"/../../etc",
|
||||
"/../obj",
|
||||
"/./abc/def",
|
||||
"/.dockerenv",
|
||||
"/.trash",
|
||||
@@ -704,6 +706,7 @@
|
||||
"//contains/double-forwardslash-prefix",
|
||||
"/?",
|
||||
"/?X-Amz-Algorithm=AWS4-HMAC-SHA256\u0026X-Amz-Credential=USWUXHGYZQYFYFFIT3RE%2F20170529%2Fus-east-1%2Fs3%2Faws4_request\u0026X-Amz-Date=20170529T190139Z\u0026X-Amz-Expires=600\u0026X-Amz-Signature=19b58080999df54b446fc97304eb8dda60d3df1812ae97f3e8783351bfd9781d\u0026X-Amz-SignedHeaders=host\u0026prefix=Hello%2AWorld%2A",
|
||||
"/A/obj",
|
||||
"/a",
|
||||
"/a/b/c",
|
||||
"/a/b/c/d/e/f/g",
|
||||
@@ -720,6 +723,7 @@
|
||||
"/admin",
|
||||
"/afile",
|
||||
"/api/requests",
|
||||
"/api/v1/login",
|
||||
"/apis",
|
||||
"/audit",
|
||||
"/background-heal/status",
|
||||
@@ -759,6 +763,7 @@
|
||||
"/debug/go",
|
||||
"/del-config-kv",
|
||||
"/delete-service-account",
|
||||
"/deny/*",
|
||||
"/describe-job",
|
||||
"/dev/0",
|
||||
"/dev/1",
|
||||
@@ -851,12 +856,14 @@
|
||||
"/ls",
|
||||
"/metrics",
|
||||
"/metrics/v3",
|
||||
"/minio/admin/v3/info",
|
||||
"/minio/grid/",
|
||||
"/minio/grid/lock/",
|
||||
"/minio/health/cluster",
|
||||
"/minio/health/cluster/read",
|
||||
"/minio/health/live",
|
||||
"/minio/health/ready",
|
||||
"/mybucket/obj",
|
||||
"/myobject*",
|
||||
"/netperf",
|
||||
"/newfolder",
|
||||
@@ -968,6 +975,7 @@
|
||||
"/speedtest/site",
|
||||
"/start-job",
|
||||
"/startprofiling",
|
||||
"/startup-missing/object",
|
||||
"/status",
|
||||
"/status-job",
|
||||
"/storage",
|
||||
@@ -1018,6 +1026,7 @@
|
||||
"/version",
|
||||
"/vfile",
|
||||
"/wall",
|
||||
"/x/obj",
|
||||
"/xl.meta",
|
||||
"/{bucket}",
|
||||
"/{object:.+}"
|
||||
@@ -1708,6 +1717,8 @@
|
||||
"cmd:cmd:field:BucketMetadata.BucketTargetsConfigMetaJSON",
|
||||
"cmd:cmd:field:BucketMetadata.BucketTargetsConfigMetaUpdatedAt",
|
||||
"cmd:cmd:field:BucketMetadata.BucketTargetsConfigUpdatedAt",
|
||||
"cmd:cmd:field:BucketMetadata.CorsConfigUpdatedAt",
|
||||
"cmd:cmd:field:BucketMetadata.CorsConfigXML",
|
||||
"cmd:cmd:field:BucketMetadata.Created",
|
||||
"cmd:cmd:field:BucketMetadata.EncryptionConfigUpdatedAt",
|
||||
"cmd:cmd:field:BucketMetadata.EncryptionConfigXML",
|
||||
@@ -1811,6 +1822,7 @@
|
||||
"cmd:cmd:field:CompleteMultipartUploadResponse.ChecksumCRC64NVME",
|
||||
"cmd:cmd:field:CompleteMultipartUploadResponse.ChecksumSHA1",
|
||||
"cmd:cmd:field:CompleteMultipartUploadResponse.ChecksumSHA256",
|
||||
"cmd:cmd:field:CompleteMultipartUploadResponse.ChecksumType",
|
||||
"cmd:cmd:field:CompleteMultipartUploadResponse.ETag",
|
||||
"cmd:cmd:field:CompleteMultipartUploadResponse.Key",
|
||||
"cmd:cmd:field:CompleteMultipartUploadResponse.Location",
|
||||
@@ -1824,9 +1836,20 @@
|
||||
"cmd:cmd:field:CompletePart.PartNumber",
|
||||
"cmd:cmd:field:CompletePart.Size",
|
||||
"cmd:cmd:field:ConsoleLogger.Enable",
|
||||
"cmd:cmd:field:CopyObjectPartResponse.ChecksumCRC32",
|
||||
"cmd:cmd:field:CopyObjectPartResponse.ChecksumCRC32C",
|
||||
"cmd:cmd:field:CopyObjectPartResponse.ChecksumCRC64NVME",
|
||||
"cmd:cmd:field:CopyObjectPartResponse.ChecksumSHA1",
|
||||
"cmd:cmd:field:CopyObjectPartResponse.ChecksumSHA256",
|
||||
"cmd:cmd:field:CopyObjectPartResponse.ETag",
|
||||
"cmd:cmd:field:CopyObjectPartResponse.LastModified",
|
||||
"cmd:cmd:field:CopyObjectPartResponse.XMLName",
|
||||
"cmd:cmd:field:CopyObjectResponse.ChecksumCRC32",
|
||||
"cmd:cmd:field:CopyObjectResponse.ChecksumCRC32C",
|
||||
"cmd:cmd:field:CopyObjectResponse.ChecksumCRC64NVME",
|
||||
"cmd:cmd:field:CopyObjectResponse.ChecksumSHA1",
|
||||
"cmd:cmd:field:CopyObjectResponse.ChecksumSHA256",
|
||||
"cmd:cmd:field:CopyObjectResponse.ChecksumType",
|
||||
"cmd:cmd:field:CopyObjectResponse.ETag",
|
||||
"cmd:cmd:field:CopyObjectResponse.LastModified",
|
||||
"cmd:cmd:field:CopyObjectResponse.XMLName",
|
||||
@@ -3115,12 +3138,15 @@
|
||||
"cmd:cmd:method:BucketMetadataSys.GetBucketTargetsConfig",
|
||||
"cmd:cmd:method:BucketMetadataSys.GetConfig",
|
||||
"cmd:cmd:method:BucketMetadataSys.GetConfigFromDisk",
|
||||
"cmd:cmd:method:BucketMetadataSys.GetCorsConfig",
|
||||
"cmd:cmd:method:BucketMetadataSys.GetCorsConfigXML",
|
||||
"cmd:cmd:method:BucketMetadataSys.GetLifecycleConfig",
|
||||
"cmd:cmd:method:BucketMetadataSys.GetNotificationConfig",
|
||||
"cmd:cmd:method:BucketMetadataSys.GetObjectLockConfig",
|
||||
"cmd:cmd:method:BucketMetadataSys.GetPolicyConfig",
|
||||
"cmd:cmd:method:BucketMetadataSys.GetQuotaConfig",
|
||||
"cmd:cmd:method:BucketMetadataSys.GetReplicationConfig",
|
||||
"cmd:cmd:method:BucketMetadataSys.GetResidentCorsConfig",
|
||||
"cmd:cmd:method:BucketMetadataSys.GetSSEConfig",
|
||||
"cmd:cmd:method:BucketMetadataSys.GetTaggingConfig",
|
||||
"cmd:cmd:method:BucketMetadataSys.GetVersioningConfig",
|
||||
@@ -4020,6 +4046,7 @@
|
||||
"cmd:cmd:method:SiteReplicationSys.Netperf",
|
||||
"cmd:cmd:method:SiteReplicationSys.PeerAddPolicyHandler",
|
||||
"cmd:cmd:method:SiteReplicationSys.PeerBucketConfigureReplHandler",
|
||||
"cmd:cmd:method:SiteReplicationSys.PeerBucketCorsConfigHandler",
|
||||
"cmd:cmd:method:SiteReplicationSys.PeerBucketDeleteHandler",
|
||||
"cmd:cmd:method:SiteReplicationSys.PeerBucketLCConfigHandler",
|
||||
"cmd:cmd:method:SiteReplicationSys.PeerBucketMakeWithVersioningHandler",
|
||||
@@ -5861,6 +5888,23 @@
|
||||
"internal/bucket/bandwidth:bandwidth:type:MonitorReaderOptions",
|
||||
"internal/bucket/bandwidth:bandwidth:type:MonitoredReader",
|
||||
"internal/bucket/bandwidth:bandwidth:type:SelectionFunction",
|
||||
"internal/bucket/cors:cors:field:Config.CORSRules",
|
||||
"internal/bucket/cors:cors:field:Config.XMLName",
|
||||
"internal/bucket/cors:cors:field:Rule.AllowedHeaders",
|
||||
"internal/bucket/cors:cors:field:Rule.AllowedMethods",
|
||||
"internal/bucket/cors:cors:field:Rule.AllowedOrigins",
|
||||
"internal/bucket/cors:cors:field:Rule.ExposeHeaders",
|
||||
"internal/bucket/cors:cors:field:Rule.ID",
|
||||
"internal/bucket/cors:cors:field:Rule.MaxAgeSeconds",
|
||||
"internal/bucket/cors:cors:func:ParseBucketCorsConfig",
|
||||
"internal/bucket/cors:cors:method:Config.MatchPreflight",
|
||||
"internal/bucket/cors:cors:method:Config.MatchRule",
|
||||
"internal/bucket/cors:cors:method:Config.Validate",
|
||||
"internal/bucket/cors:cors:method:Rule.FilterAllowedHeaders",
|
||||
"internal/bucket/cors:cors:method:Rule.HasAllowedMethod",
|
||||
"internal/bucket/cors:cors:method:Rule.HasAllowedOrigin",
|
||||
"internal/bucket/cors:cors:type:Config",
|
||||
"internal/bucket/cors:cors:type:Rule",
|
||||
"internal/bucket/encryption:sse:const:AES256",
|
||||
"internal/bucket/encryption:sse:const:AWSKms",
|
||||
"internal/bucket/encryption:sse:field:ApplyOptions.AutoEncrypt",
|
||||
@@ -6938,7 +6982,9 @@
|
||||
"internal/config/notify:notify:func:SetNotifyRedis",
|
||||
"internal/config/notify:notify:func:SetNotifyWebhook",
|
||||
"internal/config/notify:notify:func:TestSubSysNotificationTargets",
|
||||
"internal/config/notify:notify:method:LegacyDatabaseTargetError.Error",
|
||||
"internal/config/notify:notify:type:Config",
|
||||
"internal/config/notify:notify:type:LegacyDatabaseTargetError",
|
||||
"internal/config/notify:notify:var:DefaultAMQPKVS",
|
||||
"internal/config/notify:notify:var:DefaultESKVS",
|
||||
"internal/config/notify:notify:var:DefaultKafkaKVS",
|
||||
@@ -10220,6 +10266,10 @@
|
||||
"cmd/object-multipart-handlers.go=\"X-Minio-Replication-Server-Side-Encryption-Iv\"",
|
||||
"cmd/object-multipart-handlers.go=\"X-Minio-Replication-Server-Side-Encryption-Seal-Algorithm\"",
|
||||
"cmd/object-multipart-handlers.go=\"X-Minio-Replication-Server-Side-Encryption-Sealed-Key\"",
|
||||
"cmd/replication-trust.go=\"X-Minio-Replication-Encrypted-Multipart\"",
|
||||
"cmd/replication-trust.go=\"X-Minio-Replication-Server-Side-Encryption-Iv\"",
|
||||
"cmd/replication-trust.go=\"X-Minio-Replication-Server-Side-Encryption-Seal-Algorithm\"",
|
||||
"cmd/replication-trust.go=\"X-Minio-Replication-Server-Side-Encryption-Sealed-Key\"",
|
||||
"cmd/s3-zip-handlers.go=\"x-minio-extract\"",
|
||||
"cmd/server-startup-msg.go=\"https://silo.pgsty.com/reference/minio-mc/#quickstart\"",
|
||||
"cmd/storage-rest-server.go=\"X-Minio-Time\"",
|
||||
|
||||
@@ -255,9 +255,11 @@ func (a adminAPIHandlers) SRPeerReplicateBucketItem(w http.ResponseWriter, r *ht
|
||||
case madmin.SRBucketMetaTypeTags:
|
||||
err = globalSiteReplicationSys.PeerBucketTaggingHandler(ctx, item.Bucket, item.Tags, item.UpdatedAt)
|
||||
case madmin.SRBucketMetaTypeObjectLockConfig:
|
||||
err = globalSiteReplicationSys.PeerBucketObjectLockConfigHandler(ctx, item.Bucket, item.ObjectLockConfig, item.UpdatedAt)
|
||||
err = globalSiteReplicationSys.peerBucketObjectLockConfigItem(ctx, item)
|
||||
case madmin.SRBucketMetaTypeSSEConfig:
|
||||
err = globalSiteReplicationSys.PeerBucketSSEConfigHandler(ctx, item.Bucket, item.SSEConfig, item.UpdatedAt)
|
||||
case madmin.SRBucketMetaTypeCorsConfig:
|
||||
err = globalSiteReplicationSys.PeerBucketCorsConfigHandler(ctx, item.Bucket, item.Cors, item.UpdatedAt)
|
||||
case madmin.SRBucketMetaLCConfig:
|
||||
err = globalSiteReplicationSys.PeerBucketLCConfigHandler(ctx, item.Bucket, item.ExpiryLCConfig, item.UpdatedAt)
|
||||
}
|
||||
|
||||
+27
-13
@@ -355,18 +355,25 @@ func (a adminAPIHandlers) ListGroups(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
// SetGroupStatus - PUT /minio/admin/v3/set-group-status?group=mygroup1&status=enabled
|
||||
func setGroupStatusAdminAction(status string) policy.AdminAction {
|
||||
if madmin.GroupStatus(status) == madmin.GroupDisabled {
|
||||
return policy.DisableGroupAdminAction
|
||||
}
|
||||
return policy.EnableGroupAdminAction
|
||||
}
|
||||
|
||||
func (a adminAPIHandlers) SetGroupStatus(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
objectAPI, _ := validateAdminReq(ctx, w, r, policy.EnableGroupAdminAction)
|
||||
if objectAPI == nil {
|
||||
return
|
||||
}
|
||||
|
||||
vars := mux.Vars(r)
|
||||
group := vars["group"]
|
||||
status := vars["status"]
|
||||
|
||||
objectAPI, _ := validateAdminReq(ctx, w, r, setGroupStatusAdminAction(status))
|
||||
if objectAPI == nil {
|
||||
return
|
||||
}
|
||||
|
||||
var (
|
||||
err error
|
||||
updatedAt time.Time
|
||||
@@ -398,18 +405,25 @@ func (a adminAPIHandlers) SetGroupStatus(w http.ResponseWriter, r *http.Request)
|
||||
}
|
||||
|
||||
// SetUserStatus - PUT /minio/admin/v3/set-user-status?accessKey=<access_key>&status=[enabled|disabled]
|
||||
func setUserStatusAdminAction(status string) policy.AdminAction {
|
||||
if madmin.AccountStatus(status) == madmin.AccountDisabled {
|
||||
return policy.DisableUserAdminAction
|
||||
}
|
||||
return policy.EnableUserAdminAction
|
||||
}
|
||||
|
||||
func (a adminAPIHandlers) SetUserStatus(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := r.Context()
|
||||
|
||||
objectAPI, creds := validateAdminReq(ctx, w, r, policy.EnableUserAdminAction)
|
||||
if objectAPI == nil {
|
||||
return
|
||||
}
|
||||
|
||||
vars := mux.Vars(r)
|
||||
accessKey := vars["accessKey"]
|
||||
status := vars["status"]
|
||||
|
||||
objectAPI, creds := validateAdminReq(ctx, w, r, setUserStatusAdminAction(status))
|
||||
if objectAPI == nil {
|
||||
return
|
||||
}
|
||||
|
||||
// you cannot enable or disable yourself.
|
||||
if accessKey == creds.AccessKey {
|
||||
writeErrorResponseJSON(ctx, w, toAdminAPIErr(ctx, errInvalidArgument), r.URL)
|
||||
@@ -859,7 +873,7 @@ func (a adminAPIHandlers) UpdateServiceAccount(w http.ResponseWriter, r *http.Re
|
||||
|
||||
var sp *policy.Policy
|
||||
if len(updateReq.NewPolicy) > 0 {
|
||||
sp, err = policy.ParseConfig(bytes.NewReader(updateReq.NewPolicy))
|
||||
sp, err = policy.ParseConfigStrict(bytes.NewReader(updateReq.NewPolicy))
|
||||
if err != nil {
|
||||
writeErrorResponseJSON(ctx, w, toAdminAPIErr(ctx, err), r.URL)
|
||||
return
|
||||
@@ -1729,7 +1743,7 @@ func (a adminAPIHandlers) AddCannedPolicy(w http.ResponseWriter, r *http.Request
|
||||
return
|
||||
}
|
||||
|
||||
iamPolicy, err := policy.ParseConfig(bytes.NewReader(iamPolicyBytes))
|
||||
iamPolicy, err := policy.ParseConfigStrict(bytes.NewReader(iamPolicyBytes))
|
||||
if err != nil {
|
||||
writeErrorResponseJSON(ctx, w, toAdminAPIErr(ctx, err), r.URL)
|
||||
return
|
||||
@@ -2981,7 +2995,7 @@ func commonAddServiceAccount(r *http.Request, ldap bool) (context.Context, auth.
|
||||
|
||||
var sp *policy.Policy
|
||||
if len(createReq.Policy) > 0 {
|
||||
sp, err = policy.ParseConfig(bytes.NewReader(createReq.Policy))
|
||||
sp, err = policy.ParseConfigStrict(bytes.NewReader(createReq.Policy))
|
||||
if err != nil {
|
||||
return ctx, auth.Credentials{}, newServiceAccountOpts{}, madmin.AddServiceAccountReq{}, "", toAdminAPIErr(ctx, err)
|
||||
}
|
||||
|
||||
@@ -41,12 +41,53 @@ import (
|
||||
"github.com/minio/minio-go/v7/pkg/signer"
|
||||
"github.com/minio/minio/internal/auth"
|
||||
"github.com/minio/pkg/v3/env"
|
||||
"github.com/minio/pkg/v3/policy"
|
||||
)
|
||||
|
||||
const (
|
||||
testDefaultTimeout = 30 * time.Second
|
||||
)
|
||||
|
||||
func TestSetUserStatusAdminAction(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
status string
|
||||
want policy.AdminAction
|
||||
}{
|
||||
{name: "enable", status: string(madmin.AccountEnabled), want: policy.EnableUserAdminAction},
|
||||
{name: "disable", status: string(madmin.AccountDisabled), want: policy.DisableUserAdminAction},
|
||||
{name: "invalid preserves authenticated default", status: "invalid", want: policy.EnableUserAdminAction},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := setUserStatusAdminAction(tt.status); got != tt.want {
|
||||
t.Fatalf("setUserStatusAdminAction(%q) = %q, want %q", tt.status, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetGroupStatusAdminAction(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
status string
|
||||
want policy.AdminAction
|
||||
}{
|
||||
{name: "enable", status: string(madmin.GroupEnabled), want: policy.EnableGroupAdminAction},
|
||||
{name: "disable", status: string(madmin.GroupDisabled), want: policy.DisableGroupAdminAction},
|
||||
{name: "invalid preserves authenticated default", status: "invalid", want: policy.EnableGroupAdminAction},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := setGroupStatusAdminAction(tt.status); got != tt.want {
|
||||
t.Fatalf("setGroupStatusAdminAction(%q) = %q, want %q", tt.status, got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// API suite container for IAM
|
||||
type TestSuiteIAM struct {
|
||||
TestSuiteCommon
|
||||
@@ -202,8 +243,11 @@ func TestIAMInternalIDPServerSuite(t *testing.T) {
|
||||
|
||||
suite.SetUpSuite(c)
|
||||
suite.TestUserCreate(c)
|
||||
suite.TestUserStatusActionAuthorization(c)
|
||||
suite.TestGroupStatusActionAuthorization(c)
|
||||
suite.TestUserPolicyEscalationBug(c)
|
||||
suite.TestPolicyCreate(c)
|
||||
suite.TestServiceAccountBareARNPolicyRejected(c)
|
||||
suite.TestCannedPolicies(c)
|
||||
suite.TestGroupAddRemove(c)
|
||||
suite.TestServiceAccountOpsByAdmin(c)
|
||||
@@ -312,6 +356,184 @@ func (s *TestSuiteIAM) TestUserCreate(c *check) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TestSuiteIAM) TestUserStatusActionAuthorization(c *check) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), testDefaultTimeout)
|
||||
defer cancel()
|
||||
|
||||
var createdUsers []string
|
||||
var createdPolicies []string
|
||||
defer func() {
|
||||
for _, user := range createdUsers {
|
||||
if err := s.adm.RemoveUser(ctx, user); err != nil {
|
||||
c.Errorf("unable to remove test user %s: %v", user, err)
|
||||
}
|
||||
}
|
||||
for _, policyName := range createdPolicies {
|
||||
if err := s.adm.RemoveCannedPolicy(ctx, policyName); err != nil {
|
||||
c.Errorf("unable to remove test policy %s: %v", policyName, err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
createUser := func() (string, string) {
|
||||
accessKey, secretKey := mustGenerateCredentials(c)
|
||||
if err := s.adm.SetUser(ctx, accessKey, secretKey, madmin.AccountEnabled); err != nil {
|
||||
c.Fatalf("unable to create test user: %v", err)
|
||||
}
|
||||
createdUsers = append(createdUsers, accessKey)
|
||||
return accessKey, secretKey
|
||||
}
|
||||
|
||||
createStatusClient := func(action policy.AdminAction) *madmin.AdminClient {
|
||||
accessKey, secretKey := createUser()
|
||||
policyName := getRandomBucketName()
|
||||
policyBytes := fmt.Appendf(nil, `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Allow",
|
||||
"Action": ["%s"]
|
||||
}]
|
||||
}`, action)
|
||||
if err := s.adm.AddCannedPolicy(ctx, policyName, policyBytes); err != nil {
|
||||
c.Fatalf("unable to add status policy: %v", err)
|
||||
}
|
||||
createdPolicies = append(createdPolicies, policyName)
|
||||
if _, err := s.adm.AttachPolicy(ctx, madmin.PolicyAssociationReq{
|
||||
Policies: []string{policyName},
|
||||
User: accessKey,
|
||||
}); err != nil {
|
||||
c.Fatalf("unable to attach status policy: %v", err)
|
||||
}
|
||||
|
||||
client, err := madmin.NewWithOptions(s.endpoint, &madmin.Options{
|
||||
Creds: credentials.NewStaticV4(accessKey, secretKey, ""),
|
||||
Secure: s.secure,
|
||||
})
|
||||
if err != nil {
|
||||
c.Fatalf("unable to create status admin client: %v", err)
|
||||
}
|
||||
client.SetCustomTransport(s.TestSuiteCommon.client.Transport)
|
||||
return client
|
||||
}
|
||||
|
||||
targetAccessKey, _ := createUser()
|
||||
disableClient := createStatusClient(policy.DisableUserAdminAction)
|
||||
if err := disableClient.SetUserStatus(ctx, targetAccessKey, madmin.AccountDisabled); err != nil {
|
||||
c.Fatalf("DisableUser-only client could not disable a user: %v", err)
|
||||
}
|
||||
if err := disableClient.SetUserStatus(ctx, targetAccessKey, madmin.AccountEnabled); err == nil || madmin.ToErrorResponse(err).Code != "AccessDenied" {
|
||||
c.Fatalf("DisableUser-only client unexpectedly enabled a user: %v", err)
|
||||
}
|
||||
|
||||
enableClient := createStatusClient(policy.EnableUserAdminAction)
|
||||
if err := enableClient.SetUserStatus(ctx, targetAccessKey, madmin.AccountEnabled); err != nil {
|
||||
c.Fatalf("EnableUser-only client could not enable a user: %v", err)
|
||||
}
|
||||
if err := enableClient.SetUserStatus(ctx, targetAccessKey, madmin.AccountDisabled); err == nil || madmin.ToErrorResponse(err).Code != "AccessDenied" {
|
||||
c.Fatalf("EnableUser-only client unexpectedly disabled a user: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TestSuiteIAM) TestGroupStatusActionAuthorization(c *check) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), testDefaultTimeout)
|
||||
defer cancel()
|
||||
|
||||
var createdUsers []string
|
||||
var createdPolicies []string
|
||||
group := getRandomBucketName()
|
||||
var groupCreated bool
|
||||
defer func() {
|
||||
if groupCreated {
|
||||
if err := s.adm.UpdateGroupMembers(ctx, madmin.GroupAddRemove{
|
||||
Group: group,
|
||||
Members: createdUsers[:1],
|
||||
IsRemove: true,
|
||||
}); err != nil {
|
||||
c.Errorf("unable to remove group member: %v", err)
|
||||
}
|
||||
if err := s.adm.UpdateGroupMembers(ctx, madmin.GroupAddRemove{Group: group, IsRemove: true}); err != nil {
|
||||
c.Errorf("unable to remove test group: %v", err)
|
||||
}
|
||||
}
|
||||
for _, user := range createdUsers {
|
||||
if err := s.adm.RemoveUser(ctx, user); err != nil {
|
||||
c.Errorf("unable to remove test user %s: %v", user, err)
|
||||
}
|
||||
}
|
||||
for _, policyName := range createdPolicies {
|
||||
if err := s.adm.RemoveCannedPolicy(ctx, policyName); err != nil {
|
||||
c.Errorf("unable to remove test policy %s: %v", policyName, err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
|
||||
createUser := func() (string, string) {
|
||||
accessKey, secretKey := mustGenerateCredentials(c)
|
||||
if err := s.adm.SetUser(ctx, accessKey, secretKey, madmin.AccountEnabled); err != nil {
|
||||
c.Fatalf("unable to create test user: %v", err)
|
||||
}
|
||||
createdUsers = append(createdUsers, accessKey)
|
||||
return accessKey, secretKey
|
||||
}
|
||||
|
||||
targetAccessKey, _ := createUser()
|
||||
if err := s.adm.UpdateGroupMembers(ctx, madmin.GroupAddRemove{
|
||||
Group: group,
|
||||
Members: []string{targetAccessKey},
|
||||
}); err != nil {
|
||||
c.Fatalf("unable to create test group: %v", err)
|
||||
}
|
||||
groupCreated = true
|
||||
|
||||
createStatusClient := func(action policy.AdminAction) *madmin.AdminClient {
|
||||
accessKey, secretKey := createUser()
|
||||
policyName := getRandomBucketName()
|
||||
policyBytes := fmt.Appendf(nil, `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Allow",
|
||||
"Action": ["%s"]
|
||||
}]
|
||||
}`, action)
|
||||
if err := s.adm.AddCannedPolicy(ctx, policyName, policyBytes); err != nil {
|
||||
c.Fatalf("unable to add group status policy: %v", err)
|
||||
}
|
||||
createdPolicies = append(createdPolicies, policyName)
|
||||
if _, err := s.adm.AttachPolicy(ctx, madmin.PolicyAssociationReq{
|
||||
Policies: []string{policyName},
|
||||
User: accessKey,
|
||||
}); err != nil {
|
||||
c.Fatalf("unable to attach group status policy: %v", err)
|
||||
}
|
||||
|
||||
client, err := madmin.NewWithOptions(s.endpoint, &madmin.Options{
|
||||
Creds: credentials.NewStaticV4(accessKey, secretKey, ""),
|
||||
Secure: s.secure,
|
||||
})
|
||||
if err != nil {
|
||||
c.Fatalf("unable to create group status admin client: %v", err)
|
||||
}
|
||||
client.SetCustomTransport(s.TestSuiteCommon.client.Transport)
|
||||
return client
|
||||
}
|
||||
|
||||
disableClient := createStatusClient(policy.DisableGroupAdminAction)
|
||||
if err := disableClient.SetGroupStatus(ctx, group, madmin.GroupDisabled); err != nil {
|
||||
c.Fatalf("DisableGroup-only client could not disable a group: %v", err)
|
||||
}
|
||||
if err := disableClient.SetGroupStatus(ctx, group, madmin.GroupEnabled); err == nil || madmin.ToErrorResponse(err).Code != "AccessDenied" {
|
||||
c.Fatalf("DisableGroup-only client unexpectedly enabled a group: %v", err)
|
||||
}
|
||||
|
||||
enableClient := createStatusClient(policy.EnableGroupAdminAction)
|
||||
if err := enableClient.SetGroupStatus(ctx, group, madmin.GroupEnabled); err != nil {
|
||||
c.Fatalf("EnableGroup-only client could not enable a group: %v", err)
|
||||
}
|
||||
if err := enableClient.SetGroupStatus(ctx, group, madmin.GroupDisabled); err == nil || madmin.ToErrorResponse(err).Code != "AccessDenied" {
|
||||
c.Fatalf("EnableGroup-only client unexpectedly disabled a group: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TestSuiteIAM) TestUserPolicyEscalationBug(c *check) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), testDefaultTimeout)
|
||||
defer cancel()
|
||||
@@ -600,6 +822,20 @@ func (s *TestSuiteIAM) TestPolicyCreate(c *check) {
|
||||
c.Fatalf("invalid policy creation success")
|
||||
}
|
||||
|
||||
for i, resource := range []string{"arn:aws:s3:::", "*arn:aws:s3:::"} {
|
||||
barePolicyBytes := fmt.Appendf(nil, `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Deny",
|
||||
"Action": ["s3:GetObject"],
|
||||
"Resource": ["%s"]
|
||||
}]
|
||||
}`, resource)
|
||||
if err = s.adm.AddCannedPolicy(ctx, fmt.Sprintf("%s-bare-%d", policy, i), barePolicyBytes); err == nil {
|
||||
c.Fatalf("bare ARN policy creation succeeded for %q", resource)
|
||||
}
|
||||
}
|
||||
|
||||
// 3. Create a user, associate policy and verify access
|
||||
accessKey, secretKey := mustGenerateCredentials(c)
|
||||
err = s.adm.SetUser(ctx, accessKey, secretKey, madmin.AccountEnabled)
|
||||
@@ -653,6 +889,51 @@ func (s *TestSuiteIAM) TestPolicyCreate(c *check) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TestSuiteIAM) TestServiceAccountBareARNPolicyRejected(c *check) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), testDefaultTimeout)
|
||||
defer cancel()
|
||||
|
||||
barePolicy := []byte(`{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetObject"],
|
||||
"NotResource": ["arn:aws:s3:::"]
|
||||
}]
|
||||
}`)
|
||||
if _, err := s.adm.AddServiceAccount(ctx, madmin.AddServiceAccountReq{
|
||||
TargetUser: globalActiveCred.AccessKey,
|
||||
Policy: barePolicy,
|
||||
}); err == nil {
|
||||
c.Fatal("service account creation accepted a bare ARN policy")
|
||||
}
|
||||
|
||||
validPolicy := []byte(`{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetObject"],
|
||||
"Resource": ["arn:aws:s3:::*"]
|
||||
}]
|
||||
}`)
|
||||
credentials, err := s.adm.AddServiceAccount(ctx, madmin.AddServiceAccountReq{
|
||||
TargetUser: globalActiveCred.AccessKey,
|
||||
Policy: validPolicy,
|
||||
})
|
||||
if err != nil {
|
||||
c.Fatalf("service account creation rejected an explicit resource: %v", err)
|
||||
}
|
||||
defer func() {
|
||||
_ = s.adm.DeleteServiceAccount(ctx, credentials.AccessKey)
|
||||
}()
|
||||
|
||||
if err = s.adm.UpdateServiceAccount(ctx, credentials.AccessKey, madmin.UpdateServiceAccountReq{
|
||||
NewPolicy: barePolicy,
|
||||
}); err == nil {
|
||||
c.Fatal("service account update accepted a bare ARN policy")
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TestSuiteIAM) TestCannedPolicies(c *check) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), testDefaultTimeout)
|
||||
defer cancel()
|
||||
|
||||
@@ -2169,6 +2169,10 @@ func toAPIErrorCode(ctx context.Context, err error) (apiErr APIErrorCode) {
|
||||
err = unwrapAll(err)
|
||||
|
||||
switch err {
|
||||
case errCompleteMultipartChecksumMismatch, errCompleteMultipartChecksumTypeMismatch:
|
||||
apiErr = ErrBadDigest
|
||||
case errMissingPartChecksum:
|
||||
apiErr = ErrInvalidRequest
|
||||
case errInvalidArgument:
|
||||
apiErr = ErrAdminInvalidArgument
|
||||
case errNoSuchPolicy:
|
||||
@@ -2465,6 +2469,14 @@ func toAPIError(ctx context.Context, err error) APIError {
|
||||
}
|
||||
|
||||
apiErr := errorCodes.ToAPIErr(toAPIErrorCode(ctx, err))
|
||||
switch {
|
||||
case errors.Is(err, errCompleteMultipartChecksumMismatch):
|
||||
apiErr.Description = strings.TrimPrefix(err.Error(), errCompleteMultipartChecksumMismatch.Error()+": ")
|
||||
case errors.Is(err, errCompleteMultipartChecksumTypeMismatch):
|
||||
apiErr.Description = strings.TrimPrefix(err.Error(), errCompleteMultipartChecksumTypeMismatch.Error()+": ")
|
||||
case errors.Is(err, errMissingPartChecksum):
|
||||
apiErr.Description = strings.TrimPrefix(err.Error(), errMissingPartChecksum.Error()+": ")
|
||||
}
|
||||
switch apiErr.Code {
|
||||
case "NotImplemented":
|
||||
apiErr = APIError{
|
||||
|
||||
@@ -39,6 +39,10 @@ var toAPIErrorTests = []struct {
|
||||
{err: ObjectNameInvalid{}, errCode: ErrInvalidObjectName},
|
||||
{err: InvalidUploadID{}, errCode: ErrNoSuchUpload},
|
||||
{err: InvalidPart{}, errCode: ErrInvalidPart},
|
||||
{err: errCompleteMultipartChecksumMismatch, errCode: ErrBadDigest},
|
||||
{err: errCompleteMultipartChecksumTypeMismatch, errCode: ErrBadDigest},
|
||||
{err: errMissingPartChecksum, errCode: ErrInvalidRequest},
|
||||
{err: hash.ChecksumMismatch{}, errCode: ErrContentChecksumMismatch},
|
||||
{err: InsufficientReadQuorum{}, errCode: ErrSlowDownRead},
|
||||
{err: InsufficientWriteQuorum{}, errCode: ErrSlowDownWrite},
|
||||
{err: InvalidUploadIDKeyCombination{}, errCode: ErrNotImplemented},
|
||||
|
||||
+34
-9
@@ -27,7 +27,6 @@ import (
|
||||
"path"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio/internal/amztime"
|
||||
"github.com/minio/minio/internal/crypto"
|
||||
@@ -380,6 +379,13 @@ type CopyObjectResponse struct {
|
||||
XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ CopyObjectResult" json:"-"`
|
||||
LastModified string // time string of format "2006-01-02T15:04:05.000Z"
|
||||
ETag string // md5sum of the copied object.
|
||||
|
||||
ChecksumCRC32 string `xml:",omitempty"`
|
||||
ChecksumCRC32C string `xml:",omitempty"`
|
||||
ChecksumSHA1 string `xml:",omitempty"`
|
||||
ChecksumSHA256 string `xml:",omitempty"`
|
||||
ChecksumCRC64NVME string `xml:",omitempty"`
|
||||
ChecksumType string `xml:",omitempty"`
|
||||
}
|
||||
|
||||
// CopyObjectPartResponse container returns ETag and LastModified of the successfully copied object
|
||||
@@ -387,6 +393,12 @@ type CopyObjectPartResponse struct {
|
||||
XMLName xml.Name `xml:"http://s3.amazonaws.com/doc/2006-03-01/ CopyPartResult" json:"-"`
|
||||
LastModified string // time string of format "2006-01-02T15:04:05.000Z"
|
||||
ETag string // md5sum of the copied object part.
|
||||
|
||||
ChecksumCRC32 string `xml:",omitempty"`
|
||||
ChecksumCRC32C string `xml:",omitempty"`
|
||||
ChecksumSHA1 string `xml:",omitempty"`
|
||||
ChecksumSHA256 string `xml:",omitempty"`
|
||||
ChecksumCRC64NVME string `xml:",omitempty"`
|
||||
}
|
||||
|
||||
// Initiator inherit from Owner struct, fields are same
|
||||
@@ -416,6 +428,7 @@ type CompleteMultipartUploadResponse struct {
|
||||
Key string
|
||||
ETag string
|
||||
|
||||
ChecksumType string `xml:"ChecksumType,omitempty"`
|
||||
ChecksumCRC32 string `xml:"ChecksumCRC32,omitempty"`
|
||||
ChecksumCRC32C string `xml:"ChecksumCRC32C,omitempty"`
|
||||
ChecksumSHA1 string `xml:"ChecksumSHA1,omitempty"`
|
||||
@@ -763,19 +776,30 @@ func generateListObjectsV2Response(ctx context.Context, bucket, prefix, token, n
|
||||
|
||||
type metaCheckFn = func(name string, action policy.Action) (s3Err APIErrorCode)
|
||||
|
||||
// generates CopyObjectResponse from etag and lastModified time.
|
||||
func generateCopyObjectResponse(etag string, lastModified time.Time) CopyObjectResponse {
|
||||
// generates CopyObjectResponse from the committed object information.
|
||||
func generateCopyObjectResponse(oi ObjectInfo, cs map[string]string) CopyObjectResponse {
|
||||
return CopyObjectResponse{
|
||||
ETag: "\"" + etag + "\"",
|
||||
LastModified: amztime.ISO8601Format(lastModified.UTC()),
|
||||
ETag: "\"" + oi.ETag + "\"",
|
||||
LastModified: amztime.ISO8601Format(oi.ModTime.UTC()),
|
||||
ChecksumCRC32: cs[hash.ChecksumCRC32.String()],
|
||||
ChecksumCRC32C: cs[hash.ChecksumCRC32C.String()],
|
||||
ChecksumSHA1: cs[hash.ChecksumSHA1.String()],
|
||||
ChecksumSHA256: cs[hash.ChecksumSHA256.String()],
|
||||
ChecksumCRC64NVME: cs[hash.ChecksumCRC64NVME.String()],
|
||||
ChecksumType: cs[xhttp.AmzChecksumType],
|
||||
}
|
||||
}
|
||||
|
||||
// generates CopyObjectPartResponse from etag and lastModified time.
|
||||
func generateCopyObjectPartResponse(etag string, lastModified time.Time) CopyObjectPartResponse {
|
||||
// generates CopyObjectPartResponse from the uploaded part information.
|
||||
func generateCopyObjectPartResponse(partInfo PartInfo) CopyObjectPartResponse {
|
||||
return CopyObjectPartResponse{
|
||||
ETag: "\"" + etag + "\"",
|
||||
LastModified: amztime.ISO8601Format(lastModified.UTC()),
|
||||
ETag: "\"" + partInfo.ETag + "\"",
|
||||
LastModified: amztime.ISO8601Format(partInfo.LastModified.UTC()),
|
||||
ChecksumCRC32: partInfo.ChecksumCRC32,
|
||||
ChecksumCRC32C: partInfo.ChecksumCRC32C,
|
||||
ChecksumSHA1: partInfo.ChecksumSHA1,
|
||||
ChecksumSHA256: partInfo.ChecksumSHA256,
|
||||
ChecksumCRC64NVME: partInfo.ChecksumCRC64NVME,
|
||||
}
|
||||
}
|
||||
|
||||
@@ -797,6 +821,7 @@ func generateCompleteMultipartUploadResponse(bucket, key, location string, oi Ob
|
||||
Key: key,
|
||||
// AWS S3 quotes the ETag in XML, make sure we are compatible here.
|
||||
ETag: "\"" + oi.ETag + "\"",
|
||||
ChecksumType: cs[xhttp.AmzChecksumType],
|
||||
ChecksumSHA1: cs[hash.ChecksumSHA1.String()],
|
||||
ChecksumSHA256: cs[hash.ChecksumSHA256.String()],
|
||||
ChecksumCRC32: cs[hash.ChecksumCRC32.String()],
|
||||
|
||||
+125
-6
@@ -18,16 +18,23 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
|
||||
consoleapi "github.com/minio/console/api"
|
||||
bktcors "github.com/minio/minio/internal/bucket/cors"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
"github.com/minio/mux"
|
||||
"github.com/minio/pkg/v3/wildcard"
|
||||
"github.com/rs/cors"
|
||||
)
|
||||
|
||||
type bucketCorsAppliedKey struct{}
|
||||
|
||||
func newHTTPServerFn() *xhttp.Server {
|
||||
globalObjLayerMutex.RLock()
|
||||
defer globalObjLayerMutex.RUnlock()
|
||||
@@ -111,11 +118,6 @@ var rejectedBucketAPIs = []rejectedAPI{
|
||||
methods: []string{http.MethodGet, http.MethodPut, http.MethodDelete},
|
||||
queries: []string{"inventory", ""},
|
||||
},
|
||||
{
|
||||
api: "cors",
|
||||
methods: []string{http.MethodPut, http.MethodDelete},
|
||||
queries: []string{"cors", ""},
|
||||
},
|
||||
{
|
||||
api: "metrics",
|
||||
methods: []string{http.MethodGet, http.MethodPut, http.MethodDelete},
|
||||
@@ -648,6 +650,94 @@ func registerAPIRouter(router *mux.Router) {
|
||||
apiRouter.MethodNotAllowedHandler = collectAPIStats("methodnotallowed", httpTraceAll(methodNotAllowedHandler("S3")))
|
||||
}
|
||||
|
||||
// applyBucketCors applies a bucket's CORS configuration to the request.
|
||||
// For an OPTIONS preflight it writes the full CORS response and returns true
|
||||
// (request is complete). For an actual request it adds the applicable
|
||||
// Access-Control-* response headers and returns false so the request
|
||||
// continues down the handler chain. If no rule matches a preflight it writes
|
||||
// 403 and returns true. A matched actual request is marked in its context so
|
||||
// inner legacy middleware does not rewrite an explicitly allowed null origin.
|
||||
func applyBucketCors(w http.ResponseWriter, r *http.Request, cfg *bktcors.Config) (handled bool) {
|
||||
origin := r.Header.Get("Origin")
|
||||
if origin == "" {
|
||||
return false // not a CORS request
|
||||
}
|
||||
h := w.Header()
|
||||
h.Add("Vary", "Origin")
|
||||
|
||||
isPreflight := r.Method == http.MethodOptions &&
|
||||
r.Header.Get("Access-Control-Request-Method") != ""
|
||||
|
||||
if isPreflight {
|
||||
method := r.Header.Get("Access-Control-Request-Method")
|
||||
reqHeaders := splitAndTrim(r.Header.Get("Access-Control-Request-Headers"))
|
||||
// A preflight response depends on all three request headers that
|
||||
// determine the outcome, including when the request is rejected.
|
||||
h.Add("Vary", "Access-Control-Request-Method")
|
||||
h.Add("Vary", "Access-Control-Request-Headers")
|
||||
rule, allowedOrigin, allowedHeaders, maxAgeSeconds, ok := cfg.MatchPreflight(origin, method, reqHeaders)
|
||||
if !ok {
|
||||
writeResponse(w, http.StatusForbidden, nil, mimeNone)
|
||||
return true
|
||||
}
|
||||
setBucketCorsOriginHeaders(h, allowedOrigin, origin)
|
||||
h.Set("Access-Control-Allow-Methods", strings.Join(rule.AllowedMethods, ", "))
|
||||
if len(allowedHeaders) > 0 {
|
||||
h.Set("Access-Control-Allow-Headers", strings.Join(allowedHeaders, ", "))
|
||||
}
|
||||
if len(rule.ExposeHeaders) > 0 {
|
||||
h.Set("Access-Control-Expose-Headers", strings.Join(rule.ExposeHeaders, ", "))
|
||||
}
|
||||
if maxAgeSeconds != nil {
|
||||
h.Set("Access-Control-Max-Age", strconv.Itoa(*maxAgeSeconds))
|
||||
}
|
||||
writeResponse(w, http.StatusOK, nil, mimeNone)
|
||||
return true
|
||||
}
|
||||
|
||||
// Actual request: attach headers if the origin+method match.
|
||||
rule, allowedOrigin, ok := cfg.MatchRule(origin, r.Method)
|
||||
if !ok {
|
||||
return false // no matching rule → no CORS headers, continue normally
|
||||
}
|
||||
*r = *r.WithContext(context.WithValue(r.Context(), bucketCorsAppliedKey{}, struct{}{}))
|
||||
setBucketCorsOriginHeaders(h, allowedOrigin, origin)
|
||||
if len(rule.ExposeHeaders) > 0 {
|
||||
h.Set("Access-Control-Expose-Headers", strings.Join(rule.ExposeHeaders, ", "))
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func bucketCorsWasApplied(r *http.Request) bool {
|
||||
_, ok := r.Context().Value(bucketCorsAppliedKey{}).(struct{})
|
||||
return ok
|
||||
}
|
||||
|
||||
func setBucketCorsOriginHeaders(h http.Header, allowedOrigin, requestOrigin string) {
|
||||
if allowedOrigin == "*" {
|
||||
h.Set("Access-Control-Allow-Origin", "*")
|
||||
h.Del("Access-Control-Allow-Credentials")
|
||||
return
|
||||
}
|
||||
h.Set("Access-Control-Allow-Origin", requestOrigin)
|
||||
h.Set("Access-Control-Allow-Credentials", "true")
|
||||
}
|
||||
|
||||
// splitAndTrim splits a comma-separated header list into trimmed, non-empty values.
|
||||
func splitAndTrim(s string) []string {
|
||||
if s == "" {
|
||||
return nil
|
||||
}
|
||||
parts := strings.Split(s, ",")
|
||||
out := parts[:0]
|
||||
for _, p := range parts {
|
||||
if p = strings.TrimSpace(p); p != "" {
|
||||
out = append(out, p)
|
||||
}
|
||||
}
|
||||
return out
|
||||
}
|
||||
|
||||
// corsHandler handler for CORS (Cross Origin Resource Sharing)
|
||||
func corsHandler(handler http.Handler) http.Handler {
|
||||
commonS3Headers := []string{
|
||||
@@ -693,5 +783,34 @@ func corsHandler(handler http.Handler) http.Handler {
|
||||
ExposedHeaders: commonS3Headers,
|
||||
AllowCredentials: true,
|
||||
}
|
||||
return cors.New(opts).Handler(handler)
|
||||
globalCors := cors.New(opts).Handler(handler)
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Header.Get("Origin") != "" {
|
||||
if bucket, _ := request2BucketObjectName(r); bucket != "" && globalBucketMetadataSys != nil {
|
||||
// Resident-only lookup: this runs pre-auth for every
|
||||
// Origin-bearing request using a client-supplied path segment as
|
||||
// the bucket name. It must never load or cache metadata for
|
||||
// arbitrary names (see GetResidentCorsConfig). GetResidentCorsConfig
|
||||
// is the single decision point: it returns errInvalidArgument for
|
||||
// the internal .minio.sys namespace (fail closed), a config for a
|
||||
// resident bucket, errBucketMetadataNotInitialized for a real but
|
||||
// unloaded bucket (fail closed), and errConfigNotFound otherwise
|
||||
// (fall back to the global policy below).
|
||||
cfg, _, err := globalBucketMetadataSys.GetResidentCorsConfig(bucket)
|
||||
if err == nil && cfg != nil {
|
||||
if applyBucketCors(w, r, cfg) {
|
||||
return
|
||||
}
|
||||
handler.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
if err != nil && !errors.Is(err, errConfigNotFound) {
|
||||
internalLogOnceIf(r.Context(), err, "bucket-cors-metadata")
|
||||
handler.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
globalCors.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
|
||||
+65
-30
@@ -363,17 +363,6 @@ func checkRequestAuthTypeWithRequestTags(ctx context.Context, r *http.Request, a
|
||||
return authorizeRequestWithTags(ctx, r, action, "", requestTags)
|
||||
}
|
||||
|
||||
// checkRequestAuthTypeWithVID is similar to checkRequestAuthType
|
||||
// passes versionID additionally.
|
||||
func checkRequestAuthTypeWithVID(ctx context.Context, r *http.Request, action policy.Action, bucketName, objectName, versionID string) (s3Err APIErrorCode) {
|
||||
logger.GetReqInfo(ctx).BucketName = bucketName
|
||||
logger.GetReqInfo(ctx).ObjectName = objectName
|
||||
logger.GetReqInfo(ctx).VersionID = versionID
|
||||
|
||||
_, _, s3Err = checkRequestAuthTypeCredential(ctx, r, action)
|
||||
return s3Err
|
||||
}
|
||||
|
||||
func authenticateRequest(ctx context.Context, r *http.Request, action policy.Action) (s3Err APIErrorCode) {
|
||||
if logger.GetReqInfo(ctx) == nil {
|
||||
bugLogIf(ctx, errors.New("unexpected context.Context does not have a logger.ReqInfo"), logger.ErrorKind)
|
||||
@@ -439,6 +428,23 @@ func authorizeRequest(ctx context.Context, r *http.Request, action policy.Action
|
||||
return authorizeRequestWithExistingTags(ctx, r, action, "")
|
||||
}
|
||||
|
||||
func deleteObjectAction(versionID string) policy.Action {
|
||||
if versionID != "" {
|
||||
return policy.DeleteObjectVersionAction
|
||||
}
|
||||
return policy.DeleteObjectAction
|
||||
}
|
||||
|
||||
func actionUsesObjectVersion(action policy.Action) bool {
|
||||
switch action {
|
||||
case policy.DeleteObjectAction, policy.DeleteObjectVersionAction,
|
||||
policy.ReplicateDeleteAction, policy.BypassGovernanceRetentionAction:
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func authorizeRequestWithExistingTags(ctx context.Context, r *http.Request, action policy.Action, existingTags string) (s3Err APIErrorCode) {
|
||||
return authorizeRequestWithTags(ctx, r, action, existingTags, nil)
|
||||
}
|
||||
@@ -457,7 +463,7 @@ func authorizeRequestWithTags(ctx context.Context, r *http.Request, action polic
|
||||
versionID := reqInfo.VersionID
|
||||
conditionValuesForAuth := func(locationConstraint string, credentials auth.Credentials) map[string][]string {
|
||||
values := getConditionValuesWithTags(r, locationConstraint, credentials, existingTags, requestTags)
|
||||
if action == policy.DeleteObjectAction {
|
||||
if actionUsesObjectVersion(action) {
|
||||
// DeleteObjects carries the effective version ID in each XML object,
|
||||
// not in the request query. Keep authorization scoped to that entry.
|
||||
if versionID == "" {
|
||||
@@ -503,21 +509,6 @@ func authorizeRequestWithTags(ctx context.Context, r *http.Request, action polic
|
||||
|
||||
return ErrAccessDenied
|
||||
}
|
||||
if action == policy.DeleteObjectAction && versionID != "" {
|
||||
if !globalIAMSys.IsAllowed(policy.Args{
|
||||
AccountName: cred.AccessKey,
|
||||
Groups: cred.Groups,
|
||||
Action: policy.Action(policy.DeleteObjectVersionAction),
|
||||
BucketName: bucket,
|
||||
ConditionValues: conditionValuesForAuth("", cred),
|
||||
ObjectName: object,
|
||||
IsOwner: owner,
|
||||
Claims: cred.Claims,
|
||||
DenyOnly: true,
|
||||
}) { // Request is not allowed if Deny action on DeleteObjectVersionAction
|
||||
return ErrAccessDenied
|
||||
}
|
||||
}
|
||||
if globalIAMSys.IsAllowed(policy.Args{
|
||||
AccountName: cred.AccessKey,
|
||||
Groups: cred.Groups,
|
||||
@@ -553,6 +544,40 @@ func authorizeRequestWithTags(ctx context.Context, r *http.Request, action polic
|
||||
return ErrAccessDenied
|
||||
}
|
||||
|
||||
// authorizeReplicationDelete preserves the established target-credential
|
||||
// contract for trusted replication: DeleteObject and ReplicateDelete must be
|
||||
// allowed, while an explicit DeleteObjectVersion deny still blocks a named
|
||||
// version. Ordinary S3 requests never use this compatibility path.
|
||||
func authorizeReplicationDelete(ctx context.Context, r *http.Request) APIErrorCode {
|
||||
if s3Err := authorizeRequest(ctx, r, policy.DeleteObjectAction); s3Err != ErrNone {
|
||||
return s3Err
|
||||
}
|
||||
reqInfo := logger.GetReqInfo(ctx)
|
||||
if reqInfo == nil {
|
||||
return ErrAccessDenied
|
||||
}
|
||||
if reqInfo.VersionID == "" {
|
||||
return ErrNone
|
||||
}
|
||||
cred := reqInfo.Cred
|
||||
values := getConditionValuesWithTags(r, "", cred, "", nil)
|
||||
values["versionid"] = []string{reqInfo.VersionID}
|
||||
if !globalIAMSys.IsAllowed(policy.Args{
|
||||
AccountName: cred.AccessKey,
|
||||
Groups: cred.Groups,
|
||||
Action: policy.DeleteObjectVersionAction,
|
||||
BucketName: reqInfo.BucketName,
|
||||
ConditionValues: values,
|
||||
ObjectName: reqInfo.ObjectName,
|
||||
IsOwner: reqInfo.Owner,
|
||||
Claims: cred.Claims,
|
||||
DenyOnly: true,
|
||||
}) {
|
||||
return ErrAccessDenied
|
||||
}
|
||||
return ErrNone
|
||||
}
|
||||
|
||||
// Check request auth type verifies the incoming http request
|
||||
// - validates the request signature
|
||||
// - validates the policy action if anonymous tests bucket policies if any,
|
||||
@@ -786,10 +811,20 @@ func isPutActionAllowedWithRequestTags(ctx context.Context, atype authType, buck
|
||||
return s3Err
|
||||
}
|
||||
|
||||
logger.GetReqInfo(ctx).Cred = cred
|
||||
logger.GetReqInfo(ctx).Owner = owner
|
||||
logger.GetReqInfo(ctx).Region = region
|
||||
reqInfo := logger.GetReqInfo(ctx)
|
||||
if reqInfo == nil {
|
||||
return ErrAccessDenied
|
||||
}
|
||||
reqInfo.Lock()
|
||||
reqInfo.Cred = cred
|
||||
reqInfo.Owner = owner
|
||||
reqInfo.Region = region
|
||||
reqInfo.Unlock()
|
||||
|
||||
return isPutActionAllowedWithCred(bucketName, objectName, r, action, requestTags, cred, owner)
|
||||
}
|
||||
|
||||
func isPutActionAllowedWithCred(bucketName, objectName string, r *http.Request, action policy.Action, requestTags *string, cred auth.Credentials, owner bool) APIErrorCode {
|
||||
// Do not check for PutObjectRetentionAction permission,
|
||||
// if mode and retain until date are not set.
|
||||
// Can happen when bucket has default lock config set
|
||||
|
||||
@@ -0,0 +1,235 @@
|
||||
// Copyright (c) 2015-2021 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/binary"
|
||||
"hash/crc32"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/minio/minio/internal/auth"
|
||||
)
|
||||
|
||||
func TestPutBucketCorsWireValidation(t *testing.T) {
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testPutBucketCorsWireValidation,
|
||||
endpoints: []string{"PutBucketCors"},
|
||||
})
|
||||
}
|
||||
|
||||
func testPutBucketCorsWireValidation(_ ObjectLayer, _ string, bucketName string, apiRouter http.Handler,
|
||||
creds auth.Credentials, t *testing.T,
|
||||
) {
|
||||
valid := `<CORSConfiguration><CORSRule><AllowedOrigin>*</AllowedOrigin><AllowedMethod>GET</AllowedMethod></CORSRule></CORSConfiguration>`
|
||||
rule := `<CORSRule><AllowedOrigin>*</AllowedOrigin><AllowedMethod>GET</AllowedMethod></CORSRule>`
|
||||
tests := []struct {
|
||||
name string
|
||||
body string
|
||||
want int
|
||||
wantCode string
|
||||
}{
|
||||
{
|
||||
name: "second XML root",
|
||||
body: valid + `<Extra/>`,
|
||||
want: http.StatusBadRequest,
|
||||
wantCode: "MalformedXML",
|
||||
},
|
||||
{
|
||||
name: "255 Unicode character ID",
|
||||
body: `<CORSConfiguration><CORSRule><ID>` + strings.Repeat("界", 255) + `</ID><AllowedOrigin>*</AllowedOrigin><AllowedMethod>GET</AllowedMethod></CORSRule></CORSConfiguration>`,
|
||||
want: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "256 Unicode character ID",
|
||||
body: `<CORSConfiguration><CORSRule><ID>` + strings.Repeat("界", 256) + `</ID><AllowedOrigin>*</AllowedOrigin><AllowedMethod>GET</AllowedMethod></CORSRule></CORSConfiguration>`,
|
||||
want: http.StatusBadRequest,
|
||||
wantCode: "MalformedXML",
|
||||
},
|
||||
{
|
||||
name: "lowercase method",
|
||||
body: `<CORSConfiguration><CORSRule><AllowedOrigin>*</AllowedOrigin><AllowedMethod>get</AllowedMethod></CORSRule></CORSConfiguration>`,
|
||||
want: http.StatusBadRequest,
|
||||
wantCode: "MalformedXML",
|
||||
},
|
||||
{
|
||||
name: "empty origin",
|
||||
body: `<CORSConfiguration><CORSRule><AllowedOrigin/><AllowedMethod>GET</AllowedMethod></CORSRule></CORSConfiguration>`,
|
||||
want: http.StatusBadRequest,
|
||||
wantCode: "MalformedXML",
|
||||
},
|
||||
{
|
||||
name: "question mark origin wildcard",
|
||||
body: `<CORSConfiguration><CORSRule><AllowedOrigin>https://?.example.com</AllowedOrigin><AllowedMethod>GET</AllowedMethod></CORSRule></CORSConfiguration>`,
|
||||
want: http.StatusBadRequest,
|
||||
wantCode: "MalformedXML",
|
||||
},
|
||||
{
|
||||
name: "question mark header wildcard",
|
||||
body: `<CORSConfiguration><CORSRule><AllowedOrigin>*</AllowedOrigin><AllowedMethod>GET</AllowedMethod><AllowedHeader>x-amz-?</AllowedHeader></CORSRule></CORSConfiguration>`,
|
||||
want: http.StatusBadRequest,
|
||||
wantCode: "MalformedXML",
|
||||
},
|
||||
{
|
||||
name: "unknown element",
|
||||
body: `<CORSConfiguration><CORSRule><AllowedOrigin>*</AllowedOrigin><AllowedMethod>GET</AllowedMethod><Unknown/></CORSRule></CORSConfiguration>`,
|
||||
want: http.StatusBadRequest,
|
||||
wantCode: "MalformedXML",
|
||||
},
|
||||
{
|
||||
name: "empty max age",
|
||||
body: `<CORSConfiguration><CORSRule><AllowedOrigin>*</AllowedOrigin><AllowedMethod>GET</AllowedMethod><MaxAgeSeconds/></CORSRule></CORSConfiguration>`,
|
||||
want: http.StatusBadRequest,
|
||||
wantCode: "MalformedXML",
|
||||
},
|
||||
{
|
||||
name: "zero max age",
|
||||
body: `<CORSConfiguration><CORSRule><AllowedOrigin>*</AllowedOrigin><AllowedMethod>GET</AllowedMethod><MaxAgeSeconds>0</MaxAgeSeconds></CORSRule></CORSConfiguration>`,
|
||||
want: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "max age int32 overflow",
|
||||
body: `<CORSConfiguration><CORSRule><AllowedOrigin>*</AllowedOrigin><AllowedMethod>GET</AllowedMethod><MaxAgeSeconds>2147483648</MaxAgeSeconds></CORSRule></CORSConfiguration>`,
|
||||
want: http.StatusBadRequest,
|
||||
wantCode: "MalformedXML",
|
||||
},
|
||||
{
|
||||
name: "100 rules",
|
||||
body: `<CORSConfiguration>` + strings.Repeat(rule, 100) + `</CORSConfiguration>`,
|
||||
want: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "101 rules",
|
||||
body: `<CORSConfiguration>` + strings.Repeat(rule, 101) + `</CORSConfiguration>`,
|
||||
want: http.StatusBadRequest,
|
||||
wantCode: "MalformedXML",
|
||||
},
|
||||
{
|
||||
name: "exactly 64 KiB",
|
||||
body: sizedCORSConfig(maxBucketCorsSize),
|
||||
want: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "over 64 KiB",
|
||||
body: sizedCORSConfig(maxBucketCorsSize + 1),
|
||||
want: http.StatusBadRequest,
|
||||
wantCode: "EntityTooLarge",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
req, err := newTestSignedRequestV4(http.MethodPut, getBucketCorsURL("", bucketName),
|
||||
int64(len(tt.body)), bytes.NewReader([]byte(tt.body)), creds.AccessKey, creds.SecretKey, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != tt.want {
|
||||
t.Fatalf("expected status %d, got %d: %s", tt.want, rec.Code, rec.Body.String())
|
||||
}
|
||||
if tt.wantCode != "" && !bytes.Contains(rec.Body.Bytes(), []byte("<Code>"+tt.wantCode+"</Code>")) {
|
||||
t.Fatalf("expected error code %s, got: %s", tt.wantCode, rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func sizedCORSConfig(size int) string {
|
||||
prefix := `<CORSConfiguration><CORSRule><AllowedOrigin>*</AllowedOrigin><AllowedMethod>GET</AllowedMethod>`
|
||||
suffix := `</CORSRule></CORSConfiguration>`
|
||||
return prefix + strings.Repeat(" ", size-len(prefix)-len(suffix)) + suffix
|
||||
}
|
||||
|
||||
func TestPutBucketCorsChecksumValidation(t *testing.T) {
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testPutBucketCorsChecksumValidation,
|
||||
endpoints: []string{"PutBucketCors"},
|
||||
})
|
||||
}
|
||||
|
||||
func testPutBucketCorsChecksumValidation(_ ObjectLayer, _ string, bucketName string, apiRouter http.Handler,
|
||||
creds auth.Credentials, t *testing.T,
|
||||
) {
|
||||
body := []byte(`<CORSConfiguration><CORSRule><AllowedOrigin>*</AllowedOrigin><AllowedMethod>GET</AllowedMethod></CORSRule></CORSConfiguration>`)
|
||||
tests := []struct {
|
||||
name string
|
||||
configure func(*http.Request)
|
||||
want int
|
||||
wantCode string
|
||||
}{
|
||||
{
|
||||
name: "missing checksum",
|
||||
configure: func(req *http.Request) {
|
||||
req.Header.Del("Content-Md5")
|
||||
},
|
||||
want: http.StatusBadRequest,
|
||||
wantCode: "MissingContentMD5",
|
||||
},
|
||||
{
|
||||
name: "bad content md5",
|
||||
configure: func(req *http.Request) {
|
||||
req.Header.Set("Content-Md5", getMD5HashBase64([]byte("different body")))
|
||||
},
|
||||
want: http.StatusBadRequest,
|
||||
wantCode: "BadDigest",
|
||||
},
|
||||
{
|
||||
name: "valid sdk crc32",
|
||||
configure: func(req *http.Request) {
|
||||
req.Header.Del("Content-Md5")
|
||||
req.Header.Set("X-Amz-Sdk-Checksum-Algorithm", "CRC32")
|
||||
req.Header.Set("X-Amz-Checksum-Crc32", corsCRC32Base64(body))
|
||||
},
|
||||
want: http.StatusOK,
|
||||
},
|
||||
{
|
||||
name: "bad sdk crc32",
|
||||
configure: func(req *http.Request) {
|
||||
req.Header.Del("Content-Md5")
|
||||
req.Header.Set("X-Amz-Sdk-Checksum-Algorithm", "CRC32")
|
||||
req.Header.Set("X-Amz-Checksum-Crc32", corsCRC32Base64([]byte("different body")))
|
||||
},
|
||||
want: http.StatusBadRequest,
|
||||
wantCode: "BadDigest",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
req, err := newTestRequest(http.MethodPut, getBucketCorsURL("", bucketName), int64(len(body)), bytes.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tt.configure(req)
|
||||
if err = signRequestV4(req, creds.AccessKey, creds.SecretKey); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != tt.want || (tt.wantCode != "" && !bytes.Contains(rec.Body.Bytes(), []byte("<Code>"+tt.wantCode+"</Code>"))) {
|
||||
t.Fatalf("expected status %d and code %s, got %d: %s", tt.want, tt.wantCode, rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func corsCRC32Base64(data []byte) string {
|
||||
var checksum [4]byte
|
||||
binary.BigEndian.PutUint32(checksum[:], crc32.ChecksumIEEE(data))
|
||||
return base64.StdEncoding.EncodeToString(checksum[:])
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
// Copyright (c) 2015-2021 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
|
||||
humanize "github.com/dustin/go-humanize"
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/minio/internal/bucket/cors"
|
||||
hashpkg "github.com/minio/minio/internal/hash"
|
||||
"github.com/minio/minio/internal/logger"
|
||||
"github.com/minio/mux"
|
||||
"github.com/minio/pkg/v3/policy"
|
||||
)
|
||||
|
||||
// maxBucketCorsSize is the maximum allowed size of a CORS configuration document.
|
||||
const maxBucketCorsSize = 64 * humanize.KiByte
|
||||
|
||||
// PutBucketCorsHandler - PUT bucket cors.
|
||||
func (api objectAPIHandlers) PutBucketCorsHandler(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := newContext(r, w, "PutBucketCors")
|
||||
|
||||
defer logger.AuditLog(ctx, w, r, mustGetClaimsFromToken(r))
|
||||
|
||||
objAPI := api.ObjectAPI()
|
||||
if objAPI == nil {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrServerNotInitialized), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
vars := mux.Vars(r)
|
||||
bucket := vars["bucket"]
|
||||
|
||||
if s3Error := checkRequestAuthType(ctx, r, policy.PutBucketCorsAction, bucket, ""); s3Error != ErrNone {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Error), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := objAPI.GetBucketInfo(ctx, bucket, BucketOptions{}); err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
if r.ContentLength <= 0 {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrMissingContentLength), r.URL)
|
||||
return
|
||||
}
|
||||
if r.ContentLength > maxBucketCorsSize {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrEntityTooLarge), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
// PutBucketCors requires a Content-Md5 or a supported full-header
|
||||
// checksum. validateLengthAndChecksum wraps r.Body so the supplied digest
|
||||
// is verified as the body is read below.
|
||||
if !validateLengthAndChecksum(r) {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrMissingContentMD5), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
corsBytes, err := io.ReadAll(r.Body)
|
||||
if err != nil {
|
||||
if errors.Is(err, hashpkg.ErrInvalidChecksum) {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrBadDigest), r.URL)
|
||||
return
|
||||
}
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
corsCfg, err := cors.ParseBucketCorsConfig(bytes.NewReader(corsBytes))
|
||||
if err != nil {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrMalformedXML), r.URL)
|
||||
return
|
||||
}
|
||||
if err := corsCfg.Validate(); err != nil {
|
||||
writeErrorResponse(ctx, w, APIError{
|
||||
Code: "MalformedXML",
|
||||
HTTPStatusCode: http.StatusBadRequest,
|
||||
Description: err.Error(),
|
||||
}, r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
updatedAt, err := updateLocalBucketCORSMetadata(ctx, objAPI, bucket, corsBytes)
|
||||
if err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
// Call site replication hook.
|
||||
//
|
||||
// We encode the xml bytes as base64 to ensure there are no encoding
|
||||
// errors.
|
||||
cfgStr := base64.StdEncoding.EncodeToString(corsBytes)
|
||||
replLogIf(ctx, globalSiteReplicationSys.BucketMetaHook(ctx, madmin.SRBucketMeta{
|
||||
Type: madmin.SRBucketMetaTypeCorsConfig,
|
||||
Bucket: bucket,
|
||||
Cors: &cfgStr,
|
||||
UpdatedAt: updatedAt,
|
||||
}))
|
||||
|
||||
writeSuccessResponseHeadersOnly(w)
|
||||
}
|
||||
|
||||
// GetBucketCorsHandler - GET bucket cors.
|
||||
func (api objectAPIHandlers) GetBucketCorsHandler(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := newContext(r, w, "GetBucketCors")
|
||||
|
||||
defer logger.AuditLog(ctx, w, r, mustGetClaimsFromToken(r))
|
||||
|
||||
objAPI := api.ObjectAPI()
|
||||
if objAPI == nil {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrServerNotInitialized), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
vars := mux.Vars(r)
|
||||
bucket := vars["bucket"]
|
||||
|
||||
if s3Error := checkRequestAuthType(ctx, r, policy.GetBucketCorsAction, bucket, ""); s3Error != ErrNone {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Error), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := objAPI.GetBucketInfo(ctx, bucket, BucketOptions{}); err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
configData, _, err := globalBucketMetadataSys.GetCorsConfigXML(bucket)
|
||||
if err != nil {
|
||||
if errors.Is(err, errConfigNotFound) {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrNoSuchCORSConfiguration), r.URL)
|
||||
return
|
||||
}
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
writeSuccessResponseXML(w, configData)
|
||||
}
|
||||
|
||||
// DeleteBucketCorsHandler - DELETE bucket cors.
|
||||
func (api objectAPIHandlers) DeleteBucketCorsHandler(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := newContext(r, w, "DeleteBucketCors")
|
||||
|
||||
defer logger.AuditLog(ctx, w, r, mustGetClaimsFromToken(r))
|
||||
|
||||
objAPI := api.ObjectAPI()
|
||||
if objAPI == nil {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrServerNotInitialized), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
vars := mux.Vars(r)
|
||||
bucket := vars["bucket"]
|
||||
|
||||
if s3Error := checkRequestAuthType(ctx, r, policy.DeleteBucketCorsAction, bucket, ""); s3Error != ErrNone {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Error), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
if _, err := objAPI.GetBucketInfo(ctx, bucket, BucketOptions{}); err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
updatedAt, err := updateLocalBucketCORSMetadata(ctx, objAPI, bucket, nil)
|
||||
if err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
replLogIf(ctx, globalSiteReplicationSys.BucketMetaHook(ctx, madmin.SRBucketMeta{
|
||||
Type: madmin.SRBucketMetaTypeCorsConfig,
|
||||
Bucket: bucket,
|
||||
Cors: nil,
|
||||
UpdatedAt: updatedAt,
|
||||
}))
|
||||
|
||||
writeSuccessNoContent(w)
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
// Copyright (c) 2015-2021 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/minio/minio/internal/auth"
|
||||
)
|
||||
|
||||
const testCORSDoc = `<CORSConfiguration><CORSRule><AllowedOrigin>http://example.com</AllowedOrigin><AllowedMethod>GET</AllowedMethod><AllowedMethod>PUT</AllowedMethod><ExposeHeader>ETag</ExposeHeader><MaxAgeSeconds>3000</MaxAgeSeconds></CORSRule></CORSConfiguration>`
|
||||
|
||||
func TestBucketCorsHandlers(t *testing.T) {
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{t: t, objAPITest: testBucketCorsHandlers, endpoints: []string{"PutBucketCors", "GetBucketCors", "DeleteBucketCors"}})
|
||||
}
|
||||
|
||||
func testBucketCorsHandlers(obj ObjectLayer, instanceType, bucketName string, apiRouter http.Handler,
|
||||
creds auth.Credentials, t *testing.T,
|
||||
) {
|
||||
// PUT
|
||||
req, err := newTestSignedRequestV4(http.MethodPut, getBucketCorsURL("", bucketName),
|
||||
int64(len(testCORSDoc)), bytes.NewReader([]byte(testCORSDoc)), creds.AccessKey, creds.SecretKey, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("PUT cors: expected 200, got %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// GET returns what we stored
|
||||
req, err = newTestSignedRequestV4(http.MethodGet, getBucketCorsURL("", bucketName),
|
||||
0, nil, creds.AccessKey, creds.SecretKey, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec = httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("GET cors: expected 200, got %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if !bytes.Contains(rec.Body.Bytes(), []byte("http://example.com")) {
|
||||
t.Fatalf("GET cors: body missing origin: %s", rec.Body.String())
|
||||
}
|
||||
|
||||
// DELETE
|
||||
req, err = newTestSignedRequestV4(http.MethodDelete, getBucketCorsURL("", bucketName),
|
||||
0, nil, creds.AccessKey, creds.SecretKey, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec = httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("DELETE cors: expected 204, got %d", rec.Code)
|
||||
}
|
||||
|
||||
// GET after delete → 404 NoSuchCORSConfiguration
|
||||
req, err = newTestSignedRequestV4(http.MethodGet, getBucketCorsURL("", bucketName),
|
||||
0, nil, creds.AccessKey, creds.SecretKey, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec = httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("GET cors after delete: expected 404, got %d", rec.Code)
|
||||
}
|
||||
|
||||
// Malformed XML → 400
|
||||
req, err = newTestSignedRequestV4(http.MethodPut, getBucketCorsURL("", bucketName),
|
||||
int64(len("<bad>")), bytes.NewReader([]byte("<bad>")), creds.AccessKey, creds.SecretKey, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec = httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("PUT malformed cors: expected 400, got %d", rec.Code)
|
||||
}
|
||||
|
||||
// Missing Content-MD5 is rejected before the body is parsed.
|
||||
req, err = newTestRequest(http.MethodPut, getBucketCorsURL("", bucketName),
|
||||
int64(len(testCORSDoc)), bytes.NewReader([]byte(testCORSDoc)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Del("Content-Md5")
|
||||
if err = signRequestV4(req, creds.AccessKey, creds.SecretKey); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec = httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest || !bytes.Contains(rec.Body.Bytes(), []byte("<Code>MissingContentMD5</Code>")) {
|
||||
t.Fatalf("PUT cors without Content-MD5: expected MissingContentMD5, got %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// A signed but incorrect Content-MD5 is rejected while reading the body.
|
||||
req, err = newTestRequest(http.MethodPut, getBucketCorsURL("", bucketName),
|
||||
int64(len(testCORSDoc)), bytes.NewReader([]byte(testCORSDoc)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Content-Md5", getMD5HashBase64([]byte("different body")))
|
||||
if err = signRequestV4(req, creds.AccessKey, creds.SecretKey); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec = httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest || !bytes.Contains(rec.Body.Bytes(), []byte("<Code>BadDigest</Code>")) {
|
||||
t.Fatalf("PUT cors with bad Content-MD5: expected BadDigest, got %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// Re-PUT the config so the store→GetCorsConfig→enforce seam below has
|
||||
// something to enforce (the earlier DELETE removed it).
|
||||
req, err = newTestSignedRequestV4(http.MethodPut, getBucketCorsURL("", bucketName),
|
||||
int64(len(testCORSDoc)), bytes.NewReader([]byte(testCORSDoc)), creds.AccessKey, creds.SecretKey, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec = httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("PUT cors (re-put): expected 200, got %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// End-to-end enforcement: drive an OPTIONS preflight through the real
|
||||
// corsHandler wrapper (not applyBucketCors in isolation), exercising the
|
||||
// full store -> globalBucketMetadataSys.GetCorsConfig -> enforce seam.
|
||||
wrapped := corsHandler(apiRouter)
|
||||
|
||||
preflightURL := getBucketCorsURL("", bucketName)
|
||||
preflightReq := httptest.NewRequest(http.MethodOptions, preflightURL, nil)
|
||||
preflightReq.Header.Set("Origin", "http://example.com")
|
||||
preflightReq.Header.Set("Access-Control-Request-Method", http.MethodGet)
|
||||
|
||||
rec = httptest.NewRecorder()
|
||||
wrapped.ServeHTTP(rec, preflightReq)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("OPTIONS preflight via corsHandler: expected 200, got %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "http://example.com" {
|
||||
t.Fatalf("OPTIONS preflight via corsHandler: expected Access-Control-Allow-Origin echoed, got %q", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,740 @@
|
||||
// Copyright (c) 2015-2021 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
|
||||
"github.com/minio/minio/internal/auth"
|
||||
"github.com/minio/minio/internal/bucket/cors"
|
||||
)
|
||||
|
||||
type corsLookupCountingObjectLayer struct {
|
||||
ObjectLayer
|
||||
getObjectNInfoCalls atomic.Int64
|
||||
}
|
||||
|
||||
func (o *corsLookupCountingObjectLayer) GetObjectNInfo(ctx context.Context, bucket, object string, rs *HTTPRangeSpec, h http.Header, opts ObjectOptions) (*GetObjectReader, error) {
|
||||
o.getObjectNInfoCalls.Add(1)
|
||||
return o.ObjectLayer.GetObjectNInfo(ctx, bucket, object, rs, h, opts)
|
||||
}
|
||||
|
||||
func TestPerBucketCorsPreflight(t *testing.T) {
|
||||
cfg := &cors.Config{CORSRules: []cors.Rule{{
|
||||
AllowedOrigins: []string{"http://example.com"},
|
||||
AllowedMethods: []string{"GET", "PUT"},
|
||||
AllowedHeaders: []string{"*"},
|
||||
ExposeHeaders: []string{"ETag"},
|
||||
MaxAgeSeconds: 3000,
|
||||
}}}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodOptions, "/mybucket/obj", nil)
|
||||
req.Header.Set("Origin", "http://example.com")
|
||||
req.Header.Set("Access-Control-Request-Method", "GET")
|
||||
req.Header.Set("Access-Control-Request-Headers", "X-Amz-Date")
|
||||
|
||||
handled := applyBucketCors(rec, req, cfg)
|
||||
if !handled {
|
||||
t.Fatal("expected preflight to be handled")
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "http://example.com" {
|
||||
t.Fatalf("allow-origin = %q", got)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Credentials"); got != "true" {
|
||||
t.Fatalf("allow-credentials = %q", got)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Methods"); got != "GET, PUT" {
|
||||
t.Fatalf("allow-methods = %q", got)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Headers"); got != "X-Amz-Date" {
|
||||
t.Fatalf("allow-headers = %q", got)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Expose-Headers"); got != "ETag" {
|
||||
t.Fatalf("expose-headers = %q", got)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Max-Age"); got != "3000" {
|
||||
t.Fatalf("max-age = %q", got)
|
||||
}
|
||||
requireCorsVary(t, rec.Header())
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("preflight status = %d", rec.Code)
|
||||
}
|
||||
requireCorsOriginVary(t, rec.Header())
|
||||
}
|
||||
|
||||
func TestPerBucketCorsActualRequestNoMatchVariesByOrigin(t *testing.T) {
|
||||
cfg := &cors.Config{CORSRules: []cors.Rule{{
|
||||
AllowedOrigins: []string{"https://allowed.example.com"},
|
||||
AllowedMethods: []string{"GET"},
|
||||
}}}
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/mybucket/obj", nil)
|
||||
req.Header.Set("Origin", "https://denied.example.com")
|
||||
|
||||
if handled := applyBucketCors(rec, req, cfg); handled {
|
||||
t.Fatal("actual request must continue when CORS does not match")
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "" {
|
||||
t.Fatalf("allow-origin = %q", got)
|
||||
}
|
||||
requireCorsOriginVary(t, rec.Header())
|
||||
}
|
||||
|
||||
func TestPerBucketCorsPreflightNoMatch(t *testing.T) {
|
||||
cfg := &cors.Config{CORSRules: []cors.Rule{{
|
||||
AllowedOrigins: []string{"http://example.com"},
|
||||
AllowedMethods: []string{"GET"},
|
||||
}}}
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodOptions, "/mybucket/obj", nil)
|
||||
req.Header.Set("Origin", "http://evil.com")
|
||||
req.Header.Set("Access-Control-Request-Method", "GET")
|
||||
|
||||
handled := applyBucketCors(rec, req, cfg)
|
||||
if !handled {
|
||||
t.Fatal("expected preflight to be handled (rejected)")
|
||||
}
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("expected 403 for disallowed origin, got %d", rec.Code)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "" {
|
||||
t.Fatalf("rejected preflight returned allow-origin %q", got)
|
||||
}
|
||||
requireCorsVary(t, rec.Header())
|
||||
}
|
||||
|
||||
func TestPerBucketCorsPreflightWildcardOriginAndZeroMaxAge(t *testing.T) {
|
||||
doc := `<CORSConfiguration><CORSRule><AllowedOrigin>*</AllowedOrigin><AllowedMethod>GET</AllowedMethod><AllowedMethod>HEAD</AllowedMethod><AllowedHeader>*</AllowedHeader><ExposeHeader>ETag</ExposeHeader><MaxAgeSeconds>0</MaxAgeSeconds></CORSRule></CORSConfiguration>`
|
||||
cfg, err := cors.ParseBucketCorsConfig(strings.NewReader(doc))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodOptions, "/mybucket/obj", nil)
|
||||
req.Header.Set("Origin", "https://app.example.com")
|
||||
req.Header.Set("Access-Control-Request-Method", "GET")
|
||||
req.Header.Set("Access-Control-Request-Headers", "RANGE")
|
||||
|
||||
if handled := applyBucketCors(rec, req, cfg); !handled {
|
||||
t.Fatal("expected preflight to be handled")
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "*" {
|
||||
t.Fatalf("allow-origin = %q", got)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Credentials"); got != "" {
|
||||
t.Fatalf("allow-credentials = %q", got)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Methods"); got != "GET, HEAD" {
|
||||
t.Fatalf("allow-methods = %q", got)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Headers"); got != "RANGE" {
|
||||
t.Fatalf("allow-headers = %q", got)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Expose-Headers"); got != "ETag" {
|
||||
t.Fatalf("expose-headers = %q", got)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Max-Age"); got != "0" {
|
||||
t.Fatalf("max-age = %q", got)
|
||||
}
|
||||
requireCorsVary(t, rec.Header())
|
||||
}
|
||||
|
||||
func TestPerBucketCorsPreflightUsesFirstFullyMatchingRule(t *testing.T) {
|
||||
cfg := &cors.Config{CORSRules: []cors.Rule{
|
||||
{
|
||||
AllowedOrigins: []string{"https://app.example.com"},
|
||||
AllowedMethods: []string{"GET"},
|
||||
AllowedHeaders: []string{"x-a"},
|
||||
ExposeHeaders: []string{"x-rule-a"},
|
||||
MaxAgeSeconds: 1,
|
||||
},
|
||||
{
|
||||
AllowedOrigins: []string{"https://app.example.com"},
|
||||
AllowedMethods: []string{"GET", "HEAD"},
|
||||
AllowedHeaders: []string{"*"},
|
||||
ExposeHeaders: []string{"x-rule-b"},
|
||||
MaxAgeSeconds: 2,
|
||||
},
|
||||
}}
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodOptions, "/mybucket/obj", nil)
|
||||
req.Header.Set("Origin", "https://app.example.com")
|
||||
req.Header.Set("Access-Control-Request-Method", "GET")
|
||||
req.Header.Set("Access-Control-Request-Headers", "X-B")
|
||||
|
||||
if handled := applyBucketCors(rec, req, cfg); !handled {
|
||||
t.Fatal("expected preflight to be handled")
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Expose-Headers"); got != "x-rule-b" {
|
||||
t.Fatalf("selected rule expose-headers = %q", got)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Methods"); got != "GET, HEAD" {
|
||||
t.Fatalf("selected rule allow-methods = %q", got)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Max-Age"); got != "2" {
|
||||
t.Fatalf("selected rule max-age = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPerBucketCorsActualRequest(t *testing.T) {
|
||||
cfg := &cors.Config{CORSRules: []cors.Rule{{
|
||||
AllowedOrigins: []string{"*"},
|
||||
AllowedMethods: []string{"GET"},
|
||||
ExposeHeaders: []string{"ETag"},
|
||||
}}}
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/mybucket/obj", nil)
|
||||
req.Header.Set("Origin", "http://any.com")
|
||||
|
||||
handled := applyBucketCors(rec, req, cfg)
|
||||
if handled {
|
||||
t.Fatal("actual (non-preflight) request must not be terminated by CORS")
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "*" {
|
||||
t.Fatalf("allow-origin = %q", got)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Credentials"); got != "" {
|
||||
t.Fatalf("allow-credentials = %q", got)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Expose-Headers"); got != "ETag" {
|
||||
t.Fatalf("expose-headers = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPerBucketCorsOriginPatternResponse(t *testing.T) {
|
||||
cfg := &cors.Config{CORSRules: []cors.Rule{{
|
||||
AllowedOrigins: []string{"https://app.example.com", "https://*", "*"},
|
||||
AllowedMethods: []string{"GET"},
|
||||
}}}
|
||||
|
||||
tests := []struct {
|
||||
origin string
|
||||
wantOrigin string
|
||||
wantCredentials string
|
||||
}{
|
||||
{"https://app.example.com", "https://app.example.com", "true"},
|
||||
{"https://other.example.com", "https://other.example.com", "true"},
|
||||
{"http://other.example.com", "*", ""},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/mybucket/obj", nil)
|
||||
req.Header.Set("Origin", tt.origin)
|
||||
if handled := applyBucketCors(rec, req, cfg); handled {
|
||||
t.Fatal("actual request must not be terminated by CORS")
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != tt.wantOrigin {
|
||||
t.Fatalf("origin %q: allow-origin = %q, want %q", tt.origin, got, tt.wantOrigin)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Credentials"); got != tt.wantCredentials {
|
||||
t.Fatalf("origin %q: allow-credentials = %q, want %q", tt.origin, got, tt.wantCredentials)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBucketCorsMetadataErrorFailsClosed(t *testing.T) {
|
||||
oldObjectAPI := newObjectLayerFn()
|
||||
oldMetadataSys := globalBucketMetadataSys
|
||||
setObjectLayer(nil)
|
||||
globalBucketMetadataSys = NewBucketMetadataSys()
|
||||
defer func() {
|
||||
setObjectLayer(oldObjectAPI)
|
||||
globalBucketMetadataSys = oldMetadataSys
|
||||
}()
|
||||
|
||||
wrapped := corsHandler(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
|
||||
for _, method := range []string{http.MethodGet, http.MethodOptions} {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(method, getGetObjectURL("", "cors-metadata-error", "object"), nil)
|
||||
req.Header.Set("Origin", "https://app.example.com")
|
||||
if method == http.MethodOptions {
|
||||
req.Header.Set("Access-Control-Request-Method", http.MethodGet)
|
||||
}
|
||||
wrapped.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("%s status = %d, want %d", method, rec.Code, http.StatusNoContent)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "" {
|
||||
t.Fatalf("%s metadata error fell back to global allow-origin %q", method, got)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Credentials"); got != "" {
|
||||
t.Fatalf("%s metadata error fell back to global credentials %q", method, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBucketCorsSkipsMetadataLookupWithoutOrigin(t *testing.T) {
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testBucketCorsSkipsMetadataLookupWithoutOrigin,
|
||||
endpoints: []string{"GetObject"},
|
||||
})
|
||||
}
|
||||
|
||||
func testBucketCorsSkipsMetadataLookupWithoutOrigin(obj ObjectLayer, _ string, _ string, _ http.Handler, _ auth.Credentials, t *testing.T) {
|
||||
oldObjectAPI := newObjectLayerFn()
|
||||
counting := &corsLookupCountingObjectLayer{ObjectLayer: obj}
|
||||
setObjectLayer(counting)
|
||||
defer setObjectLayer(oldObjectAPI)
|
||||
|
||||
wrapped := corsHandler(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
rec := httptest.NewRecorder()
|
||||
wrapped.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, getGetObjectURL("", "api", "v1/login"), nil))
|
||||
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, http.StatusNoContent)
|
||||
}
|
||||
requireCorsOriginVary(t, rec.Header())
|
||||
if got := counting.getObjectNInfoCalls.Load(); got != 0 {
|
||||
t.Fatalf("request without Origin performed %d bucket metadata reads", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBucketCorsOriginlessPreflightShapeUsesGlobalHandler(t *testing.T) {
|
||||
nextCalled := false
|
||||
wrapped := corsHandler(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
nextCalled = true
|
||||
w.WriteHeader(http.StatusTeapot)
|
||||
}))
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodOptions, getGetObjectURL("", "api", "v1/login"), nil)
|
||||
req.Header.Set("Access-Control-Request-Method", http.MethodGet)
|
||||
wrapped.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, http.StatusNoContent)
|
||||
}
|
||||
if nextCalled {
|
||||
t.Fatal("originless preflight-shaped OPTIONS reached the application handler")
|
||||
}
|
||||
requireCorsOriginVary(t, rec.Header())
|
||||
}
|
||||
|
||||
func TestBucketCorsNoConfigUsesGlobalFallback(t *testing.T) {
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testBucketCorsNoConfigUsesGlobalFallback,
|
||||
endpoints: []string{"GetBucketCors"},
|
||||
})
|
||||
}
|
||||
|
||||
func TestBucketCorsMissingBucketUsesGlobalFallback(t *testing.T) {
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testBucketCorsMissingBucketUsesGlobalFallback,
|
||||
endpoints: []string{"GetBucketCors"},
|
||||
})
|
||||
}
|
||||
|
||||
func testBucketCorsMissingBucketUsesGlobalFallback(obj ObjectLayer, _ string, bucket string, _ http.Handler, _ auth.Credentials, t *testing.T) {
|
||||
// Model a fully started server: bucket metadata loading has completed, so
|
||||
// a name that is not resident is genuinely not a CORS-bearing bucket.
|
||||
restore := markBucketMetadataInitialized(t)
|
||||
defer restore()
|
||||
|
||||
// A non-resident bucket name must not cause any bucket-metadata disk read.
|
||||
oldObjectAPI := newObjectLayerFn()
|
||||
counting := &corsLookupCountingObjectLayer{ObjectLayer: obj}
|
||||
setObjectLayer(counting)
|
||||
defer setObjectLayer(oldObjectAPI)
|
||||
|
||||
before := bucketMetadataMapLen()
|
||||
|
||||
wrapped := corsHandler(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}))
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, getGetObjectURL("", bucket+"-missing", "object"), nil)
|
||||
req.Header.Set("Origin", "https://app.example.com")
|
||||
wrapped.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, http.StatusNotFound)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "https://app.example.com" {
|
||||
t.Fatalf("allow-origin = %q", got)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Credentials"); got != "true" {
|
||||
t.Fatalf("allow-credentials = %q", got)
|
||||
}
|
||||
// Regression guard: the pre-auth CORS lookup for a non-existent bucket must
|
||||
// neither read bucket metadata from disk nor cache a synthetic entry.
|
||||
if got := counting.getObjectNInfoCalls.Load(); got != 0 {
|
||||
t.Fatalf("missing-bucket CORS lookup performed %d bucket metadata reads", got)
|
||||
}
|
||||
if after := bucketMetadataMapLen(); after != before {
|
||||
t.Fatalf("missing-bucket CORS lookup grew metadataMap from %d to %d", before, after)
|
||||
}
|
||||
}
|
||||
|
||||
func testBucketCorsNoConfigUsesGlobalFallback(_ ObjectLayer, _ string, bucket string, _ http.Handler, _ auth.Credentials, t *testing.T) {
|
||||
wrapped := corsHandler(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, getGetObjectURL("", bucket, "object"), nil)
|
||||
req.Header.Set("Origin", "https://app.example.com")
|
||||
wrapped.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("status = %d, want %d", rec.Code, http.StatusNoContent)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "https://app.example.com" {
|
||||
t.Fatalf("allow-origin = %q", got)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Credentials"); got != "true" {
|
||||
t.Fatalf("allow-credentials = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPerBucketCorsActualPatternOriginSupportsCredentials(t *testing.T) {
|
||||
cfg := &cors.Config{CORSRules: []cors.Rule{{
|
||||
AllowedOrigins: []string{"https://*.example.com"},
|
||||
AllowedMethods: []string{"GET"},
|
||||
}}}
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/mybucket/obj", nil)
|
||||
req.Header.Set("Origin", "https://app.example.com")
|
||||
|
||||
if handled := applyBucketCors(rec, req, cfg); handled {
|
||||
t.Fatal("actual request must continue")
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "https://app.example.com" {
|
||||
t.Fatalf("allow-origin = %q", got)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Credentials"); got != "true" {
|
||||
t.Fatalf("allow-credentials = %q", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPerBucketCorsActualNullOriginSurvivesForwardingMiddleware(t *testing.T) {
|
||||
next := setBucketForwardingMiddleware(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
|
||||
t.Run("per-bucket null origin", func(t *testing.T) {
|
||||
cfg := &cors.Config{CORSRules: []cors.Rule{{
|
||||
AllowedOrigins: []string{"null"},
|
||||
AllowedMethods: []string{"GET"},
|
||||
}}}
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/mybucket/obj", nil)
|
||||
req.Header.Set("Origin", "null")
|
||||
|
||||
if handled := applyBucketCors(rec, req, cfg); handled {
|
||||
t.Fatal("actual request must continue")
|
||||
}
|
||||
next.ServeHTTP(rec, req)
|
||||
|
||||
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "null" {
|
||||
t.Fatalf("allow-origin = %q", got)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Credentials"); got != "true" {
|
||||
t.Fatalf("allow-credentials = %q", got)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("legacy unmarked null origin", func(t *testing.T) {
|
||||
rec := httptest.NewRecorder()
|
||||
rec.Header().Set("Access-Control-Allow-Origin", "null")
|
||||
req := httptest.NewRequest(http.MethodGet, "/mybucket/obj", nil)
|
||||
|
||||
next.ServeHTTP(rec, req)
|
||||
|
||||
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "*" {
|
||||
t.Fatalf("allow-origin = %q", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func requireCorsVary(t *testing.T, header http.Header) {
|
||||
t.Helper()
|
||||
values := strings.Join(header.Values("Vary"), ",")
|
||||
for _, want := range []string{"Origin", "Access-Control-Request-Method", "Access-Control-Request-Headers"} {
|
||||
if !strings.Contains(values, want) {
|
||||
t.Fatalf("Vary = %q, missing %q", values, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func requireCorsOriginVary(t *testing.T, header http.Header) {
|
||||
t.Helper()
|
||||
if values := strings.Join(header.Values("Vary"), ","); !strings.Contains(values, "Origin") {
|
||||
t.Fatalf("Vary = %q, missing Origin", values)
|
||||
}
|
||||
}
|
||||
|
||||
// markBucketMetadataInitialized marks the global bucket-metadata subsystem as
|
||||
// fully loaded, modeling a running server (the API test harness sets up the
|
||||
// subsystem but does not run Init). It returns a function that restores the
|
||||
// previous state.
|
||||
func markBucketMetadataInitialized(t *testing.T) func() {
|
||||
t.Helper()
|
||||
sys := globalBucketMetadataSys
|
||||
if sys == nil {
|
||||
t.Fatal("globalBucketMetadataSys is nil")
|
||||
}
|
||||
sys.Lock()
|
||||
prev := sys.initialized
|
||||
sys.initialized = true
|
||||
sys.Unlock()
|
||||
return func() {
|
||||
sys.Lock()
|
||||
sys.initialized = prev
|
||||
sys.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// bucketMetadataMapLen returns the number of resident bucket-metadata entries.
|
||||
func bucketMetadataMapLen() int {
|
||||
sys := globalBucketMetadataSys
|
||||
if sys == nil {
|
||||
return 0
|
||||
}
|
||||
sys.RLock()
|
||||
defer sys.RUnlock()
|
||||
return len(sys.metadataMap)
|
||||
}
|
||||
|
||||
// TestBucketCorsUnknownBucketDoesNotGrowMetadata is the regression guard for
|
||||
// the pre-auth resource-exhaustion path: an unauthenticated, Origin-bearing
|
||||
// request whose first path segment is not a real bucket must fall back to the
|
||||
// global CORS policy without loading bucket metadata from disk and without
|
||||
// caching a synthetic entry. Before the resident-only lookup, each distinct
|
||||
// name grew metadataMap by one and issued an erasure metadata probe.
|
||||
func TestBucketCorsUnknownBucketDoesNotGrowMetadata(t *testing.T) {
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testBucketCorsUnknownBucketDoesNotGrowMetadata,
|
||||
endpoints: []string{"GetBucketCors"},
|
||||
})
|
||||
}
|
||||
|
||||
func testBucketCorsUnknownBucketDoesNotGrowMetadata(obj ObjectLayer, _ string, _ string, _ http.Handler, _ auth.Credentials, t *testing.T) {
|
||||
restore := markBucketMetadataInitialized(t)
|
||||
defer restore()
|
||||
|
||||
oldObjectAPI := newObjectLayerFn()
|
||||
counting := &corsLookupCountingObjectLayer{ObjectLayer: obj}
|
||||
setObjectLayer(counting)
|
||||
defer setObjectLayer(oldObjectAPI)
|
||||
|
||||
wrapped := corsHandler(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}))
|
||||
|
||||
before := bucketMetadataMapLen()
|
||||
// Console/admin routes plus enough distinct valid names to make accidental
|
||||
// cache growth or one metadata probe per name unambiguous.
|
||||
names := []string{"minio", "api"}
|
||||
for i := 0; i < 500; i++ {
|
||||
names = append(names, fmt.Sprintf("cors-missing-%03d", i))
|
||||
}
|
||||
for _, name := range names {
|
||||
for _, method := range []string{http.MethodGet, http.MethodOptions} {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(method, getGetObjectURL("", name, "obj"), nil)
|
||||
req.Header.Set("Origin", "https://app.example.com")
|
||||
if method == http.MethodOptions {
|
||||
req.Header.Set("Access-Control-Request-Method", http.MethodGet)
|
||||
}
|
||||
wrapped.ServeHTTP(rec, req)
|
||||
|
||||
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "https://app.example.com" {
|
||||
t.Fatalf("%s/%s: allow-origin = %q, want global fallback", name, method, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, path := range []string{"/../obj", "/A/obj", "/x/obj", "/minio/admin/v3/info", "/api/v1/login"} {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, path, nil)
|
||||
req.Header.Set("Origin", "https://app.example.com")
|
||||
wrapped.ServeHTTP(rec, req)
|
||||
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "https://app.example.com" {
|
||||
t.Fatalf("%s: allow-origin = %q, want global fallback", path, got)
|
||||
}
|
||||
}
|
||||
|
||||
if got := counting.getObjectNInfoCalls.Load(); got != 0 {
|
||||
t.Fatalf("unknown-bucket CORS lookups performed %d bucket metadata reads", got)
|
||||
}
|
||||
if after := bucketMetadataMapLen(); after != before {
|
||||
t.Fatalf("unknown-bucket CORS lookups grew metadataMap from %d to %d", before, after)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBucketCorsStartupMissFailsClosedWithoutIO(t *testing.T) {
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testBucketCorsStartupMissFailsClosedWithoutIO,
|
||||
endpoints: []string{"GetBucketCors"},
|
||||
})
|
||||
}
|
||||
|
||||
func testBucketCorsStartupMissFailsClosedWithoutIO(obj ObjectLayer, _ string, _ string, _ http.Handler, _ auth.Credentials, t *testing.T) {
|
||||
oldObjectAPI := newObjectLayerFn()
|
||||
oldMetadataSys := globalBucketMetadataSys
|
||||
counting := &corsLookupCountingObjectLayer{ObjectLayer: obj}
|
||||
setObjectLayer(counting)
|
||||
globalBucketMetadataSys = NewBucketMetadataSys()
|
||||
defer func() {
|
||||
setObjectLayer(oldObjectAPI)
|
||||
globalBucketMetadataSys = oldMetadataSys
|
||||
}()
|
||||
|
||||
innerCalled := false
|
||||
wrapped := corsHandler(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
innerCalled = true
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}))
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, "/startup-missing/object", nil)
|
||||
req.Header.Set("Origin", "https://app.example.com")
|
||||
wrapped.ServeHTTP(rec, req)
|
||||
|
||||
if !innerCalled || rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("startup miss did not reach inner handler: called=%v status=%d", innerCalled, rec.Code)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "" {
|
||||
t.Fatalf("startup miss used permissive global CORS: %q", got)
|
||||
}
|
||||
if got := counting.getObjectNInfoCalls.Load(); got != 0 {
|
||||
t.Fatalf("startup miss performed %d metadata reads", got)
|
||||
}
|
||||
if got := globalBucketMetadataSys.Count(); got != 0 {
|
||||
t.Fatalf("startup miss grew metadataMap to %d", got)
|
||||
}
|
||||
}
|
||||
|
||||
// markBucketMetadataLoadFailed records a bucket as one whose metadata failed to
|
||||
// load at startup while the subsystem is Initialized, modeling the degraded
|
||||
// state where a real bucket is not resident. Returns a restore function.
|
||||
func markBucketMetadataLoadFailed(t *testing.T, bucket string) func() {
|
||||
t.Helper()
|
||||
sys := globalBucketMetadataSys
|
||||
if sys == nil {
|
||||
t.Fatal("globalBucketMetadataSys is nil")
|
||||
}
|
||||
sys.Lock()
|
||||
_, had := sys.loadFailed[bucket]
|
||||
sys.loadFailed[bucket] = struct{}{}
|
||||
sys.Unlock()
|
||||
return func() {
|
||||
sys.Lock()
|
||||
if !had {
|
||||
delete(sys.loadFailed, bucket)
|
||||
}
|
||||
sys.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
// TestBucketCorsLoadFailedBucketFailsClosed guards P1: a real bucket whose
|
||||
// metadata could not be loaded at startup (present in loadFailed, subsystem
|
||||
// Initialized) must NOT be answered with the permissive global CORS policy. We
|
||||
// cannot rule out a restrictive per-bucket config for it, so it must fail
|
||||
// closed — without a synchronous disk read.
|
||||
func TestBucketCorsLoadFailedBucketFailsClosed(t *testing.T) {
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testBucketCorsLoadFailedBucketFailsClosed,
|
||||
endpoints: []string{"GetBucketCors"},
|
||||
})
|
||||
}
|
||||
|
||||
func testBucketCorsLoadFailedBucketFailsClosed(obj ObjectLayer, _ string, _ string, _ http.Handler, _ auth.Credentials, t *testing.T) {
|
||||
restoreInit := markBucketMetadataInitialized(t)
|
||||
defer restoreInit()
|
||||
restoreFail := markBucketMetadataLoadFailed(t, "strict-cors-bucket")
|
||||
defer restoreFail()
|
||||
|
||||
oldObjectAPI := newObjectLayerFn()
|
||||
counting := &corsLookupCountingObjectLayer{ObjectLayer: obj}
|
||||
setObjectLayer(counting)
|
||||
defer setObjectLayer(oldObjectAPI)
|
||||
|
||||
wrapped := corsHandler(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}))
|
||||
|
||||
for _, method := range []string{http.MethodGet, http.MethodOptions} {
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(method, getGetObjectURL("", "strict-cors-bucket", "object"), nil)
|
||||
req.Header.Set("Origin", "https://app.example.com")
|
||||
if method == http.MethodOptions {
|
||||
req.Header.Set("Access-Control-Request-Method", http.MethodGet)
|
||||
}
|
||||
wrapped.ServeHTTP(rec, req)
|
||||
|
||||
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "" {
|
||||
t.Fatalf("%s: load-failed bucket fell back to global allow-origin %q", method, got)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Credentials"); got != "" {
|
||||
t.Fatalf("%s: load-failed bucket fell back to global credentials %q", method, got)
|
||||
}
|
||||
}
|
||||
if got := counting.getObjectNInfoCalls.Load(); got != 0 {
|
||||
t.Fatalf("load-failed CORS lookup performed %d synchronous bucket metadata reads", got)
|
||||
}
|
||||
}
|
||||
|
||||
// TestBucketCorsInternalBucketFailsClosed guards P2: an Origin-bearing request
|
||||
// whose first path segment is the reserved .minio.sys namespace must preserve
|
||||
// GetConfig's errInvalidArgument semantics and fail closed, not fall back to
|
||||
// the permissive global CORS policy.
|
||||
func TestBucketCorsInternalBucketFailsClosed(t *testing.T) {
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testBucketCorsInternalBucketFailsClosed,
|
||||
endpoints: []string{"GetBucketCors"},
|
||||
})
|
||||
}
|
||||
|
||||
func testBucketCorsInternalBucketFailsClosed(_ ObjectLayer, _ string, _ string, _ http.Handler, _ auth.Credentials, t *testing.T) {
|
||||
restoreInit := markBucketMetadataInitialized(t)
|
||||
defer restoreInit()
|
||||
|
||||
wrapped := corsHandler(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}))
|
||||
rec := httptest.NewRecorder()
|
||||
req := httptest.NewRequest(http.MethodGet, getGetObjectURL("", minioMetaBucket, "object"), nil)
|
||||
req.Header.Set("Origin", "https://app.example.com")
|
||||
wrapped.ServeHTTP(rec, req)
|
||||
|
||||
if got := rec.Header().Get("Access-Control-Allow-Origin"); got != "" {
|
||||
t.Fatalf("internal bucket fell back to global allow-origin %q", got)
|
||||
}
|
||||
if got := rec.Header().Get("Access-Control-Allow-Credentials"); got != "" {
|
||||
t.Fatalf("internal bucket fell back to global credentials %q", got)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
+16
-12
@@ -463,13 +463,20 @@ func (api objectAPIHandlers) DeleteMultipleObjectsHandler(w http.ResponseWriter,
|
||||
// Make sure to update context to print ObjectNames for multi objects.
|
||||
ctx = updateReqContext(ctx, objects...)
|
||||
|
||||
// Call checkRequestAuthType to populate ReqInfo.AccessKey before GetBucketInfo()
|
||||
// Ignore errors here to preserve the S3 error behavior of GetBucketInfo()
|
||||
checkRequestAuthType(ctx, r, policy.DeleteObjectAction, bucket, "")
|
||||
|
||||
deleteObjectsFn := objectAPI.DeleteObjects
|
||||
|
||||
// Return Malformed XML as S3 spec if the number of objects is empty
|
||||
reqInfo := logger.GetReqInfo(ctx)
|
||||
if reqInfo == nil {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrAccessDenied), r.URL)
|
||||
return
|
||||
}
|
||||
reqInfo.BucketName = bucket
|
||||
reqInfo.ObjectName = ""
|
||||
if s3Err := authenticateRequest(ctx, r, policy.DeleteObjectAction); s3Err != ErrNone {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Err), r.URL)
|
||||
return
|
||||
}
|
||||
// Return Malformed XML as S3 spec if the number of objects is empty.
|
||||
if len(deleteObjectsReq.Objects) == 0 || len(deleteObjectsReq.Objects) > maxDeleteList {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrMalformedXML), r.URL)
|
||||
return
|
||||
@@ -499,7 +506,9 @@ func (api objectAPIHandlers) DeleteMultipleObjectsHandler(w http.ResponseWriter,
|
||||
vc, _ := globalBucketVersioningSys.Get(bucket)
|
||||
oss := make([]*objSweeper, len(deleteObjectsReq.Objects))
|
||||
for index, object := range deleteObjectsReq.Objects {
|
||||
if apiErrCode := checkRequestAuthTypeWithVID(ctx, r, policy.DeleteObjectAction, bucket, object.ObjectName, object.VersionID); apiErrCode != ErrNone {
|
||||
reqInfo.ObjectName = object.ObjectName
|
||||
reqInfo.VersionID = object.VersionID
|
||||
if apiErrCode := authorizeRequest(ctx, r, deleteObjectAction(object.VersionID)); apiErrCode != ErrNone {
|
||||
if apiErrCode == ErrSignatureDoesNotMatch || apiErrCode == ErrInvalidAccessKeyID {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(apiErrCode), r.URL)
|
||||
return
|
||||
@@ -1844,12 +1853,7 @@ func (api objectAPIHandlers) PutBucketObjectLockConfigHandler(w http.ResponseWri
|
||||
// We encode the xml bytes as base64 to ensure there are no encoding
|
||||
// errors.
|
||||
cfgStr := base64.StdEncoding.EncodeToString(configData)
|
||||
replLogIf(ctx, globalSiteReplicationSys.BucketMetaHook(ctx, madmin.SRBucketMeta{
|
||||
Type: madmin.SRBucketMetaTypeObjectLockConfig,
|
||||
Bucket: bucket,
|
||||
ObjectLockConfig: &cfgStr,
|
||||
UpdatedAt: updatedAt,
|
||||
}))
|
||||
replLogIf(ctx, globalSiteReplicationSys.BucketMetaHook(ctx, newSRBucketObjectLockMeta(bucket, &cfgStr, updatedAt)))
|
||||
|
||||
// Write success response.
|
||||
writeSuccessResponseHeadersOnly(w)
|
||||
|
||||
+71
-18
@@ -24,12 +24,52 @@ import (
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/minio/minio/internal/auth"
|
||||
)
|
||||
|
||||
func TestListObjectsNonExistentBucketHandler(t *testing.T) {
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{t: t, objAPITest: testListObjectsNonExistentBucketHandler})
|
||||
}
|
||||
|
||||
func testListObjectsNonExistentBucketHandler(_ ObjectLayer, instanceType, _ string, apiRouter http.Handler,
|
||||
credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
const bucket = "missing-bucket"
|
||||
testCases := []struct {
|
||||
name string
|
||||
query url.Values
|
||||
}{
|
||||
{name: "ListObjects", query: url.Values{"prefix": {"/"}}},
|
||||
{name: "ListObjectsV2", query: url.Values{"list-type": {"2"}, "prefix": {"/"}}},
|
||||
{name: "ListObjectVersions", query: url.Values{"versions": {""}, "prefix": {"/"}}},
|
||||
}
|
||||
|
||||
for _, tc := range testCases {
|
||||
req, err := newTestSignedRequestV4(http.MethodGet, makeTestTargetURL("", bucket, "", tc.query), 0, nil,
|
||||
credentials.AccessKey, credentials.SecretKey, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: %s: failed to create request: %v", instanceType, tc.name, err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNotFound {
|
||||
t.Errorf("%s: %s: expected status %d, got %d", instanceType, tc.name, http.StatusNotFound, rec.Code)
|
||||
}
|
||||
|
||||
var apiErr APIErrorResponse
|
||||
if err = xml.Unmarshal(rec.Body.Bytes(), &apiErr); err != nil {
|
||||
t.Fatalf("%s: %s: failed to decode error response: %v", instanceType, tc.name, err)
|
||||
}
|
||||
if apiErr.Code != "NoSuchBucket" {
|
||||
t.Errorf("%s: %s: expected NoSuchBucket, got %q", instanceType, tc.name, apiErr.Code)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Wrapper for calling RemoveBucket HTTP handler tests for both Erasure multiple disks and single node setup.
|
||||
func TestRemoveBucketHandler(t *testing.T) {
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{t: t, objAPITest: testRemoveBucketHandler, endpoints: []string{"RemoveBucket"}})
|
||||
@@ -978,14 +1018,23 @@ func testAPIDeleteMultipleObjectsVersionIDNullCondition(obj ObjectLayer, instanc
|
||||
|
||||
policyBytes := fmt.Appendf(nil, `{
|
||||
"Version":"2012-10-17",
|
||||
"Statement":[{
|
||||
"Effect":"Allow",
|
||||
"Principal":"*",
|
||||
"Action":"s3:DeleteObject",
|
||||
"Resource":"arn:aws:s3:::%s/*",
|
||||
"Condition":{"Null":{"s3:versionid":"true"}}
|
||||
}]
|
||||
}`, bucketName)
|
||||
"Statement":[
|
||||
{
|
||||
"Effect":"Allow",
|
||||
"Principal":"*",
|
||||
"Action":"s3:DeleteObject",
|
||||
"Resource":"arn:aws:s3:::%s/*",
|
||||
"Condition":{"Null":{"s3:versionid":"true"}}
|
||||
},
|
||||
{
|
||||
"Effect":"Allow",
|
||||
"Principal":"*",
|
||||
"Action":"s3:DeleteObjectVersion",
|
||||
"Resource":"arn:aws:s3:::%s/*",
|
||||
"Condition":{"StringEquals":{"s3:versionid":"%s"}}
|
||||
}
|
||||
]
|
||||
}`, bucketName, bucketName, versionIDs["with-version-id"])
|
||||
policyReq, err := newTestSignedRequestV4(http.MethodPut, getPutPolicyURL("", bucketName), int64(len(policyBytes)),
|
||||
bytes.NewReader(policyBytes), credentials.AccessKey, credentials.SecretKey, nil)
|
||||
if err != nil {
|
||||
@@ -1031,29 +1080,30 @@ func testAPIDeleteMultipleObjectsVersionIDNullCondition(obj ObjectLayer, instanc
|
||||
t.Errorf("%s: %q was not a successful delete-marker creation: %+v", instanceType, objectName, response.DeletedObjects)
|
||||
}
|
||||
}
|
||||
if len(deleted) != 2 {
|
||||
if object, ok := deleted["with-version-id"]; !ok || object.VersionID != versionIDs["with-version-id"] {
|
||||
t.Errorf("%s: matching explicit version was not deleted: %+v", instanceType, response.DeletedObjects)
|
||||
}
|
||||
if len(deleted) != 3 {
|
||||
t.Errorf("%s: unexpected deleted objects: %+v", instanceType, response.DeletedObjects)
|
||||
}
|
||||
errorsByKey := make(map[string]DeleteError, len(response.Errors))
|
||||
for _, deleteErr := range response.Errors {
|
||||
errorsByKey[deleteErr.Key] = deleteErr
|
||||
}
|
||||
for objectName, versionID := range map[string]string{
|
||||
"with-version-id": versionIDs["with-version-id"],
|
||||
"with-null-version-id": nullVersionID,
|
||||
} {
|
||||
for objectName, versionID := range map[string]string{"with-null-version-id": nullVersionID} {
|
||||
deleteErr, ok := errorsByKey[objectName]
|
||||
if !ok || deleteErr.VersionID != versionID || deleteErr.Code != errorCodes[ErrAccessDenied].Code {
|
||||
t.Errorf("%s: %q did not return AccessDenied for version %q: %+v", instanceType, objectName, versionID, response.Errors)
|
||||
}
|
||||
}
|
||||
if len(errorsByKey) != 2 {
|
||||
if len(errorsByKey) != 1 {
|
||||
t.Errorf("%s: unexpected delete errors: %+v", instanceType, response.Errors)
|
||||
}
|
||||
|
||||
// A simple delete adds a marker and keeps the old version. The explicitly
|
||||
// named version must also remain because its policy condition did not match.
|
||||
for objectName, versionID := range versionIDs {
|
||||
// A simple delete adds a marker and keeps the old version. The null-version
|
||||
// delete remains denied because its per-entry condition does not match.
|
||||
for _, objectName := range []string{"without-version-id-before", "without-version-id-after", "with-null-version-id"} {
|
||||
versionID := versionIDs[objectName]
|
||||
if _, err = obj.GetObjectInfo(t.Context(), bucketName, objectName, ObjectOptions{VersionID: versionID}); err != nil {
|
||||
t.Errorf("%s: version %s of %q was not preserved: %v", instanceType, versionID, objectName, err)
|
||||
}
|
||||
@@ -1063,7 +1113,10 @@ func testAPIDeleteMultipleObjectsVersionIDNullCondition(obj ObjectLayer, instanc
|
||||
t.Errorf("%s: simple delete of %q did not hide the latest object behind a delete marker: %v", instanceType, objectName, err)
|
||||
}
|
||||
}
|
||||
for _, objectName := range []string{"with-version-id", "with-null-version-id"} {
|
||||
if _, err = obj.GetObjectInfo(t.Context(), bucketName, "with-version-id", ObjectOptions{VersionID: versionIDs["with-version-id"]}); !isErrVersionNotFound(err) && !isErrObjectNotFound(err) {
|
||||
t.Errorf("%s: matching explicit version still exists: %v", instanceType, err)
|
||||
}
|
||||
for _, objectName := range []string{"with-null-version-id"} {
|
||||
if info, err := obj.GetObjectInfo(t.Context(), bucketName, objectName, ObjectOptions{}); err != nil {
|
||||
t.Errorf("%s: denied version delete removed latest %q: %v", instanceType, objectName, err)
|
||||
} else if info.VersionID != versionIDs[objectName] {
|
||||
|
||||
@@ -29,6 +29,7 @@ import (
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/minio-go/v7/pkg/set"
|
||||
"github.com/minio/minio-go/v7/pkg/tags"
|
||||
"github.com/minio/minio/internal/bucket/cors"
|
||||
bucketsse "github.com/minio/minio/internal/bucket/encryption"
|
||||
"github.com/minio/minio/internal/bucket/lifecycle"
|
||||
objectlock "github.com/minio/minio/internal/bucket/object/lock"
|
||||
@@ -50,6 +51,14 @@ type BucketMetadataSys struct {
|
||||
initialized bool
|
||||
group *singleflight.Group
|
||||
metadataMap map[string]BucketMetadata
|
||||
// loadFailed tracks real buckets whose metadata could not be loaded at
|
||||
// startup (concurrentLoad) or during a refresh. Such buckets are NOT
|
||||
// resident in metadataMap even though the subsystem is Initialized, so a
|
||||
// plain map miss cannot distinguish "not a bucket" from "known bucket whose
|
||||
// config we could not read". Callers that must fail closed for a real but
|
||||
// unreadable bucket (e.g. per-bucket CORS) consult this set. It is bounded
|
||||
// by the number of load failures and is empty in normal operation.
|
||||
loadFailed map[string]struct{}
|
||||
}
|
||||
|
||||
// Count returns number of bucket metadata map entries.
|
||||
@@ -66,6 +75,7 @@ func (sys *BucketMetadataSys) Remove(buckets ...string) {
|
||||
for _, bucket := range buckets {
|
||||
sys.group.Forget(bucket)
|
||||
delete(sys.metadataMap, bucket)
|
||||
delete(sys.loadFailed, bucket)
|
||||
globalBucketMonitor.DeleteBucket(bucket)
|
||||
}
|
||||
sys.Unlock()
|
||||
@@ -83,6 +93,11 @@ func (sys *BucketMetadataSys) RemoveStaleBuckets(diskBuckets set.StringSet) {
|
||||
delete(sys.metadataMap, bucket)
|
||||
globalBucketMonitor.DeleteBucket(bucket)
|
||||
}
|
||||
for bucket := range sys.loadFailed {
|
||||
if !diskBuckets.Contains(bucket) {
|
||||
delete(sys.loadFailed, bucket)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Set - sets a new metadata in-memory.
|
||||
@@ -94,6 +109,7 @@ func (sys *BucketMetadataSys) Set(bucket string, meta BucketMetadata) {
|
||||
if !isMinioMetaBucketName(bucket) {
|
||||
sys.Lock()
|
||||
sys.metadataMap[bucket] = meta
|
||||
delete(sys.loadFailed, bucket)
|
||||
sys.Unlock()
|
||||
}
|
||||
}
|
||||
@@ -134,6 +150,9 @@ func (sys *BucketMetadataSys) updateAndParse(ctx context.Context, bucket string,
|
||||
case bucketTaggingConfig:
|
||||
meta.TaggingConfigXML = configData
|
||||
meta.TaggingConfigUpdatedAt = updatedAt
|
||||
case bucketCorsConfig:
|
||||
meta.CorsConfigXML = configData
|
||||
meta.CorsConfigUpdatedAt = updatedAt
|
||||
case bucketQuotaConfigFile:
|
||||
meta.QuotaConfigJSON = configData
|
||||
meta.QuotaConfigUpdatedAt = updatedAt
|
||||
@@ -359,6 +378,98 @@ func (sys *BucketMetadataSys) GetSSEConfig(bucket string) (*bucketsse.BucketSSEC
|
||||
return meta.sseConfig, meta.EncryptionConfigUpdatedAt, nil
|
||||
}
|
||||
|
||||
// GetCorsConfig returns the CORS configuration for the given bucket.
|
||||
// The returned object must not be modified.
|
||||
func (sys *BucketMetadataSys) GetCorsConfig(bucket string) (*cors.Config, time.Time, error) {
|
||||
meta, _, err := sys.GetConfig(GlobalContext, bucket)
|
||||
if err != nil {
|
||||
return nil, time.Time{}, err
|
||||
}
|
||||
if meta.corsConfigErr != nil {
|
||||
return nil, meta.CorsConfigUpdatedAt, meta.corsConfigErr
|
||||
}
|
||||
if meta.corsConfig == nil {
|
||||
return nil, time.Time{}, errConfigNotFound
|
||||
}
|
||||
return meta.corsConfig, meta.CorsConfigUpdatedAt, nil
|
||||
}
|
||||
|
||||
// GetResidentCorsConfig returns the CORS configuration for the given bucket
|
||||
// using only bucket metadata that is already resident in memory. Unlike
|
||||
// GetCorsConfig it never loads metadata from disk and never caches a new
|
||||
// entry.
|
||||
//
|
||||
// The per-request CORS middleware runs before authentication, for every
|
||||
// Origin-bearing request, using the validated first path segment as the bucket
|
||||
// name.
|
||||
// Routing that through GetCorsConfig (which loads and caches) let an
|
||||
// unauthenticated client grow metadataMap without bound and trigger an
|
||||
// erasure metadata probe for every distinct, attacker-controlled,
|
||||
// non-existent name it sent with an Origin header (e.g. /minio/... , /api/... ,
|
||||
// or random buckets). Every bucket that can carry a CORS document is made
|
||||
// resident when the document is written (Set) and when metadata is loaded at
|
||||
// startup (Init/concurrentLoad), so a resident-only read is complete for real
|
||||
// buckets while costing only an in-memory map lookup for everything else.
|
||||
//
|
||||
// While bucket metadata is still loading (not yet Initialized) a non-resident
|
||||
// bucket returns errBucketMetadataNotInitialized so the caller fails closed
|
||||
// rather than answering with the permissive global policy for a bucket whose
|
||||
// restrictive CORS document may simply not be loaded yet.
|
||||
func (sys *BucketMetadataSys) GetResidentCorsConfig(bucket string) (*cors.Config, time.Time, error) {
|
||||
if isMinioMetaBucketName(bucket) {
|
||||
// Preserve GetConfig's semantics for the internal namespace: this is
|
||||
// not a real bucket, and returning a non-errConfigNotFound error makes
|
||||
// the CORS middleware fail closed rather than answer for .minio.sys
|
||||
// with the permissive global policy.
|
||||
return nil, time.Time{}, errInvalidArgument
|
||||
}
|
||||
if isReservedOrInvalidBucket(bucket, true) {
|
||||
return nil, time.Time{}, errConfigNotFound
|
||||
}
|
||||
sys.RLock()
|
||||
meta, ok := sys.metadataMap[bucket]
|
||||
_, failed := sys.loadFailed[bucket]
|
||||
initialized := sys.initialized
|
||||
sys.RUnlock()
|
||||
if ok {
|
||||
if meta.corsConfigErr != nil {
|
||||
return nil, meta.CorsConfigUpdatedAt, meta.corsConfigErr
|
||||
}
|
||||
if meta.corsConfig == nil {
|
||||
return nil, time.Time{}, errConfigNotFound
|
||||
}
|
||||
return meta.corsConfig, meta.CorsConfigUpdatedAt, nil
|
||||
}
|
||||
// Not resident. Two cases must not be conflated:
|
||||
// - metadata is still loading (!initialized), or this is a real bucket
|
||||
// whose metadata failed to load: we cannot rule out a restrictive CORS
|
||||
// config, so fail closed rather than answer with the global policy.
|
||||
// - a fully initialized subsystem with no record of the name: it is not a
|
||||
// bucket that can carry CORS, so fall back to the global policy without
|
||||
// loading or caching metadata for an arbitrary, client-supplied name.
|
||||
if !initialized || failed {
|
||||
return nil, time.Time{}, errBucketMetadataNotInitialized
|
||||
}
|
||||
return nil, time.Time{}, errConfigNotFound
|
||||
}
|
||||
|
||||
// GetCorsConfigXML returns the raw stored CORS configuration XML for the
|
||||
// given bucket, preserving the document exactly as it was PUT (including
|
||||
// the S3 xmlns and any unmodeled elements).
|
||||
func (sys *BucketMetadataSys) GetCorsConfigXML(bucket string) ([]byte, time.Time, error) {
|
||||
meta, _, err := sys.GetConfig(GlobalContext, bucket)
|
||||
if err != nil {
|
||||
return nil, time.Time{}, err
|
||||
}
|
||||
if meta.corsConfigErr != nil {
|
||||
return nil, meta.CorsConfigUpdatedAt, meta.corsConfigErr
|
||||
}
|
||||
if len(meta.CorsConfigXML) == 0 {
|
||||
return nil, time.Time{}, errConfigNotFound
|
||||
}
|
||||
return meta.CorsConfigXML, meta.CorsConfigUpdatedAt, nil
|
||||
}
|
||||
|
||||
// CreatedAt returns the time of creation of bucket
|
||||
func (sys *BucketMetadataSys) CreatedAt(bucket string) (time.Time, error) {
|
||||
meta, _, err := sys.GetConfig(GlobalContext, bucket)
|
||||
@@ -539,8 +650,13 @@ func (sys *BucketMetadataSys) concurrentLoad(ctx context.Context, buckets []stri
|
||||
sys.Lock()
|
||||
for i, meta := range bucketMetas {
|
||||
if errs[i] != nil {
|
||||
// Real bucket whose metadata could not be loaded: record it so
|
||||
// consumers that must fail closed (per-bucket CORS) can tell it
|
||||
// apart from a name that is not a bucket at all.
|
||||
sys.loadFailed[buckets[i]] = struct{}{}
|
||||
continue
|
||||
}
|
||||
delete(sys.loadFailed, buckets[i])
|
||||
sys.metadataMap[buckets[i]] = meta
|
||||
}
|
||||
sys.Unlock()
|
||||
@@ -590,6 +706,9 @@ func (sys *BucketMetadataSys) refreshBucketsMetadataLoop(ctx context.Context) {
|
||||
meta, err := loadBucketMetadata(ctx, sys.objAPI, bucket)
|
||||
if err != nil {
|
||||
internalLogIf(ctx, err, logger.WarningKind)
|
||||
sys.Lock()
|
||||
sys.loadFailed[bucket] = struct{}{}
|
||||
sys.Unlock()
|
||||
wait() // wait to proceed to next entry.
|
||||
continue
|
||||
}
|
||||
@@ -600,6 +719,8 @@ func (sys *BucketMetadataSys) refreshBucketsMetadataLoop(ctx context.Context) {
|
||||
updated = true
|
||||
sys.metadataMap[bucket] = meta
|
||||
}
|
||||
// A successful (re)load clears any earlier load failure.
|
||||
delete(sys.loadFailed, bucket)
|
||||
sys.Unlock()
|
||||
|
||||
if updated {
|
||||
@@ -647,6 +768,7 @@ func (sys *BucketMetadataSys) init(ctx context.Context, buckets []string) {
|
||||
func (sys *BucketMetadataSys) Reset() {
|
||||
sys.Lock()
|
||||
clear(sys.metadataMap)
|
||||
clear(sys.loadFailed)
|
||||
sys.Unlock()
|
||||
}
|
||||
|
||||
@@ -654,6 +776,7 @@ func (sys *BucketMetadataSys) Reset() {
|
||||
func NewBucketMetadataSys() *BucketMetadataSys {
|
||||
return &BucketMetadataSys{
|
||||
metadataMap: make(map[string]BucketMetadata),
|
||||
loadFailed: make(map[string]struct{}),
|
||||
group: &singleflight.Group{},
|
||||
}
|
||||
}
|
||||
|
||||
+40
-1
@@ -31,6 +31,7 @@ import (
|
||||
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/minio-go/v7/pkg/tags"
|
||||
"github.com/minio/minio/internal/bucket/cors"
|
||||
bucketsse "github.com/minio/minio/internal/bucket/encryption"
|
||||
"github.com/minio/minio/internal/bucket/lifecycle"
|
||||
objectlock "github.com/minio/minio/internal/bucket/object/lock"
|
||||
@@ -58,6 +59,9 @@ var (
|
||||
enabledBucketVersioningConfig = []byte(`<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Status>Enabled</Status></VersioningConfiguration>`)
|
||||
)
|
||||
|
||||
// Bucket CORS configuration file.
|
||||
const bucketCorsConfig = "cors.xml"
|
||||
|
||||
//go:generate msgp -file $GOFILE
|
||||
|
||||
// BucketMetadata contains bucket metadata.
|
||||
@@ -80,6 +84,7 @@ type BucketMetadata struct {
|
||||
ReplicationConfigXML []byte
|
||||
BucketTargetsConfigJSON []byte
|
||||
BucketTargetsConfigMetaJSON []byte
|
||||
CorsConfigXML []byte
|
||||
|
||||
PolicyConfigUpdatedAt time.Time
|
||||
ObjectLockConfigUpdatedAt time.Time
|
||||
@@ -92,6 +97,7 @@ type BucketMetadata struct {
|
||||
NotificationConfigUpdatedAt time.Time
|
||||
BucketTargetsConfigUpdatedAt time.Time
|
||||
BucketTargetsConfigMetaUpdatedAt time.Time
|
||||
CorsConfigUpdatedAt time.Time
|
||||
// Add a new UpdatedAt field and update lastUpdate function
|
||||
|
||||
// Unexported fields. Must be updated atomically.
|
||||
@@ -106,6 +112,8 @@ type BucketMetadata struct {
|
||||
replicationConfig *replication.Config
|
||||
bucketTargetConfig *madmin.BucketTargets
|
||||
bucketTargetConfigMeta map[string]string
|
||||
corsConfig *cors.Config
|
||||
corsConfigErr error
|
||||
}
|
||||
|
||||
// newBucketMetadata creates BucketMetadata with the supplied name and Created to Now.
|
||||
@@ -160,6 +168,9 @@ func (b BucketMetadata) lastUpdate() (t time.Time) {
|
||||
if b.BucketTargetsConfigMetaUpdatedAt.After(t) {
|
||||
t = b.BucketTargetsConfigMetaUpdatedAt
|
||||
}
|
||||
if b.CorsConfigUpdatedAt.After(t) {
|
||||
t = b.CorsConfigUpdatedAt
|
||||
}
|
||||
|
||||
return t
|
||||
}
|
||||
@@ -251,6 +262,12 @@ func loadBucketMetadataParse(ctx context.Context, objectAPI ObjectLayer, bucket
|
||||
return b, err
|
||||
}
|
||||
}
|
||||
if b.corsConfigErr != nil {
|
||||
// Keep the rest of the bucket metadata available so an operator can
|
||||
// replace or delete a CORS document accepted by an older, more lenient
|
||||
// build. Defer unrelated metadata migration until CORS is repaired.
|
||||
return b, nil
|
||||
}
|
||||
|
||||
// migrate unencrypted remote targets
|
||||
if err = b.migrateTargetConfig(ctx, objectAPI); err != nil {
|
||||
@@ -310,8 +327,27 @@ func (b *BucketMetadata) parseAllConfigs(ctx context.Context, objectAPI ObjectLa
|
||||
b.taggingConfig = nil
|
||||
}
|
||||
|
||||
b.corsConfigErr = nil
|
||||
if len(b.CorsConfigXML) != 0 {
|
||||
cfg, corsErr := cors.ParseBucketCorsConfig(bytes.NewReader(b.CorsConfigXML))
|
||||
if corsErr == nil {
|
||||
corsErr = cfg.Validate()
|
||||
}
|
||||
if corsErr != nil {
|
||||
b.corsConfig = nil
|
||||
b.corsConfigErr = fmt.Errorf("invalid bucket CORS configuration: %w", corsErr)
|
||||
} else {
|
||||
b.corsConfig = cfg
|
||||
}
|
||||
} else {
|
||||
b.corsConfig = nil
|
||||
}
|
||||
|
||||
if bytes.Equal(b.ObjectLockConfigXML, enabledBucketObjectLockConfig) {
|
||||
b.VersioningConfigXML = enabledBucketVersioningConfig
|
||||
config, versioningErr := versioning.ParseConfig(bytes.NewReader(b.VersioningConfigXML))
|
||||
if versioningErr != nil || !config.Enabled() {
|
||||
b.VersioningConfigXML = enabledBucketVersioningConfig
|
||||
}
|
||||
}
|
||||
|
||||
if len(b.ObjectLockConfigXML) != 0 {
|
||||
@@ -503,6 +539,9 @@ func (b *BucketMetadata) Save(ctx context.Context, api ObjectLayer) error {
|
||||
if err := b.parseAllConfigs(ctx, api); err != nil {
|
||||
return err
|
||||
}
|
||||
if b.corsConfigErr != nil {
|
||||
return b.corsConfigErr
|
||||
}
|
||||
|
||||
data := make([]byte, 4, b.Msgsize()+4)
|
||||
|
||||
|
||||
@@ -108,6 +108,12 @@ func (z *BucketMetadata) DecodeMsg(dc *msgp.Reader) (err error) {
|
||||
err = msgp.WrapError(err, "BucketTargetsConfigMetaJSON")
|
||||
return
|
||||
}
|
||||
case "CorsConfigXML":
|
||||
z.CorsConfigXML, err = dc.ReadBytes(z.CorsConfigXML)
|
||||
if err != nil {
|
||||
err = msgp.WrapError(err, "CorsConfigXML")
|
||||
return
|
||||
}
|
||||
case "PolicyConfigUpdatedAt":
|
||||
z.PolicyConfigUpdatedAt, err = dc.ReadTime()
|
||||
if err != nil {
|
||||
@@ -174,6 +180,12 @@ func (z *BucketMetadata) DecodeMsg(dc *msgp.Reader) (err error) {
|
||||
err = msgp.WrapError(err, "BucketTargetsConfigMetaUpdatedAt")
|
||||
return
|
||||
}
|
||||
case "CorsConfigUpdatedAt":
|
||||
z.CorsConfigUpdatedAt, err = dc.ReadTime()
|
||||
if err != nil {
|
||||
err = msgp.WrapError(err, "CorsConfigUpdatedAt")
|
||||
return
|
||||
}
|
||||
default:
|
||||
err = dc.Skip()
|
||||
if err != nil {
|
||||
@@ -187,9 +199,9 @@ func (z *BucketMetadata) DecodeMsg(dc *msgp.Reader) (err error) {
|
||||
|
||||
// EncodeMsg implements msgp.Encodable
|
||||
func (z *BucketMetadata) EncodeMsg(en *msgp.Writer) (err error) {
|
||||
// map header, size 25
|
||||
// map header, size 27
|
||||
// write "Name"
|
||||
err = en.Append(0xde, 0x0, 0x19, 0xa4, 0x4e, 0x61, 0x6d, 0x65)
|
||||
err = en.Append(0xde, 0x0, 0x1b, 0xa4, 0x4e, 0x61, 0x6d, 0x65)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
@@ -328,6 +340,16 @@ func (z *BucketMetadata) EncodeMsg(en *msgp.Writer) (err error) {
|
||||
err = msgp.WrapError(err, "BucketTargetsConfigMetaJSON")
|
||||
return
|
||||
}
|
||||
// write "CorsConfigXML"
|
||||
err = en.Append(0xad, 0x43, 0x6f, 0x72, 0x73, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x58, 0x4d, 0x4c)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = en.WriteBytes(z.CorsConfigXML)
|
||||
if err != nil {
|
||||
err = msgp.WrapError(err, "CorsConfigXML")
|
||||
return
|
||||
}
|
||||
// write "PolicyConfigUpdatedAt"
|
||||
err = en.Append(0xb5, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x41, 0x74)
|
||||
if err != nil {
|
||||
@@ -438,15 +460,25 @@ func (z *BucketMetadata) EncodeMsg(en *msgp.Writer) (err error) {
|
||||
err = msgp.WrapError(err, "BucketTargetsConfigMetaUpdatedAt")
|
||||
return
|
||||
}
|
||||
// write "CorsConfigUpdatedAt"
|
||||
err = en.Append(0xb3, 0x43, 0x6f, 0x72, 0x73, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x41, 0x74)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
err = en.WriteTime(z.CorsConfigUpdatedAt)
|
||||
if err != nil {
|
||||
err = msgp.WrapError(err, "CorsConfigUpdatedAt")
|
||||
return
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
// MarshalMsg implements msgp.Marshaler
|
||||
func (z *BucketMetadata) MarshalMsg(b []byte) (o []byte, err error) {
|
||||
o = msgp.Require(b, z.Msgsize())
|
||||
// map header, size 25
|
||||
// map header, size 27
|
||||
// string "Name"
|
||||
o = append(o, 0xde, 0x0, 0x19, 0xa4, 0x4e, 0x61, 0x6d, 0x65)
|
||||
o = append(o, 0xde, 0x0, 0x1b, 0xa4, 0x4e, 0x61, 0x6d, 0x65)
|
||||
o = msgp.AppendString(o, z.Name)
|
||||
// string "Created"
|
||||
o = append(o, 0xa7, 0x43, 0x72, 0x65, 0x61, 0x74, 0x65, 0x64)
|
||||
@@ -487,6 +519,9 @@ func (z *BucketMetadata) MarshalMsg(b []byte) (o []byte, err error) {
|
||||
// string "BucketTargetsConfigMetaJSON"
|
||||
o = append(o, 0xbb, 0x42, 0x75, 0x63, 0x6b, 0x65, 0x74, 0x54, 0x61, 0x72, 0x67, 0x65, 0x74, 0x73, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x4d, 0x65, 0x74, 0x61, 0x4a, 0x53, 0x4f, 0x4e)
|
||||
o = msgp.AppendBytes(o, z.BucketTargetsConfigMetaJSON)
|
||||
// string "CorsConfigXML"
|
||||
o = append(o, 0xad, 0x43, 0x6f, 0x72, 0x73, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x58, 0x4d, 0x4c)
|
||||
o = msgp.AppendBytes(o, z.CorsConfigXML)
|
||||
// string "PolicyConfigUpdatedAt"
|
||||
o = append(o, 0xb5, 0x50, 0x6f, 0x6c, 0x69, 0x63, 0x79, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x41, 0x74)
|
||||
o = msgp.AppendTime(o, z.PolicyConfigUpdatedAt)
|
||||
@@ -520,6 +555,9 @@ func (z *BucketMetadata) MarshalMsg(b []byte) (o []byte, err error) {
|
||||
// string "BucketTargetsConfigMetaUpdatedAt"
|
||||
o = append(o, 0xd9, 0x20, 0x42, 0x75, 0x63, 0x6b, 0x65, 0x74, 0x54, 0x61, 0x72, 0x67, 0x65, 0x74, 0x73, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x4d, 0x65, 0x74, 0x61, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x41, 0x74)
|
||||
o = msgp.AppendTime(o, z.BucketTargetsConfigMetaUpdatedAt)
|
||||
// string "CorsConfigUpdatedAt"
|
||||
o = append(o, 0xb3, 0x43, 0x6f, 0x72, 0x73, 0x43, 0x6f, 0x6e, 0x66, 0x69, 0x67, 0x55, 0x70, 0x64, 0x61, 0x74, 0x65, 0x64, 0x41, 0x74)
|
||||
o = msgp.AppendTime(o, z.CorsConfigUpdatedAt)
|
||||
return
|
||||
}
|
||||
|
||||
@@ -625,6 +663,12 @@ func (z *BucketMetadata) UnmarshalMsg(bts []byte) (o []byte, err error) {
|
||||
err = msgp.WrapError(err, "BucketTargetsConfigMetaJSON")
|
||||
return
|
||||
}
|
||||
case "CorsConfigXML":
|
||||
z.CorsConfigXML, bts, err = msgp.ReadBytesBytes(bts, z.CorsConfigXML)
|
||||
if err != nil {
|
||||
err = msgp.WrapError(err, "CorsConfigXML")
|
||||
return
|
||||
}
|
||||
case "PolicyConfigUpdatedAt":
|
||||
z.PolicyConfigUpdatedAt, bts, err = msgp.ReadTimeBytes(bts)
|
||||
if err != nil {
|
||||
@@ -691,6 +735,12 @@ func (z *BucketMetadata) UnmarshalMsg(bts []byte) (o []byte, err error) {
|
||||
err = msgp.WrapError(err, "BucketTargetsConfigMetaUpdatedAt")
|
||||
return
|
||||
}
|
||||
case "CorsConfigUpdatedAt":
|
||||
z.CorsConfigUpdatedAt, bts, err = msgp.ReadTimeBytes(bts)
|
||||
if err != nil {
|
||||
err = msgp.WrapError(err, "CorsConfigUpdatedAt")
|
||||
return
|
||||
}
|
||||
default:
|
||||
bts, err = msgp.Skip(bts)
|
||||
if err != nil {
|
||||
@@ -705,6 +755,6 @@ func (z *BucketMetadata) UnmarshalMsg(bts []byte) (o []byte, err error) {
|
||||
|
||||
// Msgsize returns an upper bound estimate of the number of bytes occupied by the serialized message
|
||||
func (z *BucketMetadata) Msgsize() (s int) {
|
||||
s = 3 + 5 + msgp.StringPrefixSize + len(z.Name) + 8 + msgp.TimeSize + 12 + msgp.BoolSize + 17 + msgp.BytesPrefixSize + len(z.PolicyConfigJSON) + 22 + msgp.BytesPrefixSize + len(z.NotificationConfigXML) + 19 + msgp.BytesPrefixSize + len(z.LifecycleConfigXML) + 20 + msgp.BytesPrefixSize + len(z.ObjectLockConfigXML) + 20 + msgp.BytesPrefixSize + len(z.VersioningConfigXML) + 20 + msgp.BytesPrefixSize + len(z.EncryptionConfigXML) + 17 + msgp.BytesPrefixSize + len(z.TaggingConfigXML) + 16 + msgp.BytesPrefixSize + len(z.QuotaConfigJSON) + 21 + msgp.BytesPrefixSize + len(z.ReplicationConfigXML) + 24 + msgp.BytesPrefixSize + len(z.BucketTargetsConfigJSON) + 28 + msgp.BytesPrefixSize + len(z.BucketTargetsConfigMetaJSON) + 22 + msgp.TimeSize + 26 + msgp.TimeSize + 26 + msgp.TimeSize + 23 + msgp.TimeSize + 21 + msgp.TimeSize + 27 + msgp.TimeSize + 26 + msgp.TimeSize + 25 + msgp.TimeSize + 28 + msgp.TimeSize + 29 + msgp.TimeSize + 34 + msgp.TimeSize
|
||||
s = 3 + 5 + msgp.StringPrefixSize + len(z.Name) + 8 + msgp.TimeSize + 12 + msgp.BoolSize + 17 + msgp.BytesPrefixSize + len(z.PolicyConfigJSON) + 22 + msgp.BytesPrefixSize + len(z.NotificationConfigXML) + 19 + msgp.BytesPrefixSize + len(z.LifecycleConfigXML) + 20 + msgp.BytesPrefixSize + len(z.ObjectLockConfigXML) + 20 + msgp.BytesPrefixSize + len(z.VersioningConfigXML) + 20 + msgp.BytesPrefixSize + len(z.EncryptionConfigXML) + 17 + msgp.BytesPrefixSize + len(z.TaggingConfigXML) + 16 + msgp.BytesPrefixSize + len(z.QuotaConfigJSON) + 21 + msgp.BytesPrefixSize + len(z.ReplicationConfigXML) + 24 + msgp.BytesPrefixSize + len(z.BucketTargetsConfigJSON) + 28 + msgp.BytesPrefixSize + len(z.BucketTargetsConfigMetaJSON) + 14 + msgp.BytesPrefixSize + len(z.CorsConfigXML) + 22 + msgp.TimeSize + 26 + msgp.TimeSize + 26 + msgp.TimeSize + 23 + msgp.TimeSize + 21 + msgp.TimeSize + 27 + msgp.TimeSize + 26 + msgp.TimeSize + 25 + msgp.TimeSize + 28 + msgp.TimeSize + 29 + msgp.TimeSize + 34 + msgp.TimeSize + 20 + msgp.TimeSize
|
||||
return
|
||||
}
|
||||
|
||||
@@ -0,0 +1,41 @@
|
||||
// Copyright (c) 2015-2026 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestBucketMetadataCorsRoundTrip(t *testing.T) {
|
||||
meta := newBucketMetadata("test-cors")
|
||||
meta.CorsConfigXML = []byte(`<CORSConfiguration><CORSRule><AllowedOrigin>*</AllowedOrigin><AllowedMethod>GET</AllowedMethod></CORSRule></CORSConfiguration>`)
|
||||
meta.CorsConfigUpdatedAt = UTCNow()
|
||||
|
||||
buf, err := meta.MarshalMsg(nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var got BucketMetadata
|
||||
if _, err := got.UnmarshalMsg(buf); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(got.CorsConfigXML) != string(meta.CorsConfigXML) {
|
||||
t.Fatalf("CorsConfigXML not preserved: %q", string(got.CorsConfigXML))
|
||||
}
|
||||
if !got.CorsConfigUpdatedAt.Equal(meta.CorsConfigUpdatedAt) {
|
||||
t.Fatalf("CorsConfigUpdatedAt not preserved")
|
||||
}
|
||||
}
|
||||
+12
-12
@@ -25,8 +25,6 @@ import (
|
||||
|
||||
"github.com/minio/minio/internal/auth"
|
||||
objectlock "github.com/minio/minio/internal/bucket/object/lock"
|
||||
"github.com/minio/minio/internal/bucket/replication"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
"github.com/minio/minio/internal/logger"
|
||||
"github.com/minio/pkg/v3/policy"
|
||||
)
|
||||
@@ -150,7 +148,11 @@ func enforceRetentionBypassForDelete(ctx context.Context, r *http.Request, bucke
|
||||
}
|
||||
// https://docs.aws.amazon.com/AmazonS3/latest/dev/object-lock-overview.html#object-lock-retention-modes
|
||||
// If you try to delete objects protected by governance mode and have s3:BypassGovernanceRetention, the operation will succeed.
|
||||
if checkRequestAuthType(ctx, r, policy.BypassGovernanceRetentionAction, bucket, object.ObjectName) != ErrNone {
|
||||
if reqInfo := logger.GetReqInfo(ctx); reqInfo != nil {
|
||||
reqInfo.BucketName = bucket
|
||||
reqInfo.ObjectName = object.ObjectName
|
||||
}
|
||||
if authorizeRequest(ctx, r, policy.BypassGovernanceRetentionAction) != ErrNone {
|
||||
return errAuthentication
|
||||
}
|
||||
}
|
||||
@@ -198,7 +200,7 @@ func enforceRetentionBypassForPut(ctx context.Context, r *http.Request, oi Objec
|
||||
byPassSet, r, cred, owner)
|
||||
// Governance mode retention period cannot be shortened, if x-amz-bypass-governance is not set.
|
||||
if !byPassSet {
|
||||
if objRetention.Mode != objectlock.RetGovernance || objRetention.RetainUntilDate.Before((ret.RetainUntilDate.Time)) {
|
||||
if objRetention.Mode != objectlock.RetGovernance || objRetention.RetainUntilDate.Before(ret.RetainUntilDate.Time) {
|
||||
return ObjectLocked{Bucket: oi.Bucket, Object: oi.Name, VersionID: oi.VersionID}
|
||||
}
|
||||
}
|
||||
@@ -209,7 +211,7 @@ func enforceRetentionBypassForPut(ctx context.Context, r *http.Request, oi Objec
|
||||
case objectlock.RetCompliance:
|
||||
// Compliance retention mode cannot be changed or shortened.
|
||||
// https://docs.aws.amazon.com/AmazonS3/latest/dev/object-lock-overview.html#object-lock-retention-modes
|
||||
if objRetention.Mode != objectlock.RetCompliance || objRetention.RetainUntilDate.Before((ret.RetainUntilDate.Time)) {
|
||||
if objRetention.Mode != objectlock.RetCompliance || objRetention.RetainUntilDate.Before(ret.RetainUntilDate.Time) {
|
||||
return ObjectLocked{Bucket: oi.Bucket, Object: oi.Name, VersionID: oi.VersionID}
|
||||
}
|
||||
apiErr := isPutRetentionAllowed(oi.Bucket, oi.Name,
|
||||
@@ -242,7 +244,7 @@ func enforceRetentionBypassForPut(ctx context.Context, r *http.Request, oi Objec
|
||||
// For objects in "Compliance" mode, retention date cannot be shortened, and mode cannot be altered.
|
||||
// For objects with legal hold header set, the s3:PutObjectLegalHold permission is expected to be set
|
||||
// Both legal hold and retention can be applied independently on an object
|
||||
func checkPutObjectLockAllowed(ctx context.Context, rq *http.Request, bucket, object string, getObjectInfoFn GetObjectInfoFn, retentionPermErr, legalHoldPermErr APIErrorCode) (objectlock.RetMode, objectlock.RetentionDate, objectlock.ObjectLegalHold, APIErrorCode) {
|
||||
func checkPutObjectLockAllowed(ctx context.Context, rq *http.Request, bucket, object string, getObjectInfoFn GetObjectInfoFn, retentionPermErr, legalHoldPermErr APIErrorCode, replicaTrusted bool) (objectlock.RetMode, objectlock.RetentionDate, objectlock.ObjectLegalHold, APIErrorCode) {
|
||||
var mode objectlock.RetMode
|
||||
var retainDate objectlock.RetentionDate
|
||||
var legalHold objectlock.ObjectLegalHold
|
||||
@@ -269,9 +271,7 @@ func checkPutObjectLockAllowed(ctx context.Context, rq *http.Request, bucket, ob
|
||||
return mode, retainDate, legalHold, toAPIErrorCode(ctx, err)
|
||||
}
|
||||
|
||||
replica := rq.Header.Get(xhttp.AmzBucketReplicationStatus) == replication.Replica.String()
|
||||
|
||||
if opts.VersionID != "" && !replica {
|
||||
if opts.VersionID != "" && !replicaTrusted {
|
||||
if objInfo, err := getObjectInfoFn(ctx, bucket, object, opts); err == nil {
|
||||
r := objectlock.GetObjectRetentionMeta(objInfo.UserDefined)
|
||||
t, err := objectlock.UTCNowNTP()
|
||||
@@ -307,8 +307,8 @@ func checkPutObjectLockAllowed(ctx context.Context, rq *http.Request, bucket, ob
|
||||
if err != nil {
|
||||
return mode, retainDate, legalHold, toAPIErrorCode(ctx, err)
|
||||
}
|
||||
rMode, rDate, err := objectlock.ParseObjectLockRetentionHeaders(rq.Header)
|
||||
if err != nil && (!replica || rMode != "" || !rDate.IsZero()) {
|
||||
rMode, rDate, err := objectlock.ParseObjectLockRetentionHeaders(rq.Header, replicaTrusted)
|
||||
if err != nil && (!replicaTrusted || rMode != "" || !rDate.IsZero()) {
|
||||
return mode, retainDate, legalHold, toAPIErrorCode(ctx, err)
|
||||
}
|
||||
if retentionPermErr != ErrNone {
|
||||
@@ -316,7 +316,7 @@ func checkPutObjectLockAllowed(ctx context.Context, rq *http.Request, bucket, ob
|
||||
}
|
||||
return rMode, rDate, legalHold, ErrNone
|
||||
}
|
||||
if replica { // replica inherits retention metadata only from source
|
||||
if replicaTrusted { // replica inherits retention metadata only from source
|
||||
return "", objectlock.RetentionDate{}, legalHold, ErrNone
|
||||
}
|
||||
if !retentionRequested && retentionCfg.Validity > 0 {
|
||||
|
||||
@@ -617,7 +617,7 @@ func (api objectAPIHandlers) ValidateBucketReplicationCredsHandler(w http.Respon
|
||||
ReplicationValidityCheck: true, // set this to validate the replication config
|
||||
},
|
||||
}
|
||||
obj := path.Join(minioReservedBucket, globalLocalNodeNameHex, "deleteme")
|
||||
obj := replicationValidationObject(rule)
|
||||
ui, err := c.PutObject(ctx, clnt.Bucket, obj, reader, int64(len(buf)), "", "", putOpts)
|
||||
if err != nil && !isReplicationPermissionCheck(ErrorRespToObjectError(err, bucket, obj)) {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErrWithErr(ErrReplicationValidationError, fmt.Errorf("s3:ReplicateObject permissions missing for replication user: %w", err)), r.URL)
|
||||
@@ -658,3 +658,7 @@ func (api objectAPIHandlers) ValidateBucketReplicationCredsHandler(w http.Respon
|
||||
// Write success response.
|
||||
writeSuccessResponseHeadersOnly(w)
|
||||
}
|
||||
|
||||
func replicationValidationObject(rule replication.Rule) string {
|
||||
return path.Join(rule.Prefix(), minioReservedBucket, globalLocalNodeNameHex, "deleteme")
|
||||
}
|
||||
|
||||
@@ -20,6 +20,7 @@ package cmd
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"path"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
@@ -287,3 +288,22 @@ func TestReplicationResyncwrapper(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplicationValidationObjectUsesRulePrefix(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
rule replication.Rule
|
||||
want string
|
||||
}{
|
||||
{name: "empty prefix", rule: replication.Rule{}, want: path.Join(minioReservedBucket, globalLocalNodeNameHex, "deleteme")},
|
||||
{name: "filter prefix", rule: replication.Rule{Filter: replication.Filter{Prefix: "data/"}}, want: path.Join("data", minioReservedBucket, globalLocalNodeNameHex, "deleteme")},
|
||||
{name: "and prefix", rule: replication.Rule{Filter: replication.Filter{And: replication.And{Prefix: "archive/"}}}, want: path.Join("archive", minioReservedBucket, globalLocalNodeNameHex, "deleteme")},
|
||||
}
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
if got := replicationValidationObject(test.rule); got != test.want {
|
||||
t.Fatalf("replicationValidationObject() = %q, want %q", got, test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
+45
-8
@@ -36,6 +36,8 @@ import (
|
||||
"strings"
|
||||
"syscall"
|
||||
"time"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
fcolor "github.com/fatih/color"
|
||||
@@ -540,6 +542,30 @@ func (e envKV) String() string {
|
||||
return fmt.Sprintf("%s=%s", e.Key, e.Value)
|
||||
}
|
||||
|
||||
func isValidEnvName(name string) bool {
|
||||
if name == "" || !utf8.ValidString(name) {
|
||||
return false
|
||||
}
|
||||
for _, ch := range name {
|
||||
if ch == '=' || unicode.IsSpace(ch) || !unicode.IsGraphic(ch) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func trimExportPrefix(envEntry string) string {
|
||||
rest, ok := strings.CutPrefix(envEntry, "export")
|
||||
if !ok || rest == "" {
|
||||
return envEntry
|
||||
}
|
||||
trimmed := strings.TrimLeftFunc(rest, unicode.IsSpace)
|
||||
if len(trimmed) == len(rest) {
|
||||
return envEntry
|
||||
}
|
||||
return trimmed
|
||||
}
|
||||
|
||||
func parsEnvEntry(envEntry string) (envKV, error) {
|
||||
envEntry = strings.TrimSpace(envEntry)
|
||||
if envEntry == "" {
|
||||
@@ -554,13 +580,19 @@ func parsEnvEntry(envEntry string) (envKV, error) {
|
||||
Skip: true,
|
||||
}, nil
|
||||
}
|
||||
envTokens := strings.SplitN(strings.TrimSpace(strings.TrimPrefix(envEntry, "export")), config.EnvSeparator, 2)
|
||||
envTokens := strings.SplitN(trimExportPrefix(envEntry), config.EnvSeparator, 2)
|
||||
if len(envTokens) != 2 {
|
||||
return envKV{}, fmt.Errorf("envEntry malformed; %s, expected to be of form 'KEY=value'", envEntry)
|
||||
return envKV{}, errors.New("missing '='")
|
||||
}
|
||||
|
||||
key := envTokens[0]
|
||||
val := envTokens[1]
|
||||
key := strings.TrimSpace(envTokens[0])
|
||||
val := strings.TrimSpace(envTokens[1])
|
||||
if !isValidEnvName(key) {
|
||||
return envKV{}, fmt.Errorf("invalid environment variable name %q", key)
|
||||
}
|
||||
if strings.IndexByte(val, 0) >= 0 {
|
||||
return envKV{}, errors.New("environment variable value contains NUL")
|
||||
}
|
||||
|
||||
// Remove quotes from the value if found
|
||||
if len(val) >= 2 {
|
||||
@@ -587,10 +619,12 @@ func minioEnvironFromFile(envConfigFile string) ([]envKV, error) {
|
||||
defer f.Close()
|
||||
var ekvs []envKV
|
||||
scanner := bufio.NewScanner(f)
|
||||
lineNo := 0
|
||||
for scanner.Scan() {
|
||||
lineNo++
|
||||
ekv, err := parsEnvEntry(scanner.Text())
|
||||
if err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("%s:%d: %w", envConfigFile, lineNo, err)
|
||||
}
|
||||
if ekv.Skip {
|
||||
// Skips empty lines
|
||||
@@ -599,7 +633,7 @@ func minioEnvironFromFile(envConfigFile string) ([]envKV, error) {
|
||||
ekvs = append(ekvs, ekv)
|
||||
}
|
||||
if err = scanner.Err(); err != nil {
|
||||
return nil, err
|
||||
return nil, fmt.Errorf("%s: %w", envConfigFile, err)
|
||||
}
|
||||
return ekvs, nil
|
||||
}
|
||||
@@ -666,12 +700,15 @@ func loadEnvVarsFromFiles() {
|
||||
}
|
||||
|
||||
if env.IsSet(config.EnvConfigEnvFile) {
|
||||
ekvs, err := minioEnvironFromFile(env.Get(config.EnvConfigEnvFile, ""))
|
||||
envConfigFile := env.Get(config.EnvConfigEnvFile, "")
|
||||
ekvs, err := minioEnvironFromFile(envConfigFile)
|
||||
if err != nil && !os.IsNotExist(err) {
|
||||
logger.Fatal(err, "Unable to read the config environment file")
|
||||
}
|
||||
for _, ekv := range ekvs {
|
||||
os.Setenv(ekv.Key, ekv.Value)
|
||||
if err := os.Setenv(ekv.Key, ekv.Value); err != nil {
|
||||
logger.Fatal(err, "Unable to set %s from config environment file %s", ekv.Key, envConfigFile)
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -19,9 +19,14 @@ package cmd
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
"reflect"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/minio/minio/internal/config"
|
||||
)
|
||||
|
||||
func Test_readFromSecret(t *testing.T) {
|
||||
@@ -181,3 +186,189 @@ MINIO_ROOT_PASSWORD=minio123`,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func Test_minioEnvironFromFileWhitespaceAndValidation(t *testing.T) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
content string
|
||||
want []envKV
|
||||
errLine int
|
||||
errContains string
|
||||
errExcludes string
|
||||
}{
|
||||
{
|
||||
name: "spaces and tabs around separator",
|
||||
content: "MINIO_ROOT_USER = minio\nMINIO_ROOT_PASSWORD\t=\tminio123",
|
||||
want: []envKV{
|
||||
{Key: "MINIO_ROOT_USER", Value: "minio"},
|
||||
{Key: "MINIO_ROOT_PASSWORD", Value: "minio123"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "export tab and quoted spaces",
|
||||
content: "export\tMINIO_ROOT_USER = \" minio user \"\nexport MINIO_ROOT_PASSWORD = ' minio secret '",
|
||||
want: []envKV{
|
||||
{Key: "MINIO_ROOT_USER", Value: " minio user "},
|
||||
{Key: "MINIO_ROOT_PASSWORD", Value: " minio secret "},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "export Unicode whitespace",
|
||||
content: "export\u00a0MINIO_ROOT_USER=value",
|
||||
want: []envKV{
|
||||
{Key: "MINIO_ROOT_USER", Value: "value"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "export is only a standalone prefix",
|
||||
content: "export=value\nexportFOO=bar",
|
||||
want: []envKV{
|
||||
{Key: "export", Value: "value"},
|
||||
{Key: "exportFOO", Value: "bar"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "unquoted whitespace empty value and additional separators",
|
||||
content: "UNQUOTED = value \nEMPTY =\nTOKEN = scheme://user:password@example.com?a=b",
|
||||
want: []envKV{
|
||||
{Key: "UNQUOTED", Value: "value"},
|
||||
{Key: "EMPTY", Value: ""},
|
||||
{Key: "TOKEN", Value: "scheme://user:password@example.com?a=b"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "valid underscore and digits",
|
||||
content: "_VALID_2=value",
|
||||
want: []envKV{
|
||||
{Key: "_VALID_2", Value: "value"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "named target punctuation and unicode",
|
||||
content: "MINIO_NOTIFY_WEBHOOK_ENABLE_my-hook=off\n" +
|
||||
"MINIO_NOTIFY_WEBHOOK_ENABLE_site.eu=off\n" +
|
||||
"MINIO_NOTIFY_WEBHOOK_ENABLE_team:blue=off\n" +
|
||||
"MINIO_NOTIFY_WEBHOOK_ENABLE_目标=off",
|
||||
want: []envKV{
|
||||
{Key: "MINIO_NOTIFY_WEBHOOK_ENABLE_my-hook", Value: "off"},
|
||||
{Key: "MINIO_NOTIFY_WEBHOOK_ENABLE_site.eu", Value: "off"},
|
||||
{Key: "MINIO_NOTIFY_WEBHOOK_ENABLE_team:blue", Value: "off"},
|
||||
{Key: "MINIO_NOTIFY_WEBHOOK_ENABLE_目标", Value: "off"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "missing separator redacts the line",
|
||||
content: "MINIO_ROOT_PASSWORD=valid\nsuper-secret-without-equals",
|
||||
errLine: 2,
|
||||
errContains: "missing '='",
|
||||
errExcludes: "super-secret-without-equals",
|
||||
},
|
||||
{
|
||||
name: "empty name",
|
||||
content: "=empty-name-secret",
|
||||
errLine: 1,
|
||||
errContains: `invalid environment variable name ""`,
|
||||
errExcludes: "empty-name-secret",
|
||||
},
|
||||
{
|
||||
name: "os compatible leading digit and punctuation",
|
||||
content: "1MINIO_ROOT_USER=digit-leading-secret\n-MINIO-ROOT-USER=hyphen-secret",
|
||||
want: []envKV{
|
||||
{Key: "1MINIO_ROOT_USER", Value: "digit-leading-secret"},
|
||||
{Key: "-MINIO-ROOT-USER", Value: "hyphen-secret"},
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "whitespace in name",
|
||||
content: "MINIO ROOT USER=whitespace-secret",
|
||||
errLine: 1,
|
||||
errContains: `invalid environment variable name "MINIO ROOT USER"`,
|
||||
errExcludes: "whitespace-secret",
|
||||
},
|
||||
{
|
||||
name: "NUL in name",
|
||||
content: "MINIO\x00ROOT=nul-name-secret",
|
||||
errLine: 1,
|
||||
errContains: "invalid environment variable name",
|
||||
errExcludes: "nul-name-secret",
|
||||
},
|
||||
{
|
||||
name: "format character in name",
|
||||
content: "MINIO\u200bROOT=format-secret",
|
||||
errLine: 1,
|
||||
errContains: "invalid environment variable name",
|
||||
errExcludes: "format-secret",
|
||||
},
|
||||
{
|
||||
name: "NUL in value",
|
||||
content: "MINIO_ROOT_USER=before\x00nul-value-secret",
|
||||
errLine: 1,
|
||||
errContains: "environment variable value contains NUL",
|
||||
errExcludes: "nul-value-secret",
|
||||
},
|
||||
{
|
||||
name: "diagnostic has file and line but no value",
|
||||
content: "MINIO_ROOT_USER=valid\nBAD KEY=super-secret-value",
|
||||
errLine: 2,
|
||||
errContains: `invalid environment variable name "BAD KEY"`,
|
||||
errExcludes: "super-secret-value",
|
||||
},
|
||||
}
|
||||
|
||||
for _, testCase := range testCases {
|
||||
t.Run(testCase.name, func(t *testing.T) {
|
||||
tmpfile, err := os.CreateTemp(t.TempDir(), "testfile")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err = tmpfile.WriteString(testCase.content); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = tmpfile.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
got, err := minioEnvironFromFile(tmpfile.Name())
|
||||
if testCase.errContains == "" {
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !reflect.DeepEqual(got, testCase.want) {
|
||||
t.Errorf("expected %v, got %v", testCase.want, got)
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
if err == nil {
|
||||
t.Fatal("expected an error")
|
||||
}
|
||||
errText := err.Error()
|
||||
location := fmt.Sprintf("%s:%d:", tmpfile.Name(), testCase.errLine)
|
||||
if !strings.Contains(errText, location) {
|
||||
t.Errorf("expected error to contain %q, got %q", location, errText)
|
||||
}
|
||||
if !strings.Contains(errText, testCase.errContains) {
|
||||
t.Errorf("expected error to contain %q, got %q", testCase.errContains, errText)
|
||||
}
|
||||
if testCase.errExcludes != "" && strings.Contains(errText, testCase.errExcludes) {
|
||||
t.Errorf("expected error to redact %q, got %q", testCase.errExcludes, errText)
|
||||
}
|
||||
if got != nil {
|
||||
t.Errorf("expected no entries on parse error, got %v", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestConfigEnvFileNamedTargetDiscovery(t *testing.T) {
|
||||
key := "MINIO_NOTIFY_WEBHOOK_ENABLE_my-hook"
|
||||
t.Setenv(key, "off")
|
||||
|
||||
targets, err := (config.Config{}).GetAvailableTargets(config.NotifyWebhookSubSys)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !slices.Contains(targets, "my-hook") {
|
||||
t.Fatalf("named target %q not discovered from %s: %v", "my-hook", key, targets)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -167,7 +167,9 @@ func readConfigWithoutMigrate(ctx context.Context, objAPI ObjectLayer) (config.C
|
||||
notify.SetNotifyMQTT(newCfg, k, args)
|
||||
}
|
||||
for k, args := range cfg.Notify.MySQL {
|
||||
notify.SetNotifyMySQL(newCfg, k, args)
|
||||
if err := notify.SetNotifyMySQL(newCfg, k, args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for k, args := range cfg.Notify.NATS {
|
||||
notify.SetNotifyNATS(newCfg, k, args)
|
||||
@@ -176,7 +178,9 @@ func readConfigWithoutMigrate(ctx context.Context, objAPI ObjectLayer) (config.C
|
||||
notify.SetNotifyNSQ(newCfg, k, args)
|
||||
}
|
||||
for k, args := range cfg.Notify.PostgreSQL {
|
||||
notify.SetNotifyPostgres(newCfg, k, args)
|
||||
if err := notify.SetNotifyPostgres(newCfg, k, args); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
for k, args := range cfg.Notify.Redis {
|
||||
notify.SetNotifyRedis(newCfg, k, args)
|
||||
|
||||
@@ -0,0 +1,264 @@
|
||||
// Copyright (c) 2015-2026 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"os"
|
||||
"reflect"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/minio/minio/internal/config"
|
||||
"github.com/minio/minio/internal/config/notify"
|
||||
"github.com/minio/minio/internal/event/target"
|
||||
)
|
||||
|
||||
func installLegacyConfigFile(t *testing.T, configure func(*serverConfigV33)) (string, []byte) {
|
||||
t.Helper()
|
||||
|
||||
cfg := &serverConfigV33{
|
||||
Version: "33",
|
||||
Notify: notify.NewConfig(),
|
||||
}
|
||||
configure(cfg)
|
||||
|
||||
data, err := json.Marshal(cfg)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
oldConfigDir := globalConfigDir
|
||||
globalConfigDir = &ConfigDir{path: t.TempDir()}
|
||||
t.Cleanup(func() { globalConfigDir = oldConfigDir })
|
||||
|
||||
configFile := getConfigFile()
|
||||
if err = os.WriteFile(configFile, data, 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return configFile, data
|
||||
}
|
||||
|
||||
func assertLegacyMigrationError(t *testing.T, err error, subsystem, name, key, secret string) {
|
||||
t.Helper()
|
||||
var targetErr *notify.LegacyDatabaseTargetError
|
||||
if !errors.As(err, &targetErr) {
|
||||
t.Fatalf("error = %v, want *notify.LegacyDatabaseTargetError", err)
|
||||
}
|
||||
msg := err.Error()
|
||||
for _, want := range []string{subsystem + config.SubSystemSeparator + name, key} {
|
||||
if !strings.Contains(msg, want) {
|
||||
t.Errorf("error %q does not contain %q", msg, want)
|
||||
}
|
||||
}
|
||||
if strings.Contains(msg, secret) {
|
||||
t.Errorf("migration error leaks database password %q: %s", secret, msg)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadConfigWithoutMigrateRejectsLegacyDatabaseTargets(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
subsystem string
|
||||
key string
|
||||
secret string
|
||||
configure func(*serverConfigV33)
|
||||
}{
|
||||
{
|
||||
name: "postgres",
|
||||
subsystem: config.NotifyPostgresSubSys,
|
||||
key: target.PostgresConnectionString,
|
||||
secret: "postgres-migration-secret",
|
||||
configure: func(cfg *serverConfigV33) {
|
||||
cfg.Notify.PostgreSQL["archive"] = target.PostgreSQLArgs{
|
||||
Enable: true,
|
||||
Port: "5432",
|
||||
Username: "legacy-user",
|
||||
Password: "postgres-migration-secret",
|
||||
Database: "events",
|
||||
}
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "mysql",
|
||||
subsystem: config.NotifyMySQLSubSys,
|
||||
key: target.MySQLDSNString,
|
||||
secret: "mysql-migration-secret",
|
||||
configure: func(cfg *serverConfigV33) {
|
||||
cfg.Notify.MySQL["archive"] = target.MySQLArgs{
|
||||
Enable: true,
|
||||
Port: "3306",
|
||||
User: "legacy-user",
|
||||
Password: "mysql-migration-secret",
|
||||
Database: "events",
|
||||
}
|
||||
},
|
||||
},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
configFile, original := installLegacyConfigFile(t, test.configure)
|
||||
got, err := readConfigWithoutMigrate(t.Context(), nil)
|
||||
if got != nil {
|
||||
t.Fatalf("config = %v, want nil on failed migration", got)
|
||||
}
|
||||
assertLegacyMigrationError(t, err, test.subsystem, "archive", test.key, test.secret)
|
||||
|
||||
after, readErr := os.ReadFile(configFile)
|
||||
if readErr != nil {
|
||||
t.Fatal(readErr)
|
||||
}
|
||||
if !bytes.Equal(after, original) {
|
||||
t.Fatal("failed migration rewrote the legacy source config")
|
||||
}
|
||||
if _, statErr := os.Stat(configFile + ".old"); !errors.Is(statErr, os.ErrNotExist) {
|
||||
t.Fatalf("failed migration created a backup/persistence artifact: %v", statErr)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReadConfigWithoutMigrateMigratesCanonicalDatabaseTargets(t *testing.T) {
|
||||
const (
|
||||
postgresConnection = "host=postgres.example port=5432 dbname=events user=app password=secret sslmode=disable"
|
||||
mysqlDSN = "app:secret@tcp(mysql.example:3306)/events?parseTime=true"
|
||||
discardedLegacyValue = "discarded-legacy-value"
|
||||
)
|
||||
installLegacyConfigFile(t, func(cfg *serverConfigV33) {
|
||||
cfg.Notify.PostgreSQL["archive"] = target.PostgreSQLArgs{
|
||||
Enable: true,
|
||||
Format: "namespace",
|
||||
ConnectionString: postgresConnection,
|
||||
Table: "events",
|
||||
Port: discardedLegacyValue,
|
||||
Username: discardedLegacyValue,
|
||||
Password: discardedLegacyValue,
|
||||
Database: discardedLegacyValue,
|
||||
}
|
||||
cfg.Notify.MySQL["archive"] = target.MySQLArgs{
|
||||
Enable: true,
|
||||
Format: "namespace",
|
||||
DSN: mysqlDSN,
|
||||
Table: "events",
|
||||
Port: discardedLegacyValue,
|
||||
User: discardedLegacyValue,
|
||||
Password: discardedLegacyValue,
|
||||
Database: discardedLegacyValue,
|
||||
}
|
||||
})
|
||||
|
||||
got, err := readConfigWithoutMigrate(t.Context(), nil)
|
||||
if err != nil {
|
||||
t.Fatalf("readConfigWithoutMigrate: %v", err)
|
||||
}
|
||||
tests := []struct {
|
||||
subsystem string
|
||||
key string
|
||||
want string
|
||||
discarded string
|
||||
}{
|
||||
{config.NotifyPostgresSubSys, target.PostgresConnectionString, postgresConnection, discardedLegacyValue},
|
||||
{config.NotifyMySQLSubSys, target.MySQLDSNString, mysqlDSN, discardedLegacyValue},
|
||||
}
|
||||
for _, test := range tests {
|
||||
kvs := got[test.subsystem]["archive"]
|
||||
if value := kvs.Get(test.key); value != test.want {
|
||||
t.Errorf("%s %s = %q, want %q", test.subsystem, test.key, value, test.want)
|
||||
}
|
||||
if err := config.CheckValidKeys(test.subsystem+config.SubSystemSeparator+"archive", kvs, notify.DefaultNotificationKVS[test.subsystem]); err != nil {
|
||||
t.Errorf("migrated %s target failed key validation: %v", test.subsystem, err)
|
||||
}
|
||||
for _, key := range []string{"host", "port", "username", "password", "database"} {
|
||||
if _, ok := kvs.Lookup(key); ok {
|
||||
t.Errorf("migrated %s target contains legacy key %q", test.subsystem, key)
|
||||
}
|
||||
}
|
||||
for _, kv := range kvs {
|
||||
if strings.Contains(kv.Value, test.discarded) {
|
||||
t.Errorf("migrated %s target contains discarded legacy value in %q", test.subsystem, kv.Key)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
postgresTargets, err := notify.GetNotifyPostgres(got[config.NotifyPostgresSubSys])
|
||||
if err != nil {
|
||||
t.Fatalf("GetNotifyPostgres: %v", err)
|
||||
}
|
||||
if value := postgresTargets["archive"].ConnectionString; value != postgresConnection {
|
||||
t.Errorf("Postgres connection string = %q, want %q", value, postgresConnection)
|
||||
}
|
||||
mysqlTargets, err := notify.GetNotifyMySQL(got[config.NotifyMySQLSubSys])
|
||||
if err != nil {
|
||||
t.Fatalf("GetNotifyMySQL: %v", err)
|
||||
}
|
||||
if value := mysqlTargets["archive"].DSN; value != mysqlDSN {
|
||||
t.Errorf("MySQL DSN = %q, want %q", value, mysqlDSN)
|
||||
}
|
||||
}
|
||||
|
||||
func TestInitConfigSubsystemReturnsLegacyDatabaseTargetError(t *testing.T) {
|
||||
obj, fsDir, err := prepareFS(t.Context())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_ = obj.Shutdown(context.Background())
|
||||
_ = os.RemoveAll(fsDir)
|
||||
})
|
||||
|
||||
const secret = "startup-migration-secret"
|
||||
installLegacyConfigFile(t, func(cfg *serverConfigV33) {
|
||||
cfg.Notify.PostgreSQL["archive"] = target.PostgreSQLArgs{
|
||||
Enable: true,
|
||||
Port: "5432",
|
||||
Username: "legacy-user",
|
||||
Password: secret,
|
||||
Database: "events",
|
||||
}
|
||||
})
|
||||
|
||||
globalServerConfigMu.RLock()
|
||||
var before config.Config
|
||||
if globalServerConfig != nil {
|
||||
before = globalServerConfig.Clone()
|
||||
}
|
||||
globalServerConfigMu.RUnlock()
|
||||
|
||||
err = initConfigSubsystem(t.Context(), obj)
|
||||
assertLegacyMigrationError(t, err, config.NotifyPostgresSubSys, "archive", target.PostgresConnectionString, secret)
|
||||
if configRetriableErrors(err) {
|
||||
t.Fatal("legacy database migration error must be startup-fatal, not retriable")
|
||||
}
|
||||
if !fatalServerConfigError(err) {
|
||||
t.Fatal("legacy database migration error must abort server startup")
|
||||
}
|
||||
|
||||
globalServerConfigMu.RLock()
|
||||
var after config.Config
|
||||
if globalServerConfig != nil {
|
||||
after = globalServerConfig.Clone()
|
||||
}
|
||||
globalServerConfigMu.RUnlock()
|
||||
if !reflect.DeepEqual(after, before) {
|
||||
t.Fatal("failed migration activated a partial server configuration")
|
||||
}
|
||||
}
|
||||
@@ -326,7 +326,7 @@ func (h dataUsageHash) modAlt(cycle uint32, cycles uint32) bool {
|
||||
if cycles <= 1 {
|
||||
return cycles == 1
|
||||
}
|
||||
return uint32(xxhash.Sum64String(string(h))>>32)%(cycles) == cycle%cycles
|
||||
return uint32(xxhash.Sum64String(string(h))>>32)%cycles == cycle%cycles
|
||||
}
|
||||
|
||||
// addChild will add a child based on its hash.
|
||||
|
||||
@@ -0,0 +1,402 @@
|
||||
// Copyright (c) 2015-2026 MinIO, Inc.
|
||||
// Copyright (c) 2026 PGSTY
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/xml"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/minio/internal/auth"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
"github.com/minio/pkg/v3/policy"
|
||||
)
|
||||
|
||||
func TestDeleteObjectAction(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
versionID string
|
||||
want policy.Action
|
||||
}{
|
||||
{want: policy.DeleteObjectAction},
|
||||
{versionID: nullVersionID, want: policy.DeleteObjectVersionAction},
|
||||
{versionID: mustGetUUID(), want: policy.DeleteObjectVersionAction},
|
||||
{versionID: " ", want: policy.DeleteObjectVersionAction},
|
||||
} {
|
||||
if got := deleteObjectAction(test.versionID); got != test.want {
|
||||
t.Errorf("deleteObjectAction(%q) = %s, want %s", test.versionID, got, test.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIDeleteObjectVersionAuthorization(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPIDeleteObjectVersionAuthorization,
|
||||
endpoints: []string{"DeleteObject"},
|
||||
makeBucketOptions: MakeBucketOptions{VersioningEnabled: true},
|
||||
})
|
||||
}
|
||||
|
||||
func TestAPIDeleteMultipleObjectsVersionAuthorization(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPIDeleteMultipleObjectsVersionAuthorization,
|
||||
endpoints: []string{"DeleteMultipleObjects"},
|
||||
makeBucketOptions: MakeBucketOptions{VersioningEnabled: true},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPIDeleteMultipleObjectsVersionAuthorization(obj ObjectLayer, instanceType, bucket string,
|
||||
apiRouter http.Handler, _ auth.Credentials, t *testing.T,
|
||||
) {
|
||||
deleteOnly := newObjectAttributesAuthzUser(t, instanceType, bucket, `"s3:DeleteObject"`)
|
||||
versionOnly := newObjectAttributesAuthzUser(t, instanceType, bucket, `"s3:DeleteObjectVersion"`)
|
||||
payload := []byte("multi delete version authorization")
|
||||
|
||||
put := func(t *testing.T, object string, versioned bool) string {
|
||||
t.Helper()
|
||||
info, err := obj.PutObject(t.Context(), bucket, object,
|
||||
mustGetPutObjReader(t, bytes.NewReader(payload), int64(len(payload)), "", ""), ObjectOptions{Versioned: versioned})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return info.VersionID
|
||||
}
|
||||
request := func(t *testing.T, prefix string, creds auth.Credentials) (DeleteObjectsResponse, map[string]string) {
|
||||
t.Helper()
|
||||
versions := map[string]string{
|
||||
prefix + "simple": put(t, prefix+"simple", true),
|
||||
prefix + "explicit": put(t, prefix+"explicit", true),
|
||||
prefix + "null": put(t, prefix+"null", false),
|
||||
}
|
||||
body := encodeResponse(DeleteObjectsRequest{Objects: []ObjectToDelete{
|
||||
{ObjectV: ObjectV{ObjectName: prefix + "simple"}},
|
||||
{ObjectV: ObjectV{ObjectName: prefix + "explicit", VersionID: versions[prefix+"explicit"]}},
|
||||
{ObjectV: ObjectV{ObjectName: prefix + "null", VersionID: nullVersionID}},
|
||||
{ObjectV: ObjectV{ObjectName: prefix + "bad", VersionID: "not-a-uuid"}},
|
||||
}})
|
||||
target := getDeleteMultipleObjectsURL("", bucket) + "&versionId=query-level-decoy"
|
||||
req, err := newTestSignedRequestV4(http.MethodPost, target, int64(len(body)), bytes.NewReader(body),
|
||||
creds.AccessKey, creds.SecretKey, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: multi-delete status %d: %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
var response DeleteObjectsResponse
|
||||
if err = xml.Unmarshal(rec.Body.Bytes(), &response); err != nil {
|
||||
t.Fatalf("decode response: %v: %s", err, rec.Body.String())
|
||||
}
|
||||
return response, versions
|
||||
}
|
||||
responseMap := func(response DeleteObjectsResponse) (map[string]DeletedObject, map[string]DeleteError) {
|
||||
deleted := make(map[string]DeletedObject, len(response.DeletedObjects))
|
||||
for _, object := range response.DeletedObjects {
|
||||
deleted[object.ObjectName] = object
|
||||
}
|
||||
errs := make(map[string]DeleteError, len(response.Errors))
|
||||
for _, deleteErr := range response.Errors {
|
||||
errs[deleteErr.Key] = deleteErr
|
||||
}
|
||||
return deleted, errs
|
||||
}
|
||||
|
||||
t.Run("DeleteObject only", func(t *testing.T) {
|
||||
prefix := "multi-delete-only/"
|
||||
response, versions := request(t, prefix, deleteOnly)
|
||||
deleted, errs := responseMap(response)
|
||||
if object, ok := deleted[prefix+"simple"]; !ok || !object.DeleteMarker {
|
||||
t.Fatalf("simple delete did not create a marker: %+v", response)
|
||||
}
|
||||
for _, object := range []string{"explicit", "null", "bad"} {
|
||||
if got := errs[prefix+object].Code; got != errorCodes[ErrAccessDenied].Code {
|
||||
t.Errorf("%s error = %q, want AccessDenied", object, got)
|
||||
}
|
||||
}
|
||||
if _, err := obj.GetObjectInfo(t.Context(), bucket, prefix+"explicit", ObjectOptions{VersionID: versions[prefix+"explicit"]}); err != nil {
|
||||
t.Fatalf("denied explicit delete removed its version: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("DeleteObjectVersion only", func(t *testing.T) {
|
||||
prefix := "multi-version-only/"
|
||||
response, _ := request(t, prefix, versionOnly)
|
||||
deleted, errs := responseMap(response)
|
||||
for _, object := range []string{"explicit", "null"} {
|
||||
if _, ok := deleted[prefix+object]; !ok {
|
||||
t.Errorf("%s was not deleted: %+v", object, response)
|
||||
}
|
||||
}
|
||||
if got := errs[prefix+"simple"].Code; got != errorCodes[ErrAccessDenied].Code {
|
||||
t.Errorf("simple error = %q, want AccessDenied", got)
|
||||
}
|
||||
if got := errs[prefix+"bad"].Code; got != errorCodes[ErrNoSuchVersion].Code {
|
||||
t.Errorf("bad UUID error = %q, want NoSuchVersion", got)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func testAPIDeleteObjectVersionAuthorization(obj ObjectLayer, instanceType, bucket string,
|
||||
apiRouter http.Handler, _ auth.Credentials, t *testing.T,
|
||||
) {
|
||||
deleteOnly := newObjectAttributesAuthzUser(t, instanceType, bucket, `"s3:DeleteObject"`)
|
||||
versionOnly := newObjectAttributesAuthzUser(t, instanceType, bucket, `"s3:DeleteObjectVersion"`)
|
||||
payload := []byte("delete version authorization")
|
||||
|
||||
put := func(t *testing.T, object string, versioned bool) string {
|
||||
t.Helper()
|
||||
info, err := obj.PutObject(t.Context(), bucket, object,
|
||||
mustGetPutObjReader(t, bytes.NewReader(payload), int64(len(payload)), "", ""), ObjectOptions{Versioned: versioned})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if versioned && info.VersionID == "" {
|
||||
t.Fatalf("%s: versioned PUT returned an empty version ID", instanceType)
|
||||
}
|
||||
return info.VersionID
|
||||
}
|
||||
remove := func(t *testing.T, object, versionID string, creds auth.Credentials) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
target := getDeleteObjectURL("", bucket, object)
|
||||
if versionID != "" {
|
||||
target += "?" + url.Values{xhttp.VersionID: {versionID}}.Encode()
|
||||
}
|
||||
req, err := newTestSignedRequestV4(http.MethodDelete, target, 0, nil, creds.AccessKey, creds.SecretKey, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
t.Run("version permission deletes an explicit version", func(t *testing.T) {
|
||||
object := "delete-authz/version-only-explicit"
|
||||
versionID := put(t, object, true)
|
||||
if rec := remove(t, object, versionID, versionOnly); rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("status %d, want 204: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if _, err := obj.GetObjectInfo(t.Context(), bucket, object, ObjectOptions{VersionID: versionID}); !isErrObjectNotFound(err) && !isErrVersionNotFound(err) {
|
||||
t.Fatalf("explicit version still exists: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("version permission cannot create a delete marker", func(t *testing.T) {
|
||||
object := "delete-authz/version-only-simple"
|
||||
versionID := put(t, object, true)
|
||||
if rec := remove(t, object, "", versionOnly); rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("status %d, want 403: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if _, err := obj.GetObjectInfo(t.Context(), bucket, object, ObjectOptions{VersionID: versionID}); err != nil {
|
||||
t.Fatalf("denied simple delete removed the version: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("object permission cannot delete an explicit version", func(t *testing.T) {
|
||||
object := "delete-authz/delete-only-explicit"
|
||||
versionID := put(t, object, true)
|
||||
if rec := remove(t, object, versionID, deleteOnly); rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("status %d, want 403: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if _, err := obj.GetObjectInfo(t.Context(), bucket, object, ObjectOptions{VersionID: versionID}); err != nil {
|
||||
t.Fatalf("denied version delete removed the version: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("object permission creates a delete marker", func(t *testing.T) {
|
||||
object := "delete-authz/delete-only-simple"
|
||||
versionID := put(t, object, true)
|
||||
if rec := remove(t, object, "", deleteOnly); rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("status %d, want 204: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if _, err := obj.GetObjectInfo(t.Context(), bucket, object, ObjectOptions{VersionID: versionID}); err != nil {
|
||||
t.Fatalf("simple delete removed the old version: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("null is an explicit version", func(t *testing.T) {
|
||||
object := "delete-authz/null-version"
|
||||
if versionID := put(t, object, false); versionID != "" {
|
||||
t.Fatalf("unversioned PUT returned version ID %q", versionID)
|
||||
}
|
||||
if rec := remove(t, object, nullVersionID, versionOnly); rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("status %d, want 204: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if _, err := obj.GetObjectInfo(t.Context(), bucket, object, ObjectOptions{VersionID: nullVersionID}); !isErrObjectNotFound(err) && !isErrVersionNotFound(err) {
|
||||
t.Fatalf("null version still exists: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("authorization precedes invalid version parsing", func(t *testing.T) {
|
||||
object := "delete-authz/invalid-version"
|
||||
if rec := remove(t, object, "not-a-uuid", deleteOnly); rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("delete-only status %d, want 403: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := remove(t, object, "not-a-uuid", versionOnly); rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("version-only status %d, want 400: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("padded version uses the effective ID", func(t *testing.T) {
|
||||
object := "delete-authz/padded-version"
|
||||
versionID := put(t, object, true)
|
||||
if rec := remove(t, object, versionID+" ", versionOnly); rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("status %d, want 204: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestAPIDeleteObjectVersionDenyAndReplicationCompatibility(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPIDeleteObjectVersionDenyAndReplicationCompatibility,
|
||||
endpoints: []string{"DeleteObject"},
|
||||
makeBucketOptions: MakeBucketOptions{VersioningEnabled: true},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPIDeleteObjectVersionDenyAndReplicationCompatibility(obj ObjectLayer, instanceType, bucket string,
|
||||
apiRouter http.Handler, _ auth.Credentials, t *testing.T,
|
||||
) {
|
||||
payload := []byte("delete version deny compatibility")
|
||||
put := func(t *testing.T, object string) string {
|
||||
t.Helper()
|
||||
info, err := obj.PutObject(t.Context(), bucket, object,
|
||||
mustGetPutObjReader(t, bytes.NewReader(payload), int64(len(payload)), "", ""), ObjectOptions{Versioned: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return info.VersionID
|
||||
}
|
||||
request := func(t *testing.T, object, versionID string, creds auth.Credentials, replicationRequest bool) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
target := getDeleteObjectURL("", bucket, object)
|
||||
if versionID != "" {
|
||||
target += "?" + url.Values{xhttp.VersionID: {versionID}}.Encode()
|
||||
}
|
||||
var headers map[string]string
|
||||
if replicationRequest {
|
||||
headers = map[string]string{
|
||||
xhttp.MinIOSourceReplicationRequest: "true",
|
||||
xhttp.AmzBucketReplicationStatus: "REPLICA",
|
||||
xhttp.MinIOSourceDeleteMarker: "false",
|
||||
xhttp.MinIOSourceMTime: UTCNow().Format(time.RFC3339Nano),
|
||||
}
|
||||
}
|
||||
req, err := newTestSignedRequestV4(http.MethodDelete, target, 0, nil, creds.AccessKey, creds.SecretKey, headers)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
minimal := newDeleteAuthzPolicyUser(t, instanceType, bucket, `[
|
||||
{"Effect":"Allow","Action":["s3:DeleteObject","s3:ReplicateDelete"],"Resource":["arn:aws:s3:::`+bucket+`/*"]}
|
||||
]`)
|
||||
denied := newDeleteAuthzPolicyUser(t, instanceType, bucket, `[
|
||||
{"Effect":"Allow","Action":["s3:DeleteObject","s3:DeleteObjectVersion","s3:ReplicateDelete"],"Resource":["arn:aws:s3:::`+bucket+`/*"]},
|
||||
{"Effect":"Deny","Action":"s3:DeleteObjectVersion","Resource":"arn:aws:s3:::`+bucket+`/deny/*"}
|
||||
]`)
|
||||
deleteOnly := newObjectAttributesAuthzUser(t, instanceType, bucket, `"s3:DeleteObject"`)
|
||||
|
||||
t.Run("ordinary explicit deny wins", func(t *testing.T) {
|
||||
object := "deny/ordinary"
|
||||
versionID := put(t, object)
|
||||
if rec := request(t, object, versionID, denied, false); rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("status %d, want 403: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("version deny does not block a simple delete", func(t *testing.T) {
|
||||
object := "deny/simple"
|
||||
put(t, object)
|
||||
if rec := request(t, object, "", denied, false); rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("status %d, want 204: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("replication keeps minimal target policy", func(t *testing.T) {
|
||||
object := "replication/minimal"
|
||||
versionID := put(t, object)
|
||||
if rec := request(t, object, versionID, minimal, true); rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("status %d, want 204: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("replication preserves explicit version deny", func(t *testing.T) {
|
||||
object := "deny/replication"
|
||||
versionID := put(t, object)
|
||||
if rec := request(t, object, versionID, denied, true); rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("status %d, want 403: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("marker alone cannot enter the replication path", func(t *testing.T) {
|
||||
object := "replication/fake-marker"
|
||||
versionID := put(t, object)
|
||||
target := getDeleteObjectURL("", bucket, object) + "?" + url.Values{xhttp.VersionID: {versionID}}.Encode()
|
||||
req, err := newTestSignedRequestV4(http.MethodDelete, target, 0, nil, deleteOnly.AccessKey, deleteOnly.SecretKey,
|
||||
map[string]string{xhttp.MinIOSourceReplicationRequest: "true"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("status %d, want 403: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if _, err = obj.GetObjectInfo(t.Context(), bucket, object, ObjectOptions{VersionID: versionID}); err != nil {
|
||||
t.Fatalf("fake marker removed the version: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func newDeleteAuthzPolicyUser(t *testing.T, instanceType, bucket, statements string) auth.Credentials {
|
||||
t.Helper()
|
||||
accessKey, secretKey, err := auth.GenerateCredentials()
|
||||
if err != nil {
|
||||
t.Fatalf("%s: generate credentials: %v", instanceType, err)
|
||||
}
|
||||
creds := auth.Credentials{AccessKey: accessKey, SecretKey: secretKey}
|
||||
if _, err = globalIAMSys.CreateUser(t.Context(), accessKey, madmin.AddOrUpdateUserReq{
|
||||
SecretKey: secretKey,
|
||||
Status: madmin.AccountEnabled,
|
||||
}); err != nil {
|
||||
t.Fatalf("%s: create delete authz user: %v", instanceType, err)
|
||||
}
|
||||
policyJSON := `{"Version":"2012-10-17","Statement":` + statements + `}`
|
||||
parsed, err := policy.ParseConfig(strings.NewReader(policyJSON))
|
||||
if err != nil {
|
||||
t.Fatalf("%s: parse delete authz policy: %v", instanceType, err)
|
||||
}
|
||||
policyName := "delete-version-authz-" + mustGetUUID()
|
||||
if _, err = globalIAMSys.SetPolicy(t.Context(), policyName, *parsed); err != nil {
|
||||
t.Fatalf("%s: install delete authz policy: %v", instanceType, err)
|
||||
}
|
||||
if _, err = globalIAMSys.PolicyDBSet(t.Context(), accessKey, policyName, regUser, false); err != nil {
|
||||
t.Fatalf("%s: attach delete authz policy: %v", instanceType, err)
|
||||
}
|
||||
return creds
|
||||
}
|
||||
@@ -165,93 +165,3 @@ func (api objectAPIHandlers) GetBucketLoggingHandler(w http.ResponseWriter, r *h
|
||||
func (api objectAPIHandlers) DeleteBucketWebsiteHandler(w http.ResponseWriter, r *http.Request) {
|
||||
writeSuccessResponseHeadersOnly(w)
|
||||
}
|
||||
|
||||
// GetBucketCorsHandler - GET bucket cors, a dummy api
|
||||
func (api objectAPIHandlers) GetBucketCorsHandler(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := newContext(r, w, "GetBucketCors")
|
||||
|
||||
defer logger.AuditLog(ctx, w, r, mustGetClaimsFromToken(r))
|
||||
|
||||
vars := mux.Vars(r)
|
||||
bucket := vars["bucket"]
|
||||
|
||||
objAPI := api.ObjectAPI()
|
||||
if objAPI == nil {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrServerNotInitialized), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
if s3Error := checkRequestAuthType(ctx, r, policy.GetBucketCorsAction, bucket, ""); s3Error != ErrNone {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Error), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
// Validate if bucket exists, before proceeding further...
|
||||
_, err := objAPI.GetBucketInfo(ctx, bucket, BucketOptions{})
|
||||
if err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrNoSuchCORSConfiguration), r.URL)
|
||||
}
|
||||
|
||||
// PutBucketCorsHandler - PUT bucket cors, a dummy api
|
||||
func (api objectAPIHandlers) PutBucketCorsHandler(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := newContext(r, w, "PutBucketCors")
|
||||
|
||||
defer logger.AuditLog(ctx, w, r, mustGetClaimsFromToken(r))
|
||||
|
||||
vars := mux.Vars(r)
|
||||
bucket := vars["bucket"]
|
||||
|
||||
objAPI := api.ObjectAPI()
|
||||
if objAPI == nil {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrServerNotInitialized), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
if s3Error := checkRequestAuthType(ctx, r, policy.PutBucketCorsAction, bucket, ""); s3Error != ErrNone {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Error), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
// Validate if bucket exists, before proceeding further...
|
||||
_, err := objAPI.GetBucketInfo(ctx, bucket, BucketOptions{})
|
||||
if err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrNotImplemented), r.URL)
|
||||
}
|
||||
|
||||
// DeleteBucketCorsHandler - DELETE bucket cors, a dummy api
|
||||
func (api objectAPIHandlers) DeleteBucketCorsHandler(w http.ResponseWriter, r *http.Request) {
|
||||
ctx := newContext(r, w, "DeleteBucketCors")
|
||||
|
||||
defer logger.AuditLog(ctx, w, r, mustGetClaimsFromToken(r))
|
||||
|
||||
vars := mux.Vars(r)
|
||||
bucket := vars["bucket"]
|
||||
|
||||
objAPI := api.ObjectAPI()
|
||||
if objAPI == nil {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrServerNotInitialized), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
if s3Error := checkRequestAuthType(ctx, r, policy.DeleteBucketCorsAction, bucket, ""); s3Error != ErrNone {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Error), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
// Validate if bucket exists, before proceeding further...
|
||||
_, err := objAPI.GetBucketInfo(ctx, bucket, BucketOptions{})
|
||||
if err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrNotImplemented), r.URL)
|
||||
}
|
||||
|
||||
+42
-1
@@ -355,6 +355,29 @@ func rotateKey(ctx context.Context, oldKey []byte, newKeyID string, newKey []byt
|
||||
}
|
||||
}
|
||||
|
||||
// checkSSECCopySourceKey authenticates the SSE-C copy source key against the
|
||||
// sealed object key held in metadata. This keeps the diverted rotation safe on
|
||||
// its own and remains defense in depth when the read path also authenticates
|
||||
// zero-byte objects. Mirrors the errors rotateKey reports.
|
||||
func checkSSECCopySourceKey(h http.Header, metadata map[string]string, bucket, object string, newKey []byte) error {
|
||||
oldKey, err := ParseSSECopyCustomerRequest(h, metadata)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
sealedKey, err := crypto.SSEC.ParseMetadata(metadata)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var objectKey crypto.ObjectKey
|
||||
if err := objectKey.Unseal(oldKey, sealedKey, crypto.SSEC.String(), bucket, object); err != nil {
|
||||
if subtle.ConstantTimeCompare(oldKey, newKey) == 1 {
|
||||
return errInvalidSSEParameters
|
||||
}
|
||||
return crypto.ErrInvalidCustomerKey
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func newEncryptMetadata(ctx context.Context, kind crypto.Type, keyID string, key []byte, bucket, object string, metadata map[string]string, cryptoCtx kms.Context) (crypto.ObjectKey, error) {
|
||||
var sealedKey crypto.SealedKey
|
||||
switch kind {
|
||||
@@ -551,6 +574,24 @@ func DecryptCopyRequestR(client io.Reader, h http.Header, bucket, object string,
|
||||
return newDecryptReader(client, key, bucket, object, seqNumber, metadata)
|
||||
}
|
||||
|
||||
// checkSSECReadKey authenticates a supplied SSE-C read key against the sealed
|
||||
// object key when a read has no data from which to build a decryptor.
|
||||
func checkSSECReadKey(h http.Header, oi ObjectInfo, opts ObjectOptions) error {
|
||||
if opts.NoDecryption || opts.Transition.RestoreRequest != nil || !crypto.SSEC.IsEncrypted(oi.UserDefined) {
|
||||
return nil
|
||||
}
|
||||
switch {
|
||||
case crypto.SSECopy.IsRequested(h):
|
||||
_, err := crypto.SSECopy.UnsealObjectKey(h, oi.UserDefined, oi.Bucket, oi.Name)
|
||||
return err
|
||||
case crypto.SSEC.IsRequested(h):
|
||||
_, err := crypto.SSEC.UnsealObjectKey(h, oi.UserDefined, oi.Bucket, oi.Name)
|
||||
return err
|
||||
default:
|
||||
return nil
|
||||
}
|
||||
}
|
||||
|
||||
func newDecryptReader(client io.Reader, key []byte, bucket, object string, seqNumber uint32, metadata map[string]string) (io.Reader, error) {
|
||||
objectEncryptionKey, err := decryptObjectMeta(key, bucket, object, metadata)
|
||||
if err != nil {
|
||||
@@ -1008,7 +1049,7 @@ func DecryptObjectInfo(info *ObjectInfo, r *http.Request) (encrypted bool, err e
|
||||
if encrypted {
|
||||
if crypto.SSEC.IsEncrypted(info.UserDefined) {
|
||||
if !crypto.SSEC.IsRequested(headers) && !crypto.SSECopy.IsRequested(headers) {
|
||||
if r.Header.Get(xhttp.MinIOSourceReplicationRequest) != "true" {
|
||||
if !isReplicaTrusted(r.Context()) {
|
||||
return encrypted, errEncryptedObject
|
||||
}
|
||||
}
|
||||
|
||||
@@ -24,6 +24,7 @@ import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
@@ -139,13 +140,18 @@ func completeMultipartUploadHTTP(t *testing.T, apiRouter http.Handler, creds aut
|
||||
return rec
|
||||
}
|
||||
|
||||
func apiErrorCode(t *testing.T, rec *httptest.ResponseRecorder) string {
|
||||
func apiError(t *testing.T, rec *httptest.ResponseRecorder) APIErrorResponse {
|
||||
t.Helper()
|
||||
var e APIErrorResponse
|
||||
if err := xml.Unmarshal(rec.Body.Bytes(), &e); err != nil {
|
||||
t.Fatalf("unable to decode error response %q: %v", rec.Body.String(), err)
|
||||
}
|
||||
return e.Code
|
||||
return e
|
||||
}
|
||||
|
||||
func apiErrorCode(t *testing.T, rec *httptest.ResponseRecorder) string {
|
||||
t.Helper()
|
||||
return apiError(t, rec).Code
|
||||
}
|
||||
|
||||
// TestAPICompleteMultipartFullObjectChecksum covers pgsty/silo#31.
|
||||
@@ -243,12 +249,12 @@ func testAPICompleteMultipartFullObjectChecksumMismatch(obj ObjectLayer, instanc
|
||||
t.Fatalf("%s: CompleteMultipartUpload with a bad full object checksum returned %d, want 400",
|
||||
instanceType, rec.Code)
|
||||
}
|
||||
// NOTE: AWS S3 documents BadDigest for a full object checksum mismatch on
|
||||
// CompleteMultipartUpload. MinIO reports XAmzContentChecksumMismatch. That
|
||||
// deviation is tracked separately; assert the current code so a future
|
||||
// change to it is a deliberate one.
|
||||
if got := apiErrorCode(t, rec); got != "XAmzContentChecksumMismatch" {
|
||||
t.Fatalf("%s: expected XAmzContentChecksumMismatch, got %q", instanceType, got)
|
||||
apiErr := apiError(t, rec)
|
||||
if apiErr.Code != "BadDigest" {
|
||||
t.Fatalf("%s: expected BadDigest, got %q", instanceType, apiErr.Code)
|
||||
}
|
||||
if want := "The CRC32 checksum you specified did not match the calculated checksum."; apiErr.Message != want {
|
||||
t.Fatalf("%s: expected message %q, got %q", instanceType, want, apiErr.Message)
|
||||
}
|
||||
|
||||
if _, err := obj.GetObjectInfo(t.Context(), bucketName, objectName, ObjectOptions{}); err == nil {
|
||||
@@ -288,8 +294,33 @@ func testAPICompleteMultipartCompositeStillRequiresPartChecksums(obj ObjectLayer
|
||||
t.Fatalf("%s/%s: composite CompleteMultipartUpload without part checksums returned %d, want 400",
|
||||
instanceType, typ.String(), rec.Code)
|
||||
}
|
||||
if got := apiErrorCode(t, rec); got != "InvalidPart" {
|
||||
t.Fatalf("%s/%s: expected InvalidPart, got %q", instanceType, typ.String(), got)
|
||||
apiErr := apiError(t, rec)
|
||||
if apiErr.Code != "InvalidRequest" {
|
||||
t.Fatalf("%s/%s: expected InvalidRequest, got %q", instanceType, typ.String(), apiErr.Code)
|
||||
}
|
||||
wantMessage := fmt.Sprintf("The upload was created using a %s checksum. The complete request must include the checksum for each part. It was missing for part 1 in the request.", strings.ToLower(typ.String()))
|
||||
if apiErr.Message != wantMessage {
|
||||
t.Fatalf("%s/%s: expected message %q, got %q", instanceType, typ.String(), wantMessage, apiErr.Message)
|
||||
}
|
||||
|
||||
// A retry that supplies part 1 but omits part 2 must name the actual
|
||||
// missing part, not merely the first part in the upload.
|
||||
completedParts := []CompletePart{
|
||||
completePartWithChecksum(typ, 1, etags[0], mustChecksum(t, typ, partData[0])),
|
||||
{PartNumber: 2, ETag: etags[1]},
|
||||
}
|
||||
rec = completePartsHTTP(t, apiRouter, credentials, bucketName, objectName, uploadID, completedParts, nil)
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("%s/%s: composite completion missing part 2 checksum returned %d, want 400",
|
||||
instanceType, typ.String(), rec.Code)
|
||||
}
|
||||
apiErr = apiError(t, rec)
|
||||
if apiErr.Code != "InvalidRequest" {
|
||||
t.Fatalf("%s/%s: expected InvalidRequest, got %q", instanceType, typ.String(), apiErr.Code)
|
||||
}
|
||||
wantMessage = fmt.Sprintf("The upload was created using a %s checksum. The complete request must include the checksum for each part. It was missing for part 2 in the request.", strings.ToLower(typ.String()))
|
||||
if apiErr.Message != wantMessage {
|
||||
t.Fatalf("%s/%s: expected message %q, got %q", instanceType, typ.String(), wantMessage, apiErr.Message)
|
||||
}
|
||||
if _, err := obj.GetObjectInfo(t.Context(), bucketName, objectName, ObjectOptions{}); err == nil {
|
||||
t.Fatalf("%s/%s: object was created despite a rejected completion", instanceType, typ.String())
|
||||
@@ -297,6 +328,230 @@ func testAPICompleteMultipartCompositeStillRequiresPartChecksums(obj ObjectLayer
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPICompleteMultipartCompositeChecksumMismatch covers the composite
|
||||
// object-checksum path independently from full object checksum merging.
|
||||
func TestAPICompleteMultipartCompositeChecksumMismatch(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPICompleteMultipartCompositeChecksumMismatch,
|
||||
endpoints: []string{"NewMultipart", "PutObjectPart", "CompleteMultipart"},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPICompleteMultipartCompositeChecksumMismatch(obj ObjectLayer, instanceType, bucketName string, apiRouter http.Handler,
|
||||
credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
typ := hash.ChecksumCRC32
|
||||
partData, _ := multipartChecksumTestData()
|
||||
objectName := "uploads/composite-object-mismatch"
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, bucketName, objectName,
|
||||
typ.String(), xhttp.AmzChecksumTypeComposite)
|
||||
etags := uploadPartsHTTP(t, apiRouter, credentials, bucketName, objectName, uploadID, typ, partData)
|
||||
partCS := []string{mustChecksum(t, typ, partData[0]), mustChecksum(t, typ, partData[1])}
|
||||
rec := completeMultipartUploadHTTP(t, apiRouter, credentials, bucketName, objectName, uploadID, etags, partCS,
|
||||
map[string]string{
|
||||
typ.Key(): mustChecksum(t, typ, []byte("wrong composite checksum")) + "-2",
|
||||
xhttp.AmzChecksumType: xhttp.AmzChecksumTypeComposite,
|
||||
})
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("%s: composite checksum mismatch returned %d, want 400", instanceType, rec.Code)
|
||||
}
|
||||
apiErr := apiError(t, rec)
|
||||
if apiErr.Code != "BadDigest" {
|
||||
t.Fatalf("%s: expected BadDigest, got %q", instanceType, apiErr.Code)
|
||||
}
|
||||
if want := "The CRC32 checksum you specified did not match the calculated checksum."; apiErr.Message != want {
|
||||
t.Fatalf("%s: expected message %q, got %q", instanceType, want, apiErr.Message)
|
||||
}
|
||||
if _, err := obj.GetObjectInfo(t.Context(), bucketName, objectName, ObjectOptions{}); err == nil {
|
||||
t.Fatalf("%s: object was created despite a failed composite checksum validation", instanceType)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPICompleteMultipartChecksumTypeMismatch verifies the type comparison in
|
||||
// both directions. ChecksumType is a bitmask, so a containment check alone
|
||||
// incorrectly accepts COMPOSITE uploads completed as FULL_OBJECT.
|
||||
func TestAPICompleteMultipartChecksumTypeMismatch(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPICompleteMultipartChecksumTypeMismatch,
|
||||
endpoints: []string{"NewMultipart", "PutObjectPart", "CompleteMultipart"},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPICompleteMultipartChecksumTypeMismatch(obj ObjectLayer, instanceType, bucketName string, apiRouter http.Handler,
|
||||
credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
typ := hash.ChecksumCRC32
|
||||
partData, full := multipartChecksumTestData()
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
createdType string
|
||||
providedType string
|
||||
}{
|
||||
{name: "full-to-composite", createdType: xhttp.AmzChecksumTypeFullObject, providedType: xhttp.AmzChecksumTypeComposite},
|
||||
{name: "composite-to-full", createdType: xhttp.AmzChecksumTypeComposite, providedType: xhttp.AmzChecksumTypeFullObject},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
objectName := "type-mismatch/" + test.name
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, bucketName, objectName,
|
||||
typ.String(), test.createdType)
|
||||
etags := uploadPartsHTTP(t, apiRouter, credentials, bucketName, objectName, uploadID, typ, partData)
|
||||
partCS := []string{mustChecksum(t, typ, partData[0]), mustChecksum(t, typ, partData[1])}
|
||||
rec := completeMultipartUploadHTTP(t, apiRouter, credentials, bucketName, objectName, uploadID, etags, partCS,
|
||||
map[string]string{
|
||||
typ.Key(): mustChecksum(t, typ, full),
|
||||
xhttp.AmzChecksumType: test.providedType,
|
||||
})
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("%s: checksum type mismatch returned %d, want 400", instanceType, rec.Code)
|
||||
}
|
||||
apiErr := apiError(t, rec)
|
||||
if apiErr.Code != "BadDigest" {
|
||||
t.Fatalf("%s: expected BadDigest, got %q", instanceType, apiErr.Code)
|
||||
}
|
||||
wantMessage := fmt.Sprintf("The checksum type %s does not match the multipart upload checksum type %s.", test.providedType, test.createdType)
|
||||
if apiErr.Message != wantMessage {
|
||||
t.Fatalf("%s: expected message %q, got %q", instanceType, wantMessage, apiErr.Message)
|
||||
}
|
||||
if _, err := obj.GetObjectInfo(t.Context(), bucketName, objectName, ObjectOptions{}); err == nil {
|
||||
t.Fatalf("%s: object was created despite a rejected checksum type", instanceType)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run(test.name+"-type-only", func(t *testing.T) {
|
||||
objectName := "type-mismatch/type-only-" + test.name
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, bucketName, objectName,
|
||||
typ.String(), test.createdType)
|
||||
etags := uploadPartsHTTP(t, apiRouter, credentials, bucketName, objectName, uploadID, typ, partData)
|
||||
partCS := []string{mustChecksum(t, typ, partData[0]), mustChecksum(t, typ, partData[1])}
|
||||
rec := completeMultipartUploadHTTP(t, apiRouter, credentials, bucketName, objectName, uploadID, etags, partCS,
|
||||
map[string]string{xhttp.AmzChecksumType: test.providedType})
|
||||
if rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("%s: checksum type-only mismatch returned %d, want 400", instanceType, rec.Code)
|
||||
}
|
||||
apiErr := apiError(t, rec)
|
||||
if apiErr.Code != "BadDigest" {
|
||||
t.Fatalf("%s: expected BadDigest, got %q", instanceType, apiErr.Code)
|
||||
}
|
||||
wantMessage := fmt.Sprintf("The checksum type %s does not match the multipart upload checksum type %s.", test.providedType, test.createdType)
|
||||
if apiErr.Message != wantMessage {
|
||||
t.Fatalf("%s: expected message %q, got %q", instanceType, wantMessage, apiErr.Message)
|
||||
}
|
||||
if _, err := obj.GetObjectInfo(t.Context(), bucketName, objectName, ObjectOptions{}); err == nil {
|
||||
t.Fatalf("%s: object was created despite a rejected checksum type-only assertion", instanceType)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
providedType string
|
||||
withChecksum bool
|
||||
}{
|
||||
{name: "unknown-type-only", providedType: "NOT_A_TYPE"},
|
||||
{name: "lowercase-type-only", providedType: "full_object"},
|
||||
{name: "unknown-with-checksum", providedType: "NOT_A_TYPE", withChecksum: true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
objectName := "type-mismatch/invalid-" + test.name
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, bucketName, objectName,
|
||||
typ.String(), xhttp.AmzChecksumTypeComposite)
|
||||
etags := uploadPartsHTTP(t, apiRouter, credentials, bucketName, objectName, uploadID, typ, partData)
|
||||
partCS := []string{mustChecksum(t, typ, partData[0]), mustChecksum(t, typ, partData[1])}
|
||||
headers := map[string]string{xhttp.AmzChecksumType: test.providedType}
|
||||
if test.withChecksum {
|
||||
headers[typ.Key()] = mustChecksum(t, typ, full)
|
||||
}
|
||||
rec := completeMultipartUploadHTTP(t, apiRouter, credentials, bucketName, objectName, uploadID, etags, partCS, headers)
|
||||
if rec.Code != http.StatusBadRequest || apiErrorCode(t, rec) != "InvalidArgument" {
|
||||
t.Fatalf("%s: invalid checksum type returned %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
if _, err := obj.GetObjectInfo(t.Context(), bucketName, objectName, ObjectOptions{}); err == nil {
|
||||
t.Fatalf("%s: object was created despite an invalid checksum type", instanceType)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("matching-type-only", func(t *testing.T) {
|
||||
objectName := "type-mismatch/matching-type-only"
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, bucketName, objectName,
|
||||
typ.String(), xhttp.AmzChecksumTypeComposite)
|
||||
etags := uploadPartsHTTP(t, apiRouter, credentials, bucketName, objectName, uploadID, typ, partData)
|
||||
partCS := []string{mustChecksum(t, typ, partData[0]), mustChecksum(t, typ, partData[1])}
|
||||
rec := completeMultipartUploadHTTP(t, apiRouter, credentials, bucketName, objectName, uploadID, etags, partCS,
|
||||
map[string]string{xhttp.AmzChecksumType: xhttp.AmzChecksumTypeComposite})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: matching checksum type-only assertion returned %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("omitted-type-is-not-composite", func(t *testing.T) {
|
||||
objectName := "type-mismatch/omitted-type"
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, bucketName, objectName,
|
||||
typ.String(), xhttp.AmzChecksumTypeFullObject)
|
||||
etags := uploadPartsHTTP(t, apiRouter, credentials, bucketName, objectName, uploadID, typ, partData)
|
||||
rec := completeMultipartUploadHTTP(t, apiRouter, credentials, bucketName, objectName, uploadID, etags, nil,
|
||||
map[string]string{typ.Key(): mustChecksum(t, typ, full)})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: completion without an explicit checksum type returned %d %s",
|
||||
instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("algorithm-mismatch-remains-invalid-argument", func(t *testing.T) {
|
||||
objectName := "type-mismatch/algorithm"
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, bucketName, objectName,
|
||||
typ.String(), xhttp.AmzChecksumTypeFullObject)
|
||||
etags := uploadPartsHTTP(t, apiRouter, credentials, bucketName, objectName, uploadID, typ, partData)
|
||||
rec := completeMultipartUploadHTTP(t, apiRouter, credentials, bucketName, objectName, uploadID, etags, nil,
|
||||
map[string]string{
|
||||
hash.ChecksumCRC32C.Key(): mustChecksum(t, hash.ChecksumCRC32C, full),
|
||||
xhttp.AmzChecksumType: xhttp.AmzChecksumTypeFullObject,
|
||||
})
|
||||
if rec.Code != http.StatusBadRequest || apiErrorCode(t, rec) != "InvalidArgument" {
|
||||
t.Fatalf("%s: algorithm mismatch returned %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("crc64nvme-composite-is-rejected", func(t *testing.T) {
|
||||
crc64Type := hash.ChecksumCRC64NVME
|
||||
objectName := "type-mismatch/crc64nvme-composite"
|
||||
req, err := newTestSignedRequestV4(http.MethodPost, getNewMultipartURL("", bucketName, objectName),
|
||||
0, nil, credentials.AccessKey, credentials.SecretKey, map[string]string{
|
||||
xhttp.AmzChecksumAlgo: crc64Type.String(),
|
||||
xhttp.AmzChecksumType: xhttp.AmzChecksumTypeComposite,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest || apiErrorCode(t, rec) != "InvalidArgument" {
|
||||
t.Fatalf("%s: CRC64NVME/COMPOSITE returned %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("crc64nvme-composite-completion-is-rejected", func(t *testing.T) {
|
||||
crc64Type := hash.ChecksumCRC64NVME
|
||||
objectName := "type-mismatch/crc64nvme-composite-completion"
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, bucketName, objectName,
|
||||
crc64Type.String(), xhttp.AmzChecksumTypeFullObject)
|
||||
etags := uploadPartsHTTP(t, apiRouter, credentials, bucketName, objectName, uploadID, crc64Type, partData)
|
||||
partCS := []string{mustChecksum(t, crc64Type, partData[0]), mustChecksum(t, crc64Type, partData[1])}
|
||||
rec := completeMultipartUploadHTTP(t, apiRouter, credentials, bucketName, objectName, uploadID, etags, partCS,
|
||||
map[string]string{xhttp.AmzChecksumType: xhttp.AmzChecksumTypeComposite})
|
||||
if rec.Code != http.StatusBadRequest || apiErrorCode(t, rec) != "BadDigest" {
|
||||
t.Fatalf("%s: CRC64NVME composite completion returned %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
if _, err := obj.GetObjectInfo(t.Context(), bucketName, objectName, ObjectOptions{}); err == nil {
|
||||
t.Fatalf("%s: object was created despite a rejected CRC64NVME checksum type", instanceType)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
// TestAPICompleteMultipartFullObjectVariants pins down the surrounding
|
||||
// behavior of the relaxation: what may be omitted, what must still match, and
|
||||
// that a zero length object is handled like any other.
|
||||
|
||||
@@ -0,0 +1,596 @@
|
||||
// Copyright (c) 2015-2026 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
"encoding/xml"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"testing"
|
||||
|
||||
"github.com/minio/minio/internal/auth"
|
||||
"github.com/minio/minio/internal/hash"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
"github.com/minio/minio/internal/kms"
|
||||
)
|
||||
|
||||
func uploadPartHTTP(t *testing.T, apiRouter http.Handler, creds auth.Credentials,
|
||||
bucket, object, uploadID string, partNumber int, data []byte, headers map[string]string,
|
||||
) (string, *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
req, err := newTestSignedRequestV4(http.MethodPut,
|
||||
getPutObjectPartURL("", bucket, object, uploadID, strconv.Itoa(partNumber)),
|
||||
int64(len(data)), bytes.NewReader(data), creds.AccessKey, creds.SecretKey, headers)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to build UploadPart request: %v", err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("UploadPart failed: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
return canonicalizeETag(rec.Header()[xhttp.ETag][0]), rec
|
||||
}
|
||||
|
||||
func listPartsHTTP(t *testing.T, apiRouter http.Handler, creds auth.Credentials,
|
||||
bucket, object, uploadID string, headers map[string]string,
|
||||
) ListPartsResponse {
|
||||
t.Helper()
|
||||
req, err := newTestSignedRequestV4(http.MethodGet,
|
||||
getListMultipartURLWithParams("", bucket, object, uploadID, "1000", "", ""),
|
||||
0, nil, creds.AccessKey, creds.SecretKey, headers)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to build ListParts request: %v", err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("ListParts failed: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var response ListPartsResponse
|
||||
if err := xml.Unmarshal(rec.Body.Bytes(), &response); err != nil {
|
||||
t.Fatalf("failed to decode ListParts response: %v", err)
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
func partChecksum(typ hash.ChecksumType, part Part) string {
|
||||
switch typ.Base() {
|
||||
case hash.ChecksumCRC32:
|
||||
return part.ChecksumCRC32
|
||||
case hash.ChecksumCRC32C:
|
||||
return part.ChecksumCRC32C
|
||||
case hash.ChecksumSHA1:
|
||||
return part.ChecksumSHA1
|
||||
case hash.ChecksumSHA256:
|
||||
return part.ChecksumSHA256
|
||||
case hash.ChecksumCRC64NVME:
|
||||
return part.ChecksumCRC64NVME
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func copyPartChecksum(typ hash.ChecksumType, response CopyObjectPartResponse) string {
|
||||
switch typ.Base() {
|
||||
case hash.ChecksumCRC32:
|
||||
return response.ChecksumCRC32
|
||||
case hash.ChecksumCRC32C:
|
||||
return response.ChecksumCRC32C
|
||||
case hash.ChecksumSHA1:
|
||||
return response.ChecksumSHA1
|
||||
case hash.ChecksumSHA256:
|
||||
return response.ChecksumSHA256
|
||||
case hash.ChecksumCRC64NVME:
|
||||
return response.ChecksumCRC64NVME
|
||||
default:
|
||||
return ""
|
||||
}
|
||||
}
|
||||
|
||||
func completePartWithChecksum(typ hash.ChecksumType, partNumber int, etag, checksum string) CompletePart {
|
||||
part := CompletePart{PartNumber: partNumber, ETag: etag}
|
||||
switch typ.Base() {
|
||||
case hash.ChecksumCRC32:
|
||||
part.ChecksumCRC32 = checksum
|
||||
case hash.ChecksumCRC32C:
|
||||
part.ChecksumCRC32C = checksum
|
||||
case hash.ChecksumSHA1:
|
||||
part.ChecksumSHA1 = checksum
|
||||
case hash.ChecksumSHA256:
|
||||
part.ChecksumSHA256 = checksum
|
||||
case hash.ChecksumCRC64NVME:
|
||||
part.ChecksumCRC64NVME = checksum
|
||||
}
|
||||
return part
|
||||
}
|
||||
|
||||
func completePartsHTTP(t *testing.T, apiRouter http.Handler, creds auth.Credentials,
|
||||
bucket, object, uploadID string, parts []CompletePart, headers map[string]string,
|
||||
) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
body, err := xml.Marshal(CompleteMultipartUpload{Parts: parts})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to encode CompleteMultipartUpload request: %v", err)
|
||||
}
|
||||
req, err := newTestSignedRequestV4(http.MethodPost,
|
||||
getCompleteMultipartUploadURL("", bucket, object, uploadID),
|
||||
int64(len(body)), bytes.NewReader(body), creds.AccessKey, creds.SecretKey, headers)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to build CompleteMultipartUpload request: %v", err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func copyPartWithoutChecksumHTTP(t *testing.T, apiRouter http.Handler, creds auth.Credentials,
|
||||
bucket, source, object, uploadID, sourceRange string, headers map[string]string,
|
||||
) CopyObjectPartResponse {
|
||||
t.Helper()
|
||||
req, err := newTestSignedRequestV4(http.MethodPut,
|
||||
getCopyObjectPartURL("", bucket, object, uploadID, "1"),
|
||||
0, nil, creds.AccessKey, creds.SecretKey, headers)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to build UploadPartCopy request: %v", err)
|
||||
}
|
||||
req.Header.Set(xhttp.AmzCopySource, SlashSeparator+pathJoin(bucket, source))
|
||||
if sourceRange != "" {
|
||||
req.Header.Set(xhttp.AmzCopySourceRange, sourceRange)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("UploadPartCopy failed: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var response CopyObjectPartResponse
|
||||
if err := xml.Unmarshal(rec.Body.Bytes(), &response); err != nil {
|
||||
t.Fatalf("failed to decode UploadPartCopy response: %v", err)
|
||||
}
|
||||
return response
|
||||
}
|
||||
|
||||
// TestAPIUploadPartServerSideChecksum exercises the data transformations that
|
||||
// made installing a checksum hasher in the object layer unsafe. The checksum
|
||||
// must always cover logical plaintext, regardless of compression or encryption.
|
||||
func TestAPIUploadPartServerSideChecksum(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecExtendedObjectLayerAPITest(t, testAPIUploadPartServerSideChecksum,
|
||||
[]string{"CopyObjectPart", "PutObjectPart", "NewMultipart", "ListObjectParts", "CompleteMultipart"})
|
||||
}
|
||||
|
||||
func testAPIUploadPartServerSideChecksum(obj ObjectLayer, instanceType, bucketName string, apiRouter http.Handler,
|
||||
credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
typ := hash.ChecksumCRC32
|
||||
data := bytes.Repeat([]byte("multipart-checksum-plaintext-"), 48*1024)
|
||||
want := mustChecksum(t, typ, data)
|
||||
|
||||
t.Run("upload", func(t *testing.T) {
|
||||
object := "checksums/upload"
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, bucketName, object,
|
||||
typ.String(), xhttp.AmzChecksumTypeFullObject)
|
||||
etag, rec := uploadPartHTTP(t, apiRouter, credentials,
|
||||
bucketName, object, uploadID, 1, data, nil)
|
||||
if got := rec.Header().Get(typ.Key()); got != "" {
|
||||
t.Fatalf("%s: UploadPart returned server-computed checksum %q", instanceType, got)
|
||||
}
|
||||
|
||||
listed := listPartsHTTP(t, apiRouter, credentials, bucketName, object, uploadID, nil)
|
||||
if len(listed.Parts) != 1 || partChecksum(typ, listed.Parts[0]) != want {
|
||||
t.Fatalf("%s: ListParts checksum mismatch: %+v, want %q", instanceType, listed.Parts, want)
|
||||
}
|
||||
|
||||
rec = completePartsHTTP(t, apiRouter, credentials, bucketName, object, uploadID,
|
||||
[]CompletePart{{PartNumber: 1, ETag: etag}}, nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: CompleteMultipartUpload failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
oi, err := obj.GetObjectInfo(t.Context(), bucketName, object, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("%s: GetObjectInfo failed: %v", instanceType, err)
|
||||
}
|
||||
checksums, _ := oi.decryptChecksums(0, nil)
|
||||
if got := checksums[typ.String()]; got != want {
|
||||
t.Fatalf("%s: stored checksum %q, want plaintext checksum %q", instanceType, got, want)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("copy", func(t *testing.T) {
|
||||
source := "checksums/source"
|
||||
if _, err := obj.PutObject(t.Context(), bucketName, source,
|
||||
mustGetPutObjReader(t, bytes.NewReader(data), int64(len(data)), "", ""), ObjectOptions{}); err != nil {
|
||||
t.Fatalf("%s: source PutObject failed: %v", instanceType, err)
|
||||
}
|
||||
object := "checksums/copy"
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, bucketName, object,
|
||||
typ.String(), xhttp.AmzChecksumTypeFullObject)
|
||||
response := copyPartWithoutChecksumHTTP(t, apiRouter, credentials,
|
||||
bucketName, source, object, uploadID, "", nil)
|
||||
if got := copyPartChecksum(typ, response); got != want {
|
||||
t.Fatalf("%s: UploadPartCopy checksum %q, want %q", instanceType, got, want)
|
||||
}
|
||||
|
||||
listed := listPartsHTTP(t, apiRouter, credentials, bucketName, object, uploadID, nil)
|
||||
if len(listed.Parts) != 1 || partChecksum(typ, listed.Parts[0]) != want {
|
||||
t.Fatalf("%s: copied ListParts checksum mismatch: %+v, want %q", instanceType, listed.Parts, want)
|
||||
}
|
||||
|
||||
rec := completePartsHTTP(t, apiRouter, credentials, bucketName, object, uploadID,
|
||||
[]CompletePart{{PartNumber: 1, ETag: canonicalizeETag(response.ETag)}}, nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: copied CompleteMultipartUpload failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestAPIUploadPartServerSideChecksumAlgorithms(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPIUploadPartServerSideChecksumAlgorithms,
|
||||
endpoints: []string{"CopyObjectPart", "PutObjectPart", "NewMultipart", "ListObjectParts", "CompleteMultipart"},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPIUploadPartServerSideChecksumAlgorithms(obj ObjectLayer, instanceType, bucketName string, apiRouter http.Handler,
|
||||
credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
tests := []struct {
|
||||
typ hash.ChecksumType
|
||||
objType string
|
||||
composite bool
|
||||
}{
|
||||
{hash.ChecksumCRC32, xhttp.AmzChecksumTypeFullObject, false},
|
||||
{hash.ChecksumCRC32C, xhttp.AmzChecksumTypeFullObject, false},
|
||||
{hash.ChecksumCRC64NVME, xhttp.AmzChecksumTypeFullObject, false},
|
||||
{hash.ChecksumCRC32, xhttp.AmzChecksumTypeComposite, true},
|
||||
{hash.ChecksumSHA1, xhttp.AmzChecksumTypeComposite, true},
|
||||
{hash.ChecksumSHA256, xhttp.AmzChecksumTypeComposite, true},
|
||||
}
|
||||
data := bytes.Repeat([]byte("server-side-part-checksum"), 1024)
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.typ.String()+"/"+test.objType, func(t *testing.T) {
|
||||
object := "algorithms/" + test.typ.String() + "/" + test.objType
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, bucketName, object,
|
||||
test.typ.String(), test.objType)
|
||||
etag, rec := uploadPartHTTP(t, apiRouter, credentials,
|
||||
bucketName, object, uploadID, 1, data, nil)
|
||||
if got := rec.Header().Get(test.typ.Key()); got != "" {
|
||||
t.Fatalf("%s: UploadPart returned server-computed checksum %q", instanceType, got)
|
||||
}
|
||||
|
||||
want := mustChecksum(t, test.typ, data)
|
||||
listed := listPartsHTTP(t, apiRouter, credentials, bucketName, object, uploadID, nil)
|
||||
if len(listed.Parts) != 1 || partChecksum(test.typ, listed.Parts[0]) != want {
|
||||
t.Fatalf("%s: ListParts checksum mismatch: %+v, want %q", instanceType, listed.Parts, want)
|
||||
}
|
||||
|
||||
part := CompletePart{PartNumber: 1, ETag: etag}
|
||||
if test.composite {
|
||||
part = completePartWithChecksum(test.typ, 1, etag, want)
|
||||
}
|
||||
rec = completePartsHTTP(t, apiRouter, credentials, bucketName, object, uploadID,
|
||||
[]CompletePart{part}, nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: CompleteMultipartUpload failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
t.Run("multi-part/FULL_OBJECT", func(t *testing.T) {
|
||||
typ := hash.ChecksumCRC32
|
||||
parts, full := multipartChecksumTestData()
|
||||
object := "algorithms/multi-part-full-object"
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, bucketName, object,
|
||||
typ.String(), xhttp.AmzChecksumTypeFullObject)
|
||||
etags := make([]string, len(parts))
|
||||
for i, data := range parts {
|
||||
etag, rec := uploadPartHTTP(t, apiRouter, credentials,
|
||||
bucketName, object, uploadID, i+1, data, nil)
|
||||
if got := rec.Header().Get(typ.Key()); got != "" {
|
||||
t.Fatalf("%s: UploadPart returned server-computed checksum %q", instanceType, got)
|
||||
}
|
||||
etags[i] = etag
|
||||
}
|
||||
|
||||
listed := listPartsHTTP(t, apiRouter, credentials, bucketName, object, uploadID, nil)
|
||||
if len(listed.Parts) != len(parts) {
|
||||
t.Fatalf("%s: ListParts returned %d parts, want %d", instanceType, len(listed.Parts), len(parts))
|
||||
}
|
||||
for i, part := range listed.Parts {
|
||||
if got, want := partChecksum(typ, part), mustChecksum(t, typ, parts[i]); got != want {
|
||||
t.Fatalf("%s: part %d checksum %q, want %q", instanceType, i+1, got, want)
|
||||
}
|
||||
}
|
||||
|
||||
complete := make([]CompletePart, len(etags))
|
||||
for i, etag := range etags {
|
||||
complete[i] = CompletePart{PartNumber: i + 1, ETag: etag}
|
||||
}
|
||||
rec := completePartsHTTP(t, apiRouter, credentials, bucketName, object, uploadID, complete,
|
||||
map[string]string{
|
||||
typ.Key(): mustChecksum(t, typ, full),
|
||||
xhttp.AmzChecksumType: xhttp.AmzChecksumTypeFullObject,
|
||||
})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: multi-part CompleteMultipartUpload failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("zero-length-part", func(t *testing.T) {
|
||||
typ := hash.ChecksumCRC32
|
||||
object := "algorithms/zero-length"
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, bucketName, object,
|
||||
typ.String(), xhttp.AmzChecksumTypeFullObject)
|
||||
etag, _ := uploadPartHTTP(t, apiRouter, credentials,
|
||||
bucketName, object, uploadID, 1, nil, nil)
|
||||
listed := listPartsHTTP(t, apiRouter, credentials, bucketName, object, uploadID, nil)
|
||||
if len(listed.Parts) != 1 || partChecksum(typ, listed.Parts[0]) != mustChecksum(t, typ, nil) {
|
||||
t.Fatalf("%s: zero-length ListParts checksum mismatch: %+v", instanceType, listed.Parts)
|
||||
}
|
||||
rec := completePartsHTTP(t, apiRouter, credentials, bucketName, object, uploadID,
|
||||
[]CompletePart{{PartNumber: 1, ETag: etag}}, nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: zero-length CompleteMultipartUpload failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("overwrite-part-checksum", func(t *testing.T) {
|
||||
typ := hash.ChecksumCRC32
|
||||
object := "algorithms/overwrite"
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, bucketName, object,
|
||||
typ.String(), xhttp.AmzChecksumTypeFullObject)
|
||||
first := []byte("first part contents")
|
||||
second := []byte("replacement part contents")
|
||||
uploadPartHTTP(t, apiRouter, credentials, bucketName, object, uploadID, 1, first, nil)
|
||||
etag, _ := uploadPartHTTP(t, apiRouter, credentials, bucketName, object, uploadID, 1, second, nil)
|
||||
listed := listPartsHTTP(t, apiRouter, credentials, bucketName, object, uploadID, nil)
|
||||
if len(listed.Parts) != 1 || partChecksum(typ, listed.Parts[0]) != mustChecksum(t, typ, second) {
|
||||
t.Fatalf("%s: overwritten ListParts checksum mismatch: %+v", instanceType, listed.Parts)
|
||||
}
|
||||
rec := completePartsHTTP(t, apiRouter, credentials, bucketName, object, uploadID,
|
||||
[]CompletePart{{PartNumber: 1, ETag: etag}}, nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: overwritten CompleteMultipartUpload failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("copy/SHA256/COMPOSITE", func(t *testing.T) {
|
||||
typ := hash.ChecksumSHA256
|
||||
source := "algorithms/copy-source"
|
||||
if _, err := obj.PutObject(t.Context(), bucketName, source,
|
||||
mustGetPutObjReader(t, bytes.NewReader(data), int64(len(data)), "", ""), ObjectOptions{}); err != nil {
|
||||
t.Fatalf("%s: source PutObject failed: %v", instanceType, err)
|
||||
}
|
||||
object := "algorithms/copy-SHA256"
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, bucketName, object,
|
||||
typ.String(), xhttp.AmzChecksumTypeComposite)
|
||||
start, end := 7, len(data)-9
|
||||
response := copyPartWithoutChecksumHTTP(t, apiRouter, credentials,
|
||||
bucketName, source, object, uploadID, "bytes="+strconv.Itoa(start)+"-"+strconv.Itoa(end-1), nil)
|
||||
want := mustChecksum(t, typ, data[start:end])
|
||||
if got := copyPartChecksum(typ, response); got != want {
|
||||
t.Fatalf("%s: UploadPartCopy checksum %q, want %q", instanceType, got, want)
|
||||
}
|
||||
|
||||
part := completePartWithChecksum(typ, 1, canonicalizeETag(response.ETag), want)
|
||||
rec := completePartsHTTP(t, apiRouter, credentials, bucketName, object, uploadID,
|
||||
[]CompletePart{part}, nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: copied CompleteMultipartUpload failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestAPIUploadPartServerSideChecksumDoesNotMaskClientErrors(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPIUploadPartServerSideChecksumDoesNotMaskClientErrors,
|
||||
endpoints: []string{"PutObjectPart", "NewMultipart", "ListObjectParts"},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPIUploadPartServerSideChecksumDoesNotMaskClientErrors(_ ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
data := []byte("client checksum must remain authoritative")
|
||||
|
||||
t.Run("correct-value", func(t *testing.T) {
|
||||
typ := hash.ChecksumCRC32
|
||||
object := "errors/correct-value"
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, bucketName, object,
|
||||
typ.String(), xhttp.AmzChecksumTypeFullObject)
|
||||
want := mustChecksum(t, typ, data)
|
||||
_, rec := uploadPartHTTP(t, apiRouter, credentials,
|
||||
bucketName, object, uploadID, 1, data, map[string]string{typ.Key(): want})
|
||||
if got := rec.Header().Get(typ.Key()); got != want {
|
||||
t.Fatalf("%s: client checksum response %q, want %q", instanceType, got, want)
|
||||
}
|
||||
listed := listPartsHTTP(t, apiRouter, credentials, bucketName, object, uploadID, nil)
|
||||
if len(listed.Parts) != 1 || partChecksum(typ, listed.Parts[0]) != want {
|
||||
t.Fatalf("%s: client checksum ListParts mismatch: %+v", instanceType, listed.Parts)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("wrong-algorithm", func(t *testing.T) {
|
||||
object := "errors/wrong-algorithm"
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, bucketName, object,
|
||||
hash.ChecksumCRC32.String(), xhttp.AmzChecksumTypeFullObject)
|
||||
req, err := newTestSignedRequestV4(http.MethodPut,
|
||||
getPutObjectPartURL("", bucketName, object, uploadID, "1"),
|
||||
int64(len(data)), bytes.NewReader(data), credentials.AccessKey, credentials.SecretKey,
|
||||
map[string]string{hash.ChecksumSHA256.Key(): mustChecksum(t, hash.ChecksumSHA256, data)})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to build UploadPart request: %v", err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest || apiErrorCode(t, rec) != "InvalidArgument" {
|
||||
t.Fatalf("%s: wrong algorithm returned %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("wrong-value", func(t *testing.T) {
|
||||
object := "errors/wrong-value"
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, bucketName, object,
|
||||
hash.ChecksumCRC32.String(), xhttp.AmzChecksumTypeFullObject)
|
||||
req, err := newTestSignedRequestV4(http.MethodPut,
|
||||
getPutObjectPartURL("", bucketName, object, uploadID, "1"),
|
||||
int64(len(data)), bytes.NewReader(data), credentials.AccessKey, credentials.SecretKey,
|
||||
map[string]string{hash.ChecksumCRC32.Key(): mustChecksum(t, hash.ChecksumCRC32, []byte("wrong"))})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to build UploadPart request: %v", err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest || apiErrorCode(t, rec) != "XAmzContentChecksumMismatch" {
|
||||
t.Fatalf("%s: wrong value returned %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestAPIUploadPartServerSideChecksumSSEC(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPIUploadPartServerSideChecksumSSEC,
|
||||
endpoints: []string{"PutObjectPart", "NewMultipart", "CompleteMultipart"},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPIUploadPartServerSideChecksumSSEC(_ ObjectLayer, instanceType, bucketName string, apiRouter http.Handler,
|
||||
credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
globalIsTLS = true
|
||||
defer func() { globalIsTLS = false }()
|
||||
|
||||
key := bytes.Repeat([]byte{0x2a}, 32)
|
||||
keyMD5 := md5.Sum(key)
|
||||
ssecHeaders := map[string]string{
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(key),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(keyMD5[:]),
|
||||
}
|
||||
initHeaders := map[string]string{
|
||||
xhttp.AmzChecksumAlgo: hash.ChecksumCRC32.String(),
|
||||
xhttp.AmzChecksumType: xhttp.AmzChecksumTypeFullObject,
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: ssecHeaders[xhttp.AmzServerSideEncryptionCustomerAlgorithm],
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: ssecHeaders[xhttp.AmzServerSideEncryptionCustomerKey],
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: ssecHeaders[xhttp.AmzServerSideEncryptionCustomerKeyMD5],
|
||||
}
|
||||
object := "checksums/ssec"
|
||||
req, err := newTestSignedRequestV4(http.MethodPost, getNewMultipartURL("", bucketName, object),
|
||||
0, nil, credentials.AccessKey, credentials.SecretKey, initHeaders)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to build NewMultipartUpload request: %v", err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: NewMultipartUpload failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
var initiated InitiateMultipartUploadResponse
|
||||
if err := xml.Unmarshal(rec.Body.Bytes(), &initiated); err != nil {
|
||||
t.Fatalf("failed to decode NewMultipartUpload response: %v", err)
|
||||
}
|
||||
|
||||
data := bytes.Repeat([]byte("ssec-checksum-plaintext"), 4096)
|
||||
etag, uploadRec := uploadPartHTTP(t, apiRouter, credentials,
|
||||
bucketName, object, initiated.UploadID, 1, data, ssecHeaders)
|
||||
if got := uploadRec.Header().Get(hash.ChecksumCRC32.Key()); got != "" {
|
||||
t.Fatalf("%s: UploadPart returned server-computed checksum %q", instanceType, got)
|
||||
}
|
||||
|
||||
completeHeaders := map[string]string{
|
||||
xhttp.AmzChecksumCRC32: mustChecksum(t, hash.ChecksumCRC32, data),
|
||||
xhttp.AmzChecksumType: xhttp.AmzChecksumTypeFullObject,
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: ssecHeaders[xhttp.AmzServerSideEncryptionCustomerAlgorithm],
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: ssecHeaders[xhttp.AmzServerSideEncryptionCustomerKey],
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: ssecHeaders[xhttp.AmzServerSideEncryptionCustomerKeyMD5],
|
||||
}
|
||||
rec = completePartsHTTP(t, apiRouter, credentials, bucketName, object, initiated.UploadID,
|
||||
[]CompletePart{{PartNumber: 1, ETag: etag}}, completeHeaders)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: CompleteMultipartUpload failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIUploadPartServerSideChecksumSSES3(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPIUploadPartServerSideChecksumSSES3,
|
||||
endpoints: []string{"PutObjectPart", "NewMultipart", "CompleteMultipart"},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPIUploadPartServerSideChecksumSSES3(_ ObjectLayer, instanceType, bucketName string, apiRouter http.Handler,
|
||||
credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
KMS, err := kms.ParseSecretKey("my-minio-key:5lF+0pJM0OWwlQrvK2S/I7W9mO4a6rJJI7wzj7v09cw=")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
GlobalKMS = KMS
|
||||
defer func() { GlobalKMS = nil }()
|
||||
|
||||
object := "checksums/sse-s3"
|
||||
initHeaders := map[string]string{
|
||||
xhttp.AmzChecksumAlgo: hash.ChecksumCRC32.String(),
|
||||
xhttp.AmzChecksumType: xhttp.AmzChecksumTypeFullObject,
|
||||
xhttp.AmzServerSideEncryption: xhttp.AmzEncryptionAES,
|
||||
}
|
||||
req, err := newTestSignedRequestV4(http.MethodPost, getNewMultipartURL("", bucketName, object),
|
||||
0, nil, credentials.AccessKey, credentials.SecretKey, initHeaders)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to build NewMultipartUpload request: %v", err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: NewMultipartUpload failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
var initiated InitiateMultipartUploadResponse
|
||||
if err := xml.Unmarshal(rec.Body.Bytes(), &initiated); err != nil {
|
||||
t.Fatalf("failed to decode NewMultipartUpload response: %v", err)
|
||||
}
|
||||
|
||||
data := bytes.Repeat([]byte("sse-s3-checksum-plaintext"), 4096)
|
||||
etag, uploadRec := uploadPartHTTP(t, apiRouter, credentials,
|
||||
bucketName, object, initiated.UploadID, 1, data, nil)
|
||||
if got := uploadRec.Header().Get(hash.ChecksumCRC32.Key()); got != "" {
|
||||
t.Fatalf("%s: UploadPart returned server-computed checksum %q", instanceType, got)
|
||||
}
|
||||
|
||||
rec = completePartsHTTP(t, apiRouter, credentials, bucketName, object, initiated.UploadID,
|
||||
[]CompletePart{{PartNumber: 1, ETag: etag}}, map[string]string{
|
||||
xhttp.AmzChecksumCRC32: mustChecksum(t, hash.ChecksumCRC32, data),
|
||||
xhttp.AmzChecksumType: xhttp.AmzChecksumTypeFullObject,
|
||||
})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: CompleteMultipartUpload failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
+42
-25
@@ -597,12 +597,15 @@ func (er erasureObjects) PutObjectPart(ctx context.Context, bucket, object, uplo
|
||||
onlineDisks := er.getDisks()
|
||||
writeQuorum := fi.WriteQuorum(er.defaultWQuorum())
|
||||
|
||||
if cs := fi.Metadata[hash.MinIOMultipartChecksum]; cs != "" {
|
||||
if r.ContentCRCType().String() != cs {
|
||||
expectedChecksumType, checksumEnabled := multipartChecksumType(fi.Metadata)
|
||||
if checksumEnabled {
|
||||
got := r.contentChecksumType()
|
||||
if !expectedChecksumType.IsSet() || !got.IsSet() || got.Base() != expectedChecksumType {
|
||||
return pi, InvalidArgument{
|
||||
Bucket: bucket,
|
||||
Object: fi.Name,
|
||||
Err: fmt.Errorf("checksum missing, want %q, got %q", cs, r.ContentCRCType().String()),
|
||||
Err: fmt.Errorf("checksum missing, want %q, got %q",
|
||||
fi.Metadata[hash.MinIOMultipartChecksum], got.String()),
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -725,6 +728,13 @@ func (er erasureObjects) PutObjectPart(ctx context.Context, bucket, object, uplo
|
||||
}
|
||||
}
|
||||
|
||||
partChecksums := r.contentChecksum()
|
||||
if checksumEnabled && partChecksums[expectedChecksumType.String()] == "" {
|
||||
err := fmt.Errorf("internal error: checksum missing after reading part, want %q", expectedChecksumType.String())
|
||||
bugLogIf(ctx, err)
|
||||
return pi, toObjectErr(err, bucket, object, uploadID)
|
||||
}
|
||||
|
||||
partInfo := ObjectPartInfo{
|
||||
Number: partID,
|
||||
ETag: md5hex,
|
||||
@@ -732,7 +742,7 @@ func (er erasureObjects) PutObjectPart(ctx context.Context, bucket, object, uplo
|
||||
ActualSize: actualSize,
|
||||
ModTime: UTCNow(),
|
||||
Index: index,
|
||||
Checksums: r.ContentCRC(),
|
||||
Checksums: partChecksums,
|
||||
}
|
||||
|
||||
partFI, err := partInfo.MarshalMsg(nil)
|
||||
@@ -1163,11 +1173,20 @@ func (er erasureObjects) CompleteMultipartUpload(ctx context.Context, bucket str
|
||||
var checksumType hash.ChecksumType
|
||||
if cs := fi.Metadata[hash.MinIOMultipartChecksum]; cs != "" {
|
||||
checksumType = hash.NewChecksumType(cs, fi.Metadata[hash.MinIOMultipartChecksumType])
|
||||
if opts.WantChecksum != nil && !opts.WantChecksum.Type.Is(checksumType) {
|
||||
return oi, InvalidArgument{
|
||||
Bucket: bucket,
|
||||
Object: fi.Name,
|
||||
Err: fmt.Errorf("checksum type mismatch. got %q (%s) expected %q (%s)", checksumType.String(), checksumType.ObjType(), opts.WantChecksum.Type.String(), opts.WantChecksum.Type.ObjType()),
|
||||
expectedType := checksumType | hash.ChecksumMultipart | hash.ChecksumIncludesMultipart
|
||||
if opts.WantChecksum != nil {
|
||||
providedType := opts.WantChecksum.Type | hash.ChecksumMultipart | hash.ChecksumIncludesMultipart
|
||||
if providedType.Base() != expectedType.Base() {
|
||||
return oi, InvalidArgument{
|
||||
Bucket: bucket,
|
||||
Object: fi.Name,
|
||||
Err: fmt.Errorf("checksum algorithm mismatch. got %q expected %q", providedType.String(), expectedType.String()),
|
||||
}
|
||||
}
|
||||
}
|
||||
if opts.wantChecksumType != "" {
|
||||
if opts.wantChecksumType != expectedType.ObjType() {
|
||||
return oi, completeMultipartChecksumTypeMismatch(opts.wantChecksumType, expectedType.ObjType())
|
||||
}
|
||||
}
|
||||
checksumType |= hash.ChecksumMultipart | hash.ChecksumIncludesMultipart
|
||||
@@ -1298,19 +1317,18 @@ func (er erasureObjects) CompleteMultipartUpload(ctx context.Context, bucket str
|
||||
break
|
||||
}
|
||||
}
|
||||
// Part checksums are optional in the CompleteMultipartUpload body when
|
||||
// the upload was created with a full object checksum type: clients send
|
||||
// the object level checksum instead and do not retain part checksums.
|
||||
// A part that carries any checksum at all is still validated against
|
||||
// what we stored - including one sent under the wrong algorithm, which
|
||||
// cannot match and is rejected. The object level checksum, if supplied,
|
||||
// is verified against the merged part checksums below.
|
||||
allowMissingPartCS := checksumType.FullObjectRequested() && !suppliedAnyCS
|
||||
if !allowMissingPartCS && gotCS != crc {
|
||||
// Full object completions may omit part checksums. Composite
|
||||
// completions may not. Any checksum that is supplied is still
|
||||
// validated, including one sent under the wrong algorithm.
|
||||
if !suppliedAnyCS {
|
||||
if !checksumType.FullObjectRequested() {
|
||||
return oi, missingPartChecksum(checksumType.String(), part.PartNumber)
|
||||
}
|
||||
} else if gotCS != crc {
|
||||
return oi, InvalidPart{
|
||||
PartNumber: part.PartNumber,
|
||||
ExpETag: gotCS,
|
||||
GotETag: crc,
|
||||
ExpETag: crc,
|
||||
GotETag: gotCS,
|
||||
}
|
||||
}
|
||||
cs := hash.NewChecksumString(checksumType.String(), crc)
|
||||
@@ -1360,15 +1378,14 @@ func (er erasureObjects) CompleteMultipartUpload(ctx context.Context, bucket str
|
||||
if opts.WantChecksum != nil {
|
||||
if checksumType.FullObjectRequested() {
|
||||
if opts.WantChecksum.Encoded != checksum.Encoded {
|
||||
err := hash.ChecksumMismatch{
|
||||
Want: opts.WantChecksum.Encoded,
|
||||
Got: checksum.Encoded,
|
||||
}
|
||||
return oi, err
|
||||
return oi, completeMultipartChecksumMismatch(checksumType.String())
|
||||
}
|
||||
} else {
|
||||
err := opts.WantChecksum.Matches(checksumCombined, len(parts))
|
||||
if err != nil {
|
||||
if hash.IsChecksumMismatch(err) {
|
||||
return oi, completeMultipartChecksumMismatch(checksumType.String())
|
||||
}
|
||||
return oi, err
|
||||
}
|
||||
}
|
||||
|
||||
+21
-7
@@ -266,9 +266,19 @@ func (er erasureObjects) GetObjectNInfo(ctx context.Context, bucket, object stri
|
||||
ObjInfo: objInfo,
|
||||
}, err
|
||||
}
|
||||
|
||||
// Zero byte objects don't even need to further initialize pipes etc.
|
||||
return NewGetObjectReaderFromReader(bytes.NewReader(nil), objInfo, opts)
|
||||
gr, err = NewGetObjectReaderFromReader(bytes.NewReader(nil), objInfo, opts)
|
||||
if err != nil {
|
||||
return gr, err
|
||||
}
|
||||
// With no data, the reader above cannot authenticate an SSE-C key the
|
||||
// way NewGetObjectReader does. Check it after the preconditions so zero
|
||||
// and non-zero reads preserve the same error ordering.
|
||||
if err := checkSSECReadKey(h, objInfo, opts); err != nil {
|
||||
gr.Close()
|
||||
return nil, err
|
||||
}
|
||||
return gr, nil
|
||||
}
|
||||
|
||||
if objInfo.IsRemote() {
|
||||
@@ -1485,11 +1495,15 @@ func (er erasureObjects) putObject(ctx context.Context, bucket string, object st
|
||||
// over opts.WantChecksum.
|
||||
if opts.WantServerSideChecksumType.IsSet() {
|
||||
serverSideChecksum := r.RawServerSideChecksumResult()
|
||||
if serverSideChecksum != nil {
|
||||
fi.Checksum = serverSideChecksum.AppendTo(nil, nil)
|
||||
if opts.EncryptFn != nil {
|
||||
fi.Checksum = opts.EncryptFn("object-checksum", fi.Checksum)
|
||||
}
|
||||
if serverSideChecksum == nil || !serverSideChecksum.Valid() ||
|
||||
serverSideChecksum.Type.Base() != opts.WantServerSideChecksumType.Base() {
|
||||
err := fmt.Errorf("internal error: server-side checksum missing, invalid, or mismatched after reading object, want %q", opts.WantServerSideChecksumType.String())
|
||||
bugLogIf(ctx, err)
|
||||
return ObjectInfo{}, toObjectErr(err, bucket, object)
|
||||
}
|
||||
fi.Checksum = serverSideChecksum.AppendTo(nil, nil)
|
||||
if opts.EncryptFn != nil {
|
||||
fi.Checksum = opts.EncryptFn("object-checksum", fi.Checksum)
|
||||
}
|
||||
} else if fi.Checksum == nil && opts.WantChecksum != nil {
|
||||
// Trailing headers checksums should now be filled.
|
||||
|
||||
@@ -1328,6 +1328,8 @@ func (z *erasureServerPools) CopyObject(ctx context.Context, srcBucket, srcObjec
|
||||
return objInfo, err
|
||||
}
|
||||
|
||||
// CopyObjectHandler predicts the outcome of this decision in
|
||||
// copyRewritesObjectData(); keep the two in sync.
|
||||
if cpSrcDstSame && srcInfo.metadataOnly {
|
||||
// Version ID is set for the destination and source == destination version ID.
|
||||
if dstOpts.VersionID != "" && srcOpts.VersionID == dstOpts.VersionID {
|
||||
|
||||
@@ -839,6 +839,8 @@ func (s *erasureSets) CopyObject(ctx context.Context, srcBucket, srcObject, dstB
|
||||
|
||||
cpSrcDstSame := srcSet == dstSet
|
||||
// Check if this request is only metadata update.
|
||||
// CopyObjectHandler predicts the outcome of this decision in
|
||||
// copyRewritesObjectData(); keep the two in sync.
|
||||
if cpSrcDstSame && srcInfo.metadataOnly {
|
||||
// Version ID is set for the destination and source == destination version ID.
|
||||
// perform an in-place update.
|
||||
|
||||
@@ -476,9 +476,10 @@ func setRequestValidityMiddleware(h http.Handler) http.Handler {
|
||||
// is obtained from centralized etcd configuration service.
|
||||
func setBucketForwardingMiddleware(h http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if origin := w.Header().Get("Access-Control-Allow-Origin"); origin == "null" {
|
||||
if origin := w.Header().Get("Access-Control-Allow-Origin"); origin == "null" && !bucketCorsWasApplied(r) {
|
||||
// This is a workaround change to ensure that "Origin: null"
|
||||
// incoming request to a response back as "*" instead of "null"
|
||||
// incoming request to a response back as "*" instead of "null".
|
||||
// Per-bucket CORS preserves an explicitly allowed "null" origin.
|
||||
w.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
}
|
||||
if globalDNSConfig == nil || !globalBucketFederation ||
|
||||
|
||||
@@ -83,7 +83,6 @@ var supportedHeaders = []string{
|
||||
xhttp.AmzStorageClass,
|
||||
xhttp.AmzObjectTagging,
|
||||
"expires",
|
||||
xhttp.AmzBucketReplicationStatus,
|
||||
"X-Minio-Replication-Server-Side-Encryption-Sealed-Key",
|
||||
"X-Minio-Replication-Server-Side-Encryption-Seal-Algorithm",
|
||||
"X-Minio-Replication-Server-Side-Encryption-Iv",
|
||||
@@ -332,7 +331,7 @@ func extractReqParams(r *http.Request) map[string]string {
|
||||
m["range"] = rangeField
|
||||
}
|
||||
|
||||
if _, ok := r.Header[xhttp.MinIOSourceReplicationRequest]; ok {
|
||||
if isTrustedReplication(r.Context()) {
|
||||
m[xhttp.MinIOSourceReplicationRequest] = ""
|
||||
}
|
||||
return m
|
||||
|
||||
@@ -307,7 +307,7 @@ func TestGetCopyObjectMetadataFromHeaderReplication(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloneRequestWithoutCopyReplicationHeaders(t *testing.T) {
|
||||
func TestCloneRequestWithoutReplicationHeaders(t *testing.T) {
|
||||
req, err := http.NewRequest(http.MethodPut, "http://localhost/test", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
@@ -320,9 +320,12 @@ func TestCloneRequestWithoutCopyReplicationHeaders(t *testing.T) {
|
||||
req.Header.Set(xhttp.MinIOSourceObjectLegalHoldTimestamp, "2026-04-15T10:00:00Z")
|
||||
req.Header.Set(xhttp.MinIOReplicationActualObjectSize, "123")
|
||||
req.Header.Set(ReplicationSsecChecksumHeader, "checksum")
|
||||
req.Header.Set(xhttp.AmzBucketReplicationStatus, "REPLICA")
|
||||
req.Header.Set(xhttp.MinIOSourceDeleteMarker, "true")
|
||||
req.Header.Set("X-Minio-Replication-Server-Side-Encryption-Sealed-Key", "sealed")
|
||||
req.Header.Set("Content-Type", "application/octet-stream")
|
||||
|
||||
clone := cloneRequestWithoutCopyReplicationHeaders(req)
|
||||
clone := cloneRequestWithoutReplicationHeaders(t.Context(), req)
|
||||
if clone == req {
|
||||
t.Fatal("expected cloned request")
|
||||
}
|
||||
@@ -336,6 +339,9 @@ func TestCloneRequestWithoutCopyReplicationHeaders(t *testing.T) {
|
||||
xhttp.MinIOSourceObjectLegalHoldTimestamp,
|
||||
xhttp.MinIOReplicationActualObjectSize,
|
||||
ReplicationSsecChecksumHeader,
|
||||
xhttp.AmzBucketReplicationStatus,
|
||||
xhttp.MinIOSourceDeleteMarker,
|
||||
"X-Minio-Replication-Server-Side-Encryption-Sealed-Key",
|
||||
} {
|
||||
if got := clone.Header.Get(header); got != "" {
|
||||
t.Fatalf("expected %s to be stripped, got %q", header, got)
|
||||
|
||||
@@ -71,13 +71,13 @@ func (z *erasureServerPools) listPath(ctx context.Context, o *listPathOptions) (
|
||||
if o.Marker != "" && o.Prefix != "" {
|
||||
// Marker not common with prefix is not implemented. Send an empty response
|
||||
if !HasPrefix(o.Marker, o.Prefix) {
|
||||
return entries, io.EOF
|
||||
return entries, z.listPathShortcutEOF(ctx, o.Bucket)
|
||||
}
|
||||
}
|
||||
|
||||
// With max keys of zero we have reached eof, return right here.
|
||||
if o.Limit == 0 {
|
||||
return entries, io.EOF
|
||||
return entries, z.listPathShortcutEOF(ctx, o.Bucket)
|
||||
}
|
||||
|
||||
// For delimiter and prefix as '/' we do not list anything at all
|
||||
@@ -85,7 +85,7 @@ func (z *erasureServerPools) listPath(ctx context.Context, o *listPathOptions) (
|
||||
// as '/' we don't have any entries, since all the keys are
|
||||
// of form 'keyName/...'
|
||||
if strings.HasPrefix(o.Prefix, SlashSeparator) {
|
||||
return entries, io.EOF
|
||||
return entries, z.listPathShortcutEOF(ctx, o.Bucket)
|
||||
}
|
||||
|
||||
// If delimiter is slashSeparator we must return directories of
|
||||
@@ -254,6 +254,16 @@ func (z *erasureServerPools) listPath(ctx context.Context, o *listPathOptions) (
|
||||
return entries, nil
|
||||
}
|
||||
|
||||
// listPathShortcutEOF verifies bucket existence for shortcuts that return
|
||||
// without consulting the storage layer. Keep this check out of the normal
|
||||
// listing path since GetBucketInfo fans out to peers and disks.
|
||||
func (z *erasureServerPools) listPathShortcutEOF(ctx context.Context, bucket string) error {
|
||||
if _, err := z.GetBucketInfo(ctx, bucket, BucketOptions{}); err != nil {
|
||||
return err
|
||||
}
|
||||
return io.EOF
|
||||
}
|
||||
|
||||
// listMerged will list across all sets and return a merged results stream.
|
||||
// The result channel is closed when no more results are expected.
|
||||
func (z *erasureServerPools) listMerged(ctx context.Context, o listPathOptions, results chan<- metaCacheEntry) error {
|
||||
|
||||
@@ -191,7 +191,9 @@ func collectLocalDisksMetrics(disks map[string]struct{}) map[string]madmin.DiskM
|
||||
}
|
||||
}
|
||||
|
||||
//nolint:staticcheck // Linux implementations can fail; BSD stubs return a constant nil error.
|
||||
st, err := disk.GetDriveStats(d.Major, d.Minor)
|
||||
//nolint:staticcheck // Keep the shared cross-platform error handling.
|
||||
if err == nil {
|
||||
dm.IOStats = madmin.DiskIOStats{
|
||||
ReadIOs: st.ReadIOs,
|
||||
|
||||
@@ -22,6 +22,7 @@ import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strings"
|
||||
)
|
||||
|
||||
// Converts underlying storage error. Convenience function written to
|
||||
@@ -653,6 +654,41 @@ func (e InvalidPart) Error() string {
|
||||
e.PartNumber, e.ExpETag, e.GotETag)
|
||||
}
|
||||
|
||||
var (
|
||||
errCompleteMultipartChecksumMismatch = errors.New("complete multipart checksum mismatch")
|
||||
errCompleteMultipartChecksumTypeMismatch = errors.New("complete multipart checksum type mismatch")
|
||||
errMissingPartChecksum = errors.New("missing multipart part checksum")
|
||||
)
|
||||
|
||||
// completeMultipartChecksumMismatch reports an object checksum mismatch
|
||||
// detected while completing a multipart upload. It is distinct from
|
||||
// hash.ChecksumMismatch because AWS maps completion failures to BadDigest,
|
||||
// while streaming PutObject and UploadPart failures keep using
|
||||
// XAmzContentChecksumMismatch.
|
||||
func completeMultipartChecksumMismatch(algorithm string) error {
|
||||
description := "The checksum you specified did not match the calculated checksum."
|
||||
if algorithm != "" {
|
||||
description = fmt.Sprintf("The %s checksum you specified did not match the calculated checksum.", algorithm)
|
||||
}
|
||||
return fmt.Errorf("%w: %s", errCompleteMultipartChecksumMismatch, description)
|
||||
}
|
||||
|
||||
// completeMultipartChecksumTypeMismatch reports an explicit checksum type that
|
||||
// differs from the type selected when the multipart upload was initiated.
|
||||
func completeMultipartChecksumTypeMismatch(providedType, expectedType string) error {
|
||||
description := fmt.Sprintf("The checksum type %s does not match the multipart upload checksum type %s.",
|
||||
providedType, expectedType)
|
||||
return fmt.Errorf("%w: %s", errCompleteMultipartChecksumTypeMismatch, description)
|
||||
}
|
||||
|
||||
// missingPartChecksum reports a part whose checksum is absent from a
|
||||
// composite CompleteMultipartUpload request.
|
||||
func missingPartChecksum(algorithm string, partNumber int) error {
|
||||
description := fmt.Sprintf("The upload was created using a %s checksum. The complete request must include the checksum for each part. It was missing for part %d in the request.",
|
||||
strings.ToLower(algorithm), partNumber)
|
||||
return fmt.Errorf("%w: %s", errMissingPartChecksum, description)
|
||||
}
|
||||
|
||||
// PartTooSmall - error if part size is less than 5MB.
|
||||
type PartTooSmall struct {
|
||||
PartSize int64
|
||||
|
||||
@@ -84,7 +84,8 @@ type ObjectOptions struct {
|
||||
Expiration ExpirationOptions
|
||||
LifecycleAuditEvent lcAuditEvent
|
||||
|
||||
WantChecksum *hash.Checksum // x-amz-checksum-XXX checksum sent to PutObject/ CompleteMultipartUpload.
|
||||
WantChecksum *hash.Checksum // x-amz-checksum-XXX checksum sent to PutObject/ CompleteMultipartUpload.
|
||||
wantChecksumType string // explicit x-amz-checksum-type value on CompleteMultipartUpload.
|
||||
|
||||
WantServerSideChecksumType hash.ChecksumType // if set, we compute a server-side checksum of this type
|
||||
|
||||
|
||||
+56
-34
@@ -41,9 +41,6 @@ func getDefaultOpts(header http.Header, copySource bool, metadata map[string]str
|
||||
opts.ProxyHeaderSet = true
|
||||
opts.ProxyRequest = strings.Join(v, "") == "true"
|
||||
}
|
||||
if _, ok := header[xhttp.MinIOSourceReplicationRequest]; ok {
|
||||
opts.ReplicationRequest = true
|
||||
}
|
||||
opts.Speedtest = header.Get(globalObjectPerfUserMetadata) != ""
|
||||
|
||||
if copySource {
|
||||
@@ -116,12 +113,15 @@ func getOpts(ctx context.Context, r *http.Request, bucket, object string) (Objec
|
||||
}
|
||||
opts.PartNumber = partNumber
|
||||
opts.VersionID = vid
|
||||
opts.ReplicationRequest = isTrustedReplication(ctx)
|
||||
|
||||
delMarker, err := parseBoolHeader(bucket, object, r.Header, xhttp.MinIOSourceDeleteMarker)
|
||||
if err != nil {
|
||||
return opts, err
|
||||
if opts.ReplicationRequest {
|
||||
delMarker, err := parseBoolHeader(bucket, object, r.Header, xhttp.MinIOSourceDeleteMarker)
|
||||
if err != nil {
|
||||
return opts, err
|
||||
}
|
||||
opts.DeleteMarker = delMarker
|
||||
}
|
||||
opts.DeleteMarker = delMarker
|
||||
|
||||
replReadyCheck, err := parseBoolHeader(bucket, object, r.Header, xhttp.MinIOCheckDMReplicationReady)
|
||||
if err != nil {
|
||||
@@ -297,20 +297,22 @@ func delOpts(ctx context.Context, r *http.Request, bucket, object string) (opts
|
||||
opts.VersionID = nullVersionID
|
||||
}
|
||||
|
||||
delMarker, err := parseBoolHeader(bucket, object, r.Header, xhttp.MinIOSourceDeleteMarker)
|
||||
if err != nil {
|
||||
return opts, err
|
||||
}
|
||||
opts.DeleteMarker = delMarker
|
||||
|
||||
mtime := strings.TrimSpace(r.Header.Get(xhttp.MinIOSourceMTime))
|
||||
if mtime != "" {
|
||||
opts.MTime, err = time.Parse(time.RFC3339Nano, mtime)
|
||||
if isTrustedReplication(ctx) {
|
||||
delMarker, err := parseBoolHeader(bucket, object, r.Header, xhttp.MinIOSourceDeleteMarker)
|
||||
if err != nil {
|
||||
return opts, InvalidArgument{
|
||||
Bucket: bucket,
|
||||
Object: object,
|
||||
Err: fmt.Errorf("Unable to parse %s, failed with %w", xhttp.MinIOSourceMTime, err),
|
||||
return opts, err
|
||||
}
|
||||
opts.DeleteMarker = delMarker
|
||||
|
||||
mtime := strings.TrimSpace(r.Header.Get(xhttp.MinIOSourceMTime))
|
||||
if mtime != "" {
|
||||
opts.MTime, err = time.Parse(time.RFC3339Nano, mtime)
|
||||
if err != nil {
|
||||
return opts, InvalidArgument{
|
||||
Bucket: bucket,
|
||||
Object: object,
|
||||
Err: fmt.Errorf("Unable to parse %s, failed with %w", xhttp.MinIOSourceMTime, err),
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -319,10 +321,10 @@ func delOpts(ctx context.Context, r *http.Request, bucket, object string) (opts
|
||||
|
||||
// get ObjectOptions for PUT calls from encryption headers and metadata
|
||||
func putOptsFromReq(ctx context.Context, r *http.Request, bucket, object string, metadata map[string]string) (opts ObjectOptions, err error) {
|
||||
return putOpts(ctx, bucket, object, r.Form.Get(xhttp.VersionID), r.Header, metadata)
|
||||
return putOpts(ctx, bucket, object, r.Form.Get(xhttp.VersionID), r.Header, metadata, isTrustedReplication(ctx))
|
||||
}
|
||||
|
||||
func putOpts(ctx context.Context, bucket, object, vid string, hdrs http.Header, metadata map[string]string) (opts ObjectOptions, err error) {
|
||||
func putOpts(ctx context.Context, bucket, object, vid string, hdrs http.Header, metadata map[string]string, trustedReplication bool) (opts ObjectOptions, err error) {
|
||||
versioned := globalBucketVersioningSys.PrefixEnabled(bucket, object)
|
||||
versionSuspended := globalBucketVersioningSys.PrefixSuspended(bucket, object)
|
||||
|
||||
@@ -344,7 +346,7 @@ func putOpts(ctx context.Context, bucket, object, vid string, hdrs http.Header,
|
||||
}
|
||||
}
|
||||
}
|
||||
opts, err = putOptsFromHeaders(ctx, hdrs, metadata)
|
||||
opts, err = putOptsFromHeaders(ctx, hdrs, metadata, trustedReplication)
|
||||
if err != nil {
|
||||
return opts, InvalidArgument{
|
||||
Bucket: bucket,
|
||||
@@ -365,8 +367,15 @@ func putOpts(ctx context.Context, bucket, object, vid string, hdrs http.Header,
|
||||
return opts, nil
|
||||
}
|
||||
|
||||
func putOptsFromHeaders(ctx context.Context, hdr http.Header, metadata map[string]string) (opts ObjectOptions, err error) {
|
||||
mtimeStr := strings.TrimSpace(hdr.Get(xhttp.MinIOSourceMTime))
|
||||
func putOptsFromHeaders(ctx context.Context, hdr http.Header, metadata map[string]string, trustedReplication bool) (opts ObjectOptions, err error) {
|
||||
var mtimeStr, retaintimeStr, lholdtimeStr, tagtimeStr, etag string
|
||||
if trustedReplication {
|
||||
mtimeStr = strings.TrimSpace(hdr.Get(xhttp.MinIOSourceMTime))
|
||||
retaintimeStr = strings.TrimSpace(hdr.Get(xhttp.MinIOSourceObjectRetentionTimestamp))
|
||||
lholdtimeStr = strings.TrimSpace(hdr.Get(xhttp.MinIOSourceObjectLegalHoldTimestamp))
|
||||
tagtimeStr = strings.TrimSpace(hdr.Get(xhttp.MinIOSourceTaggingTimestamp))
|
||||
etag = strings.TrimSpace(hdr.Get(xhttp.MinIOSourceETag))
|
||||
}
|
||||
var mtime time.Time
|
||||
if mtimeStr != "" {
|
||||
mtime, err = time.Parse(time.RFC3339Nano, mtimeStr)
|
||||
@@ -374,7 +383,6 @@ func putOptsFromHeaders(ctx context.Context, hdr http.Header, metadata map[strin
|
||||
return opts, fmt.Errorf("Unable to parse %s, failed with %w", xhttp.MinIOSourceMTime, err)
|
||||
}
|
||||
}
|
||||
retaintimeStr := strings.TrimSpace(hdr.Get(xhttp.MinIOSourceObjectRetentionTimestamp))
|
||||
var retaintimestmp time.Time
|
||||
if retaintimeStr != "" {
|
||||
retaintimestmp, err = time.Parse(time.RFC3339, retaintimeStr)
|
||||
@@ -383,7 +391,6 @@ func putOptsFromHeaders(ctx context.Context, hdr http.Header, metadata map[strin
|
||||
}
|
||||
}
|
||||
|
||||
lholdtimeStr := strings.TrimSpace(hdr.Get(xhttp.MinIOSourceObjectLegalHoldTimestamp))
|
||||
var lholdtimestmp time.Time
|
||||
if lholdtimeStr != "" {
|
||||
lholdtimestmp, err = time.Parse(time.RFC3339, lholdtimeStr)
|
||||
@@ -391,7 +398,6 @@ func putOptsFromHeaders(ctx context.Context, hdr http.Header, metadata map[strin
|
||||
return opts, fmt.Errorf("Unable to parse %s, failed with %w", xhttp.MinIOSourceObjectLegalHoldTimestamp, err)
|
||||
}
|
||||
}
|
||||
tagtimeStr := strings.TrimSpace(hdr.Get(xhttp.MinIOSourceTaggingTimestamp))
|
||||
var taggingtimestmp time.Time
|
||||
if tagtimeStr != "" {
|
||||
taggingtimestmp, err = time.Parse(time.RFC3339, tagtimeStr)
|
||||
@@ -404,7 +410,6 @@ func putOptsFromHeaders(ctx context.Context, hdr http.Header, metadata map[strin
|
||||
metadata = make(map[string]string)
|
||||
}
|
||||
|
||||
etag := strings.TrimSpace(hdr.Get(xhttp.MinIOSourceETag))
|
||||
if crypto.S3KMS.IsRequested(hdr) {
|
||||
keyID, context, err := crypto.S3KMS.ParseHTTP(hdr)
|
||||
if err != nil {
|
||||
@@ -419,6 +424,7 @@ func putOptsFromHeaders(ctx context.Context, hdr http.Header, metadata map[strin
|
||||
UserDefined: metadata,
|
||||
MTime: mtime,
|
||||
PreserveETag: etag,
|
||||
ReplicationRequest: trustedReplication,
|
||||
}
|
||||
return op, nil
|
||||
}
|
||||
@@ -429,6 +435,7 @@ func putOptsFromHeaders(ctx context.Context, hdr http.Header, metadata map[strin
|
||||
}
|
||||
|
||||
opts.MTime = mtime
|
||||
opts.ReplicationRequest = trustedReplication
|
||||
opts.ReplicationSourceLegalholdTimestamp = lholdtimestmp
|
||||
opts.ReplicationSourceRetentionTimestamp = retaintimestmp
|
||||
opts.ReplicationSourceTaggingTimestamp = taggingtimestmp
|
||||
@@ -439,6 +446,9 @@ func putOptsFromHeaders(ctx context.Context, hdr http.Header, metadata map[strin
|
||||
|
||||
// get ObjectOptions for Copy calls with encryption headers provided on the target side and source side metadata
|
||||
func copyDstOpts(ctx context.Context, r *http.Request, bucket, object string, metadata map[string]string) (opts ObjectOptions, err error) {
|
||||
if _, err := hash.GetContentChecksum(r.Header); err != nil {
|
||||
return opts, err
|
||||
}
|
||||
return putOptsFromReq(ctx, r, bucket, object, metadata)
|
||||
}
|
||||
|
||||
@@ -451,12 +461,17 @@ func copySrcOpts(ctx context.Context, r *http.Request, bucket, object string) (O
|
||||
if err != nil {
|
||||
return opts, err
|
||||
}
|
||||
opts.ReplicationRequest = isReplicaTrusted(ctx)
|
||||
return opts, nil
|
||||
}
|
||||
|
||||
// get ObjectOptions for CompleteMultipart calls
|
||||
func completeMultipartOpts(ctx context.Context, r *http.Request, bucket, object string) (opts ObjectOptions, err error) {
|
||||
mtimeStr := strings.TrimSpace(r.Header.Get(xhttp.MinIOSourceMTime))
|
||||
trustedReplication := isTrustedReplication(ctx)
|
||||
var mtimeStr string
|
||||
if trustedReplication {
|
||||
mtimeStr = strings.TrimSpace(r.Header.Get(xhttp.MinIOSourceMTime))
|
||||
}
|
||||
var mtime time.Time
|
||||
if mtimeStr != "" {
|
||||
mtime, err = time.Parse(time.RFC3339Nano, mtimeStr)
|
||||
@@ -469,6 +484,13 @@ func completeMultipartOpts(ctx context.Context, r *http.Request, bucket, object
|
||||
}
|
||||
}
|
||||
|
||||
opts.wantChecksumType = r.Header.Get(xhttp.AmzChecksumType)
|
||||
switch opts.wantChecksumType {
|
||||
case "", xhttp.AmzChecksumTypeComposite, xhttp.AmzChecksumTypeFullObject:
|
||||
default:
|
||||
return opts, hash.ErrInvalidChecksum
|
||||
}
|
||||
|
||||
opts.WantChecksum, err = hash.GetContentChecksum(r.Header)
|
||||
if err != nil {
|
||||
return opts, err
|
||||
@@ -485,12 +507,12 @@ func completeMultipartOpts(ctx context.Context, r *http.Request, bucket, object
|
||||
}
|
||||
}
|
||||
}
|
||||
if _, ok := r.Header[xhttp.MinIOSourceReplicationRequest]; ok {
|
||||
if trustedReplication {
|
||||
opts.ReplicationRequest = true
|
||||
opts.UserDefined[ReservedMetadataPrefix+"Actual-Object-Size"] = r.Header.Get(xhttp.MinIOReplicationActualObjectSize)
|
||||
}
|
||||
if r.Header.Get(ReplicationSsecChecksumHeader) != "" {
|
||||
opts.UserDefined[ReplicationSsecChecksumHeader] = r.Header.Get(ReplicationSsecChecksumHeader)
|
||||
if r.Header.Get(ReplicationSsecChecksumHeader) != "" {
|
||||
opts.UserDefined[ReplicationSsecChecksumHeader] = r.Header.Get(ReplicationSsecChecksumHeader)
|
||||
}
|
||||
}
|
||||
return opts, nil
|
||||
}
|
||||
|
||||
+45
-8
@@ -1038,9 +1038,10 @@ type SealMD5CurrFn func([]byte) []byte
|
||||
// PutObjReader is a type that wraps sio.EncryptReader and
|
||||
// underlying hash.Reader in a struct
|
||||
type PutObjReader struct {
|
||||
*hash.Reader // actual data stream
|
||||
rawReader *hash.Reader // original data stream
|
||||
sealMD5Fn SealMD5CurrFn
|
||||
*hash.Reader // actual data stream
|
||||
rawReader *hash.Reader // original data stream used for ETag calculation
|
||||
checksumReader *hash.Reader // logical plaintext stream used for S3 checksum calculation
|
||||
sealMD5Fn SealMD5CurrFn
|
||||
}
|
||||
|
||||
// Size returns the absolute number of bytes the Reader
|
||||
@@ -1093,15 +1094,51 @@ func (p *PutObjReader) WithEncryption(encReader *hash.Reader, objEncKey *crypto.
|
||||
// NewPutObjReader returns a new PutObjReader. It uses given hash.Reader's
|
||||
// MD5Current method to construct md5sum when requested downstream.
|
||||
func NewPutObjReader(rawReader *hash.Reader) *PutObjReader {
|
||||
return &PutObjReader{Reader: rawReader, rawReader: rawReader}
|
||||
return &PutObjReader{Reader: rawReader, rawReader: rawReader, checksumReader: rawReader}
|
||||
}
|
||||
|
||||
// setChecksumReader sets the logical plaintext reader used for S3 checksums.
|
||||
// It can differ from rawReader when the storage stream is compressed.
|
||||
func (p *PutObjReader) setChecksumReader(r *hash.Reader) {
|
||||
if r != nil {
|
||||
p.checksumReader = r
|
||||
}
|
||||
}
|
||||
|
||||
// contentChecksumType returns the effective client-provided or server-computed
|
||||
// checksum type for the logical plaintext stream.
|
||||
func (p *PutObjReader) contentChecksumType() hash.ChecksumType {
|
||||
if p.checksumReader == nil {
|
||||
return hash.ChecksumNone
|
||||
}
|
||||
if t := p.checksumReader.ContentCRCType(); t.IsSet() {
|
||||
return t
|
||||
}
|
||||
return p.checksumReader.ServerSideChecksumType
|
||||
}
|
||||
|
||||
// contentChecksum returns the effective checksum for part metadata. A
|
||||
// client-provided checksum takes precedence; server computation is only a
|
||||
// fallback when the client omitted one.
|
||||
func (p *PutObjReader) contentChecksum() map[string]string {
|
||||
if p.checksumReader == nil {
|
||||
return nil
|
||||
}
|
||||
if checksum := p.checksumReader.ContentCRC(); checksum != nil {
|
||||
return checksum
|
||||
}
|
||||
if checksum := p.checksumReader.ServerSideChecksumResult; checksum != nil && checksum.Valid() {
|
||||
return map[string]string{checksum.Type.String(): checksum.Encoded}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// RawServerSideChecksumResult returns the ServerSideChecksumResult from the
|
||||
// underlying rawReader, since the PutObjReader might be encrypted data and
|
||||
// thus any checksum from that would be incorrect.
|
||||
// logical plaintext checksum reader, since the PutObjReader might contain
|
||||
// compressed or encrypted data and thus any checksum from that would be incorrect.
|
||||
func (p *PutObjReader) RawServerSideChecksumResult() *hash.Checksum {
|
||||
if p.rawReader != nil {
|
||||
return p.rawReader.ServerSideChecksumResult
|
||||
if p.checksumReader != nil {
|
||||
return p.checksumReader.ServerSideChecksumResult
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -0,0 +1,139 @@
|
||||
// Copyright (c) 2015-2025 MinIO, Inc.
|
||||
// Copyright (c) 2025-2026 PGSTY
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/minio/internal/auth"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
"github.com/minio/pkg/v3/policy"
|
||||
)
|
||||
|
||||
// GetObjectAttributes lets a replication peer read SSE-C attributes without
|
||||
// presenting the customer key. The X-Minio-Source-Replication-Request header
|
||||
// that marks such a request is client controlled, so the carve-out has to be
|
||||
// gated on the caller actually holding s3:ReplicateObject. Root credentials
|
||||
// hold every action, so a root-only test cannot tell the gate apart from an
|
||||
// ungated header check; these cases drive it with least-privilege users.
|
||||
func TestAPIGetObjectAttributesSSECReplicationAuthz(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPIGetObjectAttributesSSECReplicationAuthz,
|
||||
})
|
||||
}
|
||||
|
||||
func testAPIGetObjectAttributesSSECReplicationAuthz(_ ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
previousTLS := globalIsTLS
|
||||
globalIsTLS = true
|
||||
defer func() { globalIsTLS = previousTLS }()
|
||||
|
||||
key := bytes.Repeat([]byte{0x11}, 32)
|
||||
keyMD5 := md5.Sum(key)
|
||||
sseHeaders := map[string]string{
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(key),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(keyMD5[:]),
|
||||
}
|
||||
replicationHeader := map[string]string{xhttp.MinIOSourceReplicationRequest: "true"}
|
||||
|
||||
object := "attributes/ssec-replication-authz"
|
||||
putCopyChecksumSource(t, apiRouter, credentials, bucketName, object,
|
||||
bytes.Repeat([]byte("attributes-authz-"), 512), sseHeaders)
|
||||
|
||||
// s3:GetObjectAttributes and s3:GetObject reach the handler; only the
|
||||
// second policy adds the replication action the carve-out requires.
|
||||
readerOnly := newObjectAttributesAuthzUser(t, instanceType, bucketName,
|
||||
`"s3:GetObject","s3:GetObjectAttributes"`)
|
||||
replicator := newObjectAttributesAuthzUser(t, instanceType, bucketName,
|
||||
`"s3:GetObject","s3:GetObjectAttributes","s3:ReplicateObject"`)
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
creds auth.Credentials
|
||||
headers map[string]string
|
||||
want int
|
||||
}{
|
||||
// The header alone must not stand in for s3:ReplicateObject.
|
||||
{name: "reader/replication-header-only", creds: readerOnly, headers: replicationHeader, want: http.StatusBadRequest},
|
||||
// A caller that may replicate this object keeps the carve-out.
|
||||
{name: "replicator/replication-header-only", creds: replicator, headers: replicationHeader, want: http.StatusOK},
|
||||
// Root holds s3:ReplicateObject, so its carve-out is unchanged.
|
||||
{name: "root/replication-header-only", creds: credentials, headers: replicationHeader, want: http.StatusOK},
|
||||
// The ordinary key-bearing path is unaffected for every caller.
|
||||
{name: "reader/correct-key", creds: readerOnly, headers: sseHeaders, want: http.StatusOK},
|
||||
{name: "reader/no-key", creds: readerOnly, want: http.StatusBadRequest},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
rec := objectAttributesSSECRequest(t, apiRouter, test.creds, bucketName, object, test.headers)
|
||||
if rec.Code != test.want {
|
||||
t.Fatalf("%s: status %d, want %d: %s", instanceType, rec.Code, test.want, rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// newObjectAttributesAuthzUser installs a least-privilege user whose policy
|
||||
// grants exactly the listed actions on bucketName's objects.
|
||||
func newObjectAttributesAuthzUser(t *testing.T, instanceType, bucketName, actions string) auth.Credentials {
|
||||
t.Helper()
|
||||
ctx := t.Context()
|
||||
|
||||
accessKey, secretKey, err := auth.GenerateCredentials()
|
||||
if err != nil {
|
||||
t.Fatalf("%s: generate credentials: %v", instanceType, err)
|
||||
}
|
||||
creds := auth.Credentials{AccessKey: accessKey, SecretKey: secretKey}
|
||||
if _, err = globalIAMSys.CreateUser(ctx, creds.AccessKey, madmin.AddOrUpdateUserReq{
|
||||
SecretKey: creds.SecretKey,
|
||||
Status: madmin.AccountEnabled,
|
||||
}); err != nil {
|
||||
t.Fatalf("%s: create attributes user: %v", instanceType, err)
|
||||
}
|
||||
|
||||
policyJSON := `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [{
|
||||
"Effect": "Allow",
|
||||
"Action": [` + actions + `],
|
||||
"Resource": ["arn:aws:s3:::` + bucketName + `/*"]
|
||||
}]
|
||||
}`
|
||||
parsed, err := policy.ParseConfig(strings.NewReader(policyJSON))
|
||||
if err != nil {
|
||||
t.Fatalf("%s: parse attributes policy: %v", instanceType, err)
|
||||
}
|
||||
policyName := "attributes-authz-" + mustGetUUID()
|
||||
if _, err = globalIAMSys.SetPolicy(ctx, policyName, *parsed); err != nil {
|
||||
t.Fatalf("%s: install attributes policy: %v", instanceType, err)
|
||||
}
|
||||
if _, err = globalIAMSys.PolicyDBSet(ctx, creds.AccessKey, policyName, regUser, false); err != nil {
|
||||
t.Fatalf("%s: attach attributes policy: %v", instanceType, err)
|
||||
}
|
||||
return creds
|
||||
}
|
||||
@@ -0,0 +1,104 @@
|
||||
// Copyright (c) 2015-2026 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/minio/minio/internal/auth"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
)
|
||||
|
||||
func TestAPIGetObjectAttributesAuthenticatesSSECKey(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPIGetObjectAttributesAuthenticatesSSECKey,
|
||||
})
|
||||
}
|
||||
|
||||
func testAPIGetObjectAttributesAuthenticatesSSECKey(_ ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
previousTLS := globalIsTLS
|
||||
globalIsTLS = true
|
||||
defer func() { globalIsTLS = previousTLS }()
|
||||
|
||||
key := bytes.Repeat([]byte{0x11}, 32)
|
||||
keyMD5 := md5.Sum(key)
|
||||
wrongKey := bytes.Repeat([]byte{0x22}, 32)
|
||||
wrongMD5 := md5.Sum(wrongKey)
|
||||
correctHeaders := map[string]string{
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(key),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(keyMD5[:]),
|
||||
}
|
||||
wrongHeaders := map[string]string{
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(wrongKey),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(wrongMD5[:]),
|
||||
}
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
data []byte
|
||||
}{
|
||||
{name: "zero", data: nil},
|
||||
{name: "nonzero", data: []byte("secret")},
|
||||
} {
|
||||
object := "attributes/ssec-" + test.name
|
||||
putCopyChecksumSource(t, apiRouter, credentials, bucketName, object, test.data, correctHeaders)
|
||||
if rec := objectAttributesSSECRequest(t, apiRouter, credentials, bucketName, object, correctHeaders); rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s/%s: correct key returned %d: %s", instanceType, test.name, rec.Code, rec.Body.String())
|
||||
}
|
||||
if rec := objectAttributesSSECRequest(t, apiRouter, credentials, bucketName, object, wrongHeaders); rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("%s/%s: wrong key returned %d, want %d: %s", instanceType, test.name, rec.Code, http.StatusForbidden, rec.Body.String())
|
||||
}
|
||||
if rec := objectAttributesSSECRequest(t, apiRouter, credentials, bucketName, object, nil); rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("%s/%s: missing key returned %d, want %d: %s", instanceType, test.name, rec.Code, http.StatusBadRequest, rec.Body.String())
|
||||
}
|
||||
if rec := objectAttributesSSECRequest(t, apiRouter, credentials, bucketName, object, map[string]string{
|
||||
xhttp.MinIOSourceReplicationRequest: "true",
|
||||
}); rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s/%s: replication request returned %d: %s", instanceType, test.name, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func objectAttributesSSECRequest(t *testing.T, apiRouter http.Handler, credentials auth.Credentials,
|
||||
bucket, object string, encryptionHeaders map[string]string,
|
||||
) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
headers := map[string]string{xhttp.AmzObjectAttributes: "ObjectSize,ETag,ObjectParts,Checksum"}
|
||||
for key, value := range encryptionHeaders {
|
||||
headers[key] = value
|
||||
}
|
||||
req, err := newTestSignedRequestV4(http.MethodGet, getGetObjectURL("", bucket, object)+"?attributes",
|
||||
0, nil, credentials.AccessKey, credentials.SecretKey, headers)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
// Copyright (c) 2015-2026 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/xml"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/minio/minio/internal/auth"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
)
|
||||
|
||||
func TestAPIRejectsUnsupportedChecksumHeaders(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPIRejectsUnsupportedChecksumHeaders,
|
||||
endpoints: []string{"CopyObject", "NewMultipart", "PutObject", "PutObjectPart"},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPIRejectsUnsupportedChecksumHeaders(obj ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
data := []byte("unsupported-checksum")
|
||||
unsupportedValue := base64.StdEncoding.EncodeToString(make([]byte, 64))
|
||||
|
||||
put := func(object string, headers map[string]string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req, err := newTestSignedRequestV4(http.MethodPut, getPutObjectURL("", bucketName, object),
|
||||
int64(len(data)), bytes.NewReader(data), credentials.AccessKey, credentials.SecretKey, headers)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
assertRejected := func(name string, rec *httptest.ResponseRecorder) {
|
||||
t.Helper()
|
||||
if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "<Code>InvalidArgument</Code>") {
|
||||
t.Fatalf("%s: %s returned %d, want InvalidArgument: %s", instanceType, name, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
for _, algorithm := range []string{"md5", "sha512", "xxhash64", "xxhash3", "xxhash128", "future"} {
|
||||
object := "checksums/unsupported-" + algorithm
|
||||
assertRejected(algorithm, put(object, map[string]string{
|
||||
"x-amz-sdk-checksum-algorithm": "SHA512",
|
||||
"x-amz-checksum-" + algorithm: unsupportedValue,
|
||||
}))
|
||||
if _, err := obj.GetObjectInfo(t.Context(), bucketName, object, ObjectOptions{}); !isErrObjectNotFound(err) {
|
||||
t.Fatalf("%s: rejected %s checksum stored an object: %v", instanceType, algorithm, err)
|
||||
}
|
||||
}
|
||||
|
||||
assertRejected("unsupported trailer", put("checksums/unsupported-trailer", map[string]string{
|
||||
xhttp.AmzTrailer: "x-amz-checksum-sha512",
|
||||
}))
|
||||
|
||||
newMultipart := func(name string, headers map[string]string) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req, err := newTestSignedRequestV4(http.MethodPost, getNewMultipartURL("", bucketName, name),
|
||||
0, nil, credentials.AccessKey, credentials.SecretKey, headers)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
assertRejected("NewMultipartUpload value header", newMultipart("checksums/mp-value", map[string]string{
|
||||
"x-amz-checksum-sha512": unsupportedValue,
|
||||
}))
|
||||
assertRejected("NewMultipartUpload trailer", newMultipart("checksums/mp-trailer", map[string]string{
|
||||
xhttp.AmzTrailer: "x-amz-checksum-sha512",
|
||||
}))
|
||||
|
||||
rec := newMultipart("checksums/mp-part", nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: NewMultipartUpload setup returned %d: %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
var initiated InitiateMultipartUploadResponse
|
||||
if err := xml.Unmarshal(rec.Body.Bytes(), &initiated); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req, err := newTestSignedRequestV4(http.MethodPut,
|
||||
getPutObjectPartURL("", bucketName, "checksums/mp-part", initiated.UploadID, "1"),
|
||||
int64(len(data)), bytes.NewReader(data), credentials.AccessKey, credentials.SecretKey,
|
||||
map[string]string{"x-amz-checksum-sha512": unsupportedValue})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec = httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
assertRejected("UploadPart", rec)
|
||||
parts, err := obj.ListObjectParts(t.Context(), bucketName, "checksums/mp-part", initiated.UploadID, 0, 1000, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(parts.Parts) != 0 {
|
||||
t.Fatalf("%s: rejected UploadPart stored %d parts", instanceType, len(parts.Parts))
|
||||
}
|
||||
if err := obj.AbortMultipartUpload(t.Context(), bucketName, "checksums/mp-part", initiated.UploadID, ObjectOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
source := "checksums/source"
|
||||
putCopyChecksumSource(t, apiRouter, credentials, bucketName, source, data, nil)
|
||||
rec = copyChecksumRequest(t, apiRouter, credentials, bucketName, source, "checksums/copy", map[string]string{
|
||||
"x-amz-checksum-sha512": unsupportedValue,
|
||||
})
|
||||
assertRejected("CopyObject", rec)
|
||||
if _, err := obj.GetObjectInfo(t.Context(), bucketName, "checksums/copy", ObjectOptions{}); !isErrObjectNotFound(err) {
|
||||
t.Fatalf("%s: rejected CopyObject stored a destination: %v", instanceType, err)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,594 @@
|
||||
// Copyright (c) 2015-2026 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/minio/minio/internal/auth"
|
||||
"github.com/minio/minio/internal/hash"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
"github.com/minio/minio/internal/kms"
|
||||
)
|
||||
|
||||
func setCopyChecksumCompression(allowEncrypted bool) func() {
|
||||
globalCompressConfigMu.Lock()
|
||||
previous := globalCompressConfig
|
||||
globalCompressConfig.Enabled = true
|
||||
globalCompressConfig.Extensions = []string{".txt"}
|
||||
globalCompressConfig.MimeTypes = nil
|
||||
globalCompressConfig.AllowEncrypted = allowEncrypted
|
||||
globalCompressConfigMu.Unlock()
|
||||
|
||||
return func() {
|
||||
globalCompressConfigMu.Lock()
|
||||
globalCompressConfig = previous
|
||||
globalCompressConfigMu.Unlock()
|
||||
}
|
||||
}
|
||||
|
||||
func copyChecksumRequest(t *testing.T, apiRouter http.Handler, credentials auth.Credentials,
|
||||
bucket, source, destination string, headers map[string]string,
|
||||
) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req, err := newTestSignedRequestV4(http.MethodPut, getCopyObjectURL("", bucket, destination),
|
||||
0, nil, credentials.AccessKey, credentials.SecretKey, headers)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to build CopyObject request: %v", err)
|
||||
}
|
||||
req.Header.Set(xhttp.AmzCopySource, SlashSeparator+pathJoin(bucket, source))
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func putCopyChecksumSource(t *testing.T, apiRouter http.Handler, credentials auth.Credentials,
|
||||
bucket, object string, data []byte, headers map[string]string,
|
||||
) {
|
||||
t.Helper()
|
||||
req, err := newTestSignedRequestV4(http.MethodPut, getPutObjectURL("", bucket, object),
|
||||
int64(len(data)), bytes.NewReader(data), credentials.AccessKey, credentials.SecretKey, headers)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to build PutObject request: %v", err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("PutObject(%s) failed: %d %s", object, rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func readCopyChecksumObject(t *testing.T, obj ObjectLayer, bucket, object string, opts ObjectOptions) []byte {
|
||||
t.Helper()
|
||||
gr, err := obj.GetObjectNInfo(t.Context(), bucket, object, nil, nil, opts)
|
||||
if err != nil {
|
||||
t.Fatalf("GetObjectNInfo(%s) failed: %v", object, err)
|
||||
}
|
||||
defer gr.Close()
|
||||
data, err := io.ReadAll(gr)
|
||||
if err != nil {
|
||||
t.Fatalf("reading %s failed: %v", object, err)
|
||||
}
|
||||
return data
|
||||
}
|
||||
|
||||
func assertCopyChecksum(t *testing.T, obj ObjectLayer, bucket, object string, typ hash.ChecksumType,
|
||||
data []byte, compressed bool, decryptHeaders http.Header,
|
||||
) ObjectInfo {
|
||||
t.Helper()
|
||||
oi, err := obj.GetObjectInfo(t.Context(), bucket, object, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("GetObjectInfo(%s) failed: %v", object, err)
|
||||
}
|
||||
if oi.IsCompressed() != compressed {
|
||||
t.Fatalf("%s compressed=%v, want %v", object, oi.IsCompressed(), compressed)
|
||||
}
|
||||
checksums, _ := oi.decryptChecksums(0, decryptHeaders)
|
||||
if got, want := checksums[typ.String()], mustChecksum(t, typ, data); got != want {
|
||||
t.Fatalf("%s stored %s checksum %q, want logical object checksum %q (all: %v)",
|
||||
object, typ.String(), got, want, checksums)
|
||||
}
|
||||
if got := checksums[xhttp.AmzChecksumType]; got != xhttp.AmzChecksumTypeFullObject {
|
||||
t.Fatalf("%s checksum type %q, want %q", object, got, xhttp.AmzChecksumTypeFullObject)
|
||||
}
|
||||
return oi
|
||||
}
|
||||
|
||||
func assertCopyChecksumResponse(t *testing.T, rec *httptest.ResponseRecorder, typ hash.ChecksumType, data []byte) {
|
||||
t.Helper()
|
||||
var response CopyObjectResponse
|
||||
if err := xml.Unmarshal(rec.Body.Bytes(), &response); err != nil {
|
||||
t.Fatalf("unable to decode CopyObjectResult: %v", err)
|
||||
}
|
||||
var got string
|
||||
switch typ.Base() {
|
||||
case hash.ChecksumCRC32:
|
||||
got = response.ChecksumCRC32
|
||||
case hash.ChecksumCRC32C:
|
||||
got = response.ChecksumCRC32C
|
||||
case hash.ChecksumSHA1:
|
||||
got = response.ChecksumSHA1
|
||||
case hash.ChecksumSHA256:
|
||||
got = response.ChecksumSHA256
|
||||
case hash.ChecksumCRC64NVME:
|
||||
got = response.ChecksumCRC64NVME
|
||||
}
|
||||
if want := mustChecksum(t, typ, data); got != want {
|
||||
t.Fatalf("CopyObjectResult %s checksum %q, want %q: %s", typ.String(), got, want, rec.Body.String())
|
||||
}
|
||||
if response.ChecksumType != xhttp.AmzChecksumTypeFullObject {
|
||||
t.Fatalf("CopyObjectResult checksum type %q, want %q", response.ChecksumType, xhttp.AmzChecksumTypeFullObject)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPICopyObjectServerSideChecksum verifies that server-computed checksums
|
||||
// cover the logical object, never the compressed storage stream.
|
||||
func TestAPICopyObjectServerSideChecksum(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
for _, versioned := range []bool{false, true} {
|
||||
name := "unversioned"
|
||||
if versioned {
|
||||
name = "versioned"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPICopyObjectServerSideChecksum,
|
||||
endpoints: []string{"CopyObject", "PutObject", "HeadObject", "GetObject"},
|
||||
makeBucketOptions: MakeBucketOptions{VersioningEnabled: versioned},
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func testAPICopyObjectServerSideChecksum(obj ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
restoreCompression := setCopyChecksumCompression(true)
|
||||
defer restoreCompression()
|
||||
|
||||
data := bytes.Repeat([]byte("copy-object-checksum-plaintext-"), 64*1024)
|
||||
source := "copy-checksum/source.bin"
|
||||
if _, err := obj.PutObject(t.Context(), bucketName, source,
|
||||
mustGetPutObjReader(t, bytes.NewReader(data), int64(len(data)), "", ""), ObjectOptions{}); err != nil {
|
||||
t.Fatalf("%s: source PutObject failed: %v", instanceType, err)
|
||||
}
|
||||
|
||||
compressedReader, _ := newS2CompressReader(bytes.NewReader(data), int64(len(data)), false)
|
||||
compressed, err := io.ReadAll(compressedReader)
|
||||
if closeErr := compressedReader.Close(); err == nil {
|
||||
err = closeErr
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("%s: independently compressing test data failed: %v", instanceType, err)
|
||||
}
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
typ hash.ChecksumType
|
||||
explicit bool
|
||||
extension string
|
||||
compressed bool
|
||||
}{
|
||||
{name: "compressed/CRC32", typ: hash.ChecksumCRC32, explicit: true, extension: ".txt", compressed: true},
|
||||
{name: "compressed/CRC32C", typ: hash.ChecksumCRC32C, explicit: true, extension: ".txt", compressed: true},
|
||||
{name: "compressed/SHA1", typ: hash.ChecksumSHA1, explicit: true, extension: ".txt", compressed: true},
|
||||
{name: "compressed/SHA256", typ: hash.ChecksumSHA256, explicit: true, extension: ".txt", compressed: true},
|
||||
{name: "compressed/CRC64NVME", typ: hash.ChecksumCRC64NVME, explicit: true, extension: ".txt", compressed: true},
|
||||
{name: "compressed/default", typ: hash.ChecksumCRC64NVME, extension: ".txt", compressed: true},
|
||||
{name: "plain/CRC32", typ: hash.ChecksumCRC32, explicit: true, extension: ".bin"},
|
||||
{name: "plain/default", typ: hash.ChecksumCRC64NVME, extension: ".bin"},
|
||||
}
|
||||
|
||||
for i, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
headers := map[string]string(nil)
|
||||
if tc.explicit {
|
||||
headers = map[string]string{xhttp.AmzChecksumAlgo: tc.typ.String()}
|
||||
}
|
||||
destination := "copy-checksum/destination-" + tc.typ.String() + "-" + string(rune('a'+i)) + tc.extension
|
||||
rec := copyChecksumRequest(t, apiRouter, credentials, bucketName, source, destination, headers)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: CopyObject failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
assertCopyChecksumResponse(t, rec, tc.typ, data)
|
||||
|
||||
info := assertCopyChecksum(t, obj, bucketName, destination, tc.typ, data, tc.compressed, nil)
|
||||
md5sum := md5.Sum(data)
|
||||
if got, want := info.ETag, hex.EncodeToString(md5sum[:]); got != want {
|
||||
t.Fatalf("%s: ETag %q, want logical object MD5 %q", instanceType, got, want)
|
||||
}
|
||||
if tc.compressed {
|
||||
logical := mustChecksum(t, tc.typ, data)
|
||||
if transformed := mustChecksum(t, tc.typ, compressed); logical == transformed {
|
||||
t.Fatalf("%s: test payload does not distinguish logical and compressed checksum domains", instanceType)
|
||||
}
|
||||
}
|
||||
if got := readCopyChecksumObject(t, obj, bucketName, destination, ObjectOptions{}); !bytes.Equal(got, data) {
|
||||
t.Fatalf("%s: round-trip body differs for %s", instanceType, tc.name)
|
||||
}
|
||||
|
||||
if tc.name == "compressed/CRC32" {
|
||||
for _, method := range []string{http.MethodHead, http.MethodGet} {
|
||||
url := getHeadObjectURL("", bucketName, destination)
|
||||
if method == http.MethodGet {
|
||||
url = getGetObjectURL("", bucketName, destination)
|
||||
}
|
||||
req, err := newTestSignedRequestV4(method, url, 0, nil,
|
||||
credentials.AccessKey, credentials.SecretKey,
|
||||
map[string]string{xhttp.AmzChecksumMode: "ENABLED"})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to build %s request: %v", method, err)
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(response, req)
|
||||
if response.Code != http.StatusOK {
|
||||
t.Fatalf("%s returned %d: %s", method, response.Code, response.Body.String())
|
||||
}
|
||||
if got, want := response.Header().Get(tc.typ.Key()), mustChecksum(t, tc.typ, data); got != want {
|
||||
t.Fatalf("%s returned checksum %q, want %q", method, got, want)
|
||||
}
|
||||
if method == http.MethodGet && !bytes.Equal(response.Body.Bytes(), data) {
|
||||
t.Fatalf("GET response body differs")
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPICopyObjectServerSideChecksumEncryption(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPICopyObjectServerSideChecksumEncryption,
|
||||
endpoints: []string{"CopyObject", "PutObject", "GetObject"},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPICopyObjectServerSideChecksumEncryption(obj ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
restoreCompression := setCopyChecksumCompression(true)
|
||||
defer restoreCompression()
|
||||
|
||||
data := bytes.Repeat([]byte("encrypted-copy-checksum-plaintext-"), 48*1024)
|
||||
source := "copy-checksum/encrypted-source.bin"
|
||||
if _, err := obj.PutObject(t.Context(), bucketName, source,
|
||||
mustGetPutObjReader(t, bytes.NewReader(data), int64(len(data)), "", ""), ObjectOptions{}); err != nil {
|
||||
t.Fatalf("%s: source PutObject failed: %v", instanceType, err)
|
||||
}
|
||||
|
||||
t.Run("SSE-S3", func(t *testing.T) {
|
||||
secretKey, err := kms.ParseSecretKey("my-minio-key:5lF+0pJM0OWwlQrvK2S/I7W9mO4a6rJJI7wzj7v09cw=")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
previousKMS := GlobalKMS
|
||||
GlobalKMS = secretKey
|
||||
defer func() { GlobalKMS = previousKMS }()
|
||||
|
||||
for _, variant := range []struct {
|
||||
name string
|
||||
extension string
|
||||
compressed bool
|
||||
}{
|
||||
{name: "encrypted-only", extension: ".bin"},
|
||||
{name: "compressed-encrypted", extension: ".txt", compressed: true},
|
||||
} {
|
||||
t.Run(variant.name, func(t *testing.T) {
|
||||
destination := "copy-checksum/sse-s3-" + variant.name + variant.extension
|
||||
rec := copyChecksumRequest(t, apiRouter, credentials, bucketName, source, destination, map[string]string{
|
||||
xhttp.AmzChecksumAlgo: hash.ChecksumCRC32.String(),
|
||||
xhttp.AmzServerSideEncryption: xhttp.AmzEncryptionAES,
|
||||
})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: SSE-S3 CopyObject failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
assertCopyChecksumResponse(t, rec, hash.ChecksumCRC32, data)
|
||||
assertCopyChecksum(t, obj, bucketName, destination, hash.ChecksumCRC32, data, variant.compressed, nil)
|
||||
if got := readCopyChecksumObject(t, obj, bucketName, destination, ObjectOptions{}); !bytes.Equal(got, data) {
|
||||
t.Fatalf("%s: SSE-S3 round-trip body differs", instanceType)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
encryptedSource := "copy-checksum/sse-s3-source.bin"
|
||||
putCopyChecksumSource(t, apiRouter, credentials, bucketName, encryptedSource, data,
|
||||
map[string]string{xhttp.AmzServerSideEncryption: xhttp.AmzEncryptionAES})
|
||||
destination := "copy-checksum/sse-s3-source-copy.txt"
|
||||
rec := copyChecksumRequest(t, apiRouter, credentials, bucketName, encryptedSource, destination,
|
||||
map[string]string{xhttp.AmzChecksumAlgo: hash.ChecksumCRC32.String()})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: SSE-S3 source CopyObject failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
assertCopyChecksumResponse(t, rec, hash.ChecksumCRC32, data)
|
||||
assertCopyChecksum(t, obj, bucketName, destination, hash.ChecksumCRC32, data, true, nil)
|
||||
if got := readCopyChecksumObject(t, obj, bucketName, destination, ObjectOptions{}); !bytes.Equal(got, data) {
|
||||
t.Fatalf("%s: SSE-S3 source round-trip body differs", instanceType)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("SSE-C", func(t *testing.T) {
|
||||
previousTLS := globalIsTLS
|
||||
globalIsTLS = true
|
||||
defer func() { globalIsTLS = previousTLS }()
|
||||
|
||||
key := bytes.Repeat([]byte{0x2a}, 32)
|
||||
keyMD5 := md5.Sum(key)
|
||||
headers := map[string]string{
|
||||
xhttp.AmzChecksumAlgo: hash.ChecksumCRC32.String(),
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(key),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(keyMD5[:]),
|
||||
}
|
||||
decryptHeaders := http.Header{}
|
||||
for key, value := range headers {
|
||||
decryptHeaders.Set(key, value)
|
||||
}
|
||||
|
||||
getHeaders := make(map[string]string, len(headers))
|
||||
for key, value := range headers {
|
||||
if key != xhttp.AmzChecksumAlgo {
|
||||
getHeaders[key] = value
|
||||
}
|
||||
}
|
||||
for _, variant := range []struct {
|
||||
name string
|
||||
extension string
|
||||
compressed bool
|
||||
}{
|
||||
{name: "encrypted-only", extension: ".bin"},
|
||||
{name: "compressed-encrypted", extension: ".txt", compressed: true},
|
||||
} {
|
||||
t.Run(variant.name, func(t *testing.T) {
|
||||
destination := "copy-checksum/sse-c-" + variant.name + variant.extension
|
||||
rec := copyChecksumRequest(t, apiRouter, credentials, bucketName, source, destination, headers)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: SSE-C CopyObject failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
assertCopyChecksumResponse(t, rec, hash.ChecksumCRC32, data)
|
||||
assertCopyChecksum(t, obj, bucketName, destination, hash.ChecksumCRC32, data, variant.compressed, decryptHeaders)
|
||||
|
||||
req, err := newTestSignedRequestV4(http.MethodGet, getGetObjectURL("", bucketName, destination),
|
||||
0, nil, credentials.AccessKey, credentials.SecretKey, getHeaders)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to build SSE-C GetObject request: %v", err)
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(response, req)
|
||||
if response.Code != http.StatusOK || !bytes.Equal(response.Body.Bytes(), data) {
|
||||
t.Fatalf("%s: SSE-C GetObject returned %d with %d bytes, want 200 with %d bytes",
|
||||
instanceType, response.Code, response.Body.Len(), len(data))
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
oldKey := bytes.Repeat([]byte{0x31}, 32)
|
||||
oldKeyMD5 := md5.Sum(oldKey)
|
||||
newKey := bytes.Repeat([]byte{0x42}, 32)
|
||||
newKeyMD5 := md5.Sum(newKey)
|
||||
encryptedSource := "copy-checksum/sse-c-different-key-source.bin"
|
||||
putCopyChecksumSource(t, apiRouter, credentials, bucketName, encryptedSource, data, map[string]string{
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(oldKey),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(oldKeyMD5[:]),
|
||||
})
|
||||
|
||||
destination := "copy-checksum/sse-c-different-key-destination.bin"
|
||||
rec := copyChecksumRequest(t, apiRouter, credentials, bucketName, encryptedSource, destination, map[string]string{
|
||||
xhttp.AmzChecksumAlgo: hash.ChecksumCRC32.String(),
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(newKey),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(newKeyMD5[:]),
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerKey: base64.StdEncoding.EncodeToString(oldKey),
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerKeyMD5: base64.StdEncoding.EncodeToString(oldKeyMD5[:]),
|
||||
})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: different-key SSE-C CopyObject failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
assertCopyChecksumResponse(t, rec, hash.ChecksumCRC32, data)
|
||||
if got, want := rec.Header().Get(hash.ChecksumCRC32.Key()), mustChecksum(t, hash.ChecksumCRC32, data); got != want {
|
||||
t.Fatalf("%s: different-key SSE-C response header checksum %q, want %q", instanceType, got, want)
|
||||
}
|
||||
if got := rec.Header().Get(xhttp.AmzChecksumType); got != xhttp.AmzChecksumTypeFullObject {
|
||||
t.Fatalf("%s: different-key SSE-C response checksum type %q, want %q", instanceType, got, xhttp.AmzChecksumTypeFullObject)
|
||||
}
|
||||
newKeyHeaders := http.Header{
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: []string{xhttp.AmzEncryptionAES},
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: []string{base64.StdEncoding.EncodeToString(newKey)},
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: []string{base64.StdEncoding.EncodeToString(newKeyMD5[:])},
|
||||
}
|
||||
assertCopyChecksum(t, obj, bucketName, destination, hash.ChecksumCRC32, data, false, newKeyHeaders)
|
||||
})
|
||||
}
|
||||
|
||||
func TestAPICopyObjectServerSideChecksumSourceVariants(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPICopyObjectServerSideChecksumSourceVariants,
|
||||
endpoints: []string{
|
||||
"NewMultipart", "PutObjectPart", "CompleteMultipart", "ListObjectParts",
|
||||
"CopyObject", "PutObject", "HeadObject", "GetObject",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPICopyObjectServerSideChecksumSourceVariants(obj ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
restoreCompression := setCopyChecksumCompression(true)
|
||||
defer restoreCompression()
|
||||
|
||||
data := bytes.Repeat([]byte("source-variant-plaintext-"), 64*1024)
|
||||
|
||||
t.Run("compressed-source", func(t *testing.T) {
|
||||
source := "copy-checksum/compressed-source.txt"
|
||||
putCopyChecksumSource(t, apiRouter, credentials, bucketName, source, data, nil)
|
||||
if info, err := obj.GetObjectInfo(t.Context(), bucketName, source, ObjectOptions{}); err != nil || !info.IsCompressed() {
|
||||
t.Fatalf("%s: compressed source precondition failed: compressed=%v err=%v", instanceType, info.IsCompressed(), err)
|
||||
}
|
||||
destination := "copy-checksum/compressed-source-copy.txt"
|
||||
rec := copyChecksumRequest(t, apiRouter, credentials, bucketName, source, destination,
|
||||
map[string]string{xhttp.AmzChecksumAlgo: hash.ChecksumCRC32.String()})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: CopyObject failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
assertCopyChecksumResponse(t, rec, hash.ChecksumCRC32, data)
|
||||
assertCopyChecksum(t, obj, bucketName, destination, hash.ChecksumCRC32, data, true, nil)
|
||||
|
||||
rec = copyChecksumRequest(t, apiRouter, credentials, bucketName, source, source, map[string]string{
|
||||
xhttp.AmzChecksumAlgo: hash.ChecksumSHA256.String(),
|
||||
xhttp.AmzMetadataDirective: "REPLACE",
|
||||
})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: in-place CopyObject failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
assertCopyChecksumResponse(t, rec, hash.ChecksumSHA256, data)
|
||||
assertCopyChecksum(t, obj, bucketName, source, hash.ChecksumSHA256, data, true, nil)
|
||||
if got := readCopyChecksumObject(t, obj, bucketName, source, ObjectOptions{}); !bytes.Equal(got, data) {
|
||||
t.Fatalf("%s: in-place CopyObject body differs", instanceType)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("full-checksum-source", func(t *testing.T) {
|
||||
source := "copy-checksum/full-checksum-source.bin"
|
||||
want := mustChecksum(t, hash.ChecksumCRC32, data)
|
||||
putCopyChecksumSource(t, apiRouter, credentials, bucketName, source, data,
|
||||
map[string]string{xhttp.AmzChecksumCRC32: want})
|
||||
destination := "copy-checksum/full-checksum-copy.txt"
|
||||
rec := copyChecksumRequest(t, apiRouter, credentials, bucketName, source, destination, nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: CopyObject failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
assertCopyChecksumResponse(t, rec, hash.ChecksumCRC32, data)
|
||||
assertCopyChecksum(t, obj, bucketName, destination, hash.ChecksumCRC32, data, true, nil)
|
||||
})
|
||||
|
||||
t.Run("multipart-composite-source", func(t *testing.T) {
|
||||
typ := hash.ChecksumCRC32
|
||||
parts, full := multipartChecksumTestData()
|
||||
source := "copy-checksum/multipart-source.bin"
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, bucketName, source,
|
||||
typ.String(), xhttp.AmzChecksumTypeComposite)
|
||||
etags := uploadPartsHTTP(t, apiRouter, credentials, bucketName, source, uploadID, typ, parts)
|
||||
partChecksums := make([]string, len(parts))
|
||||
for i, part := range parts {
|
||||
partChecksums[i] = mustChecksum(t, typ, part)
|
||||
}
|
||||
rec := completeMultipartUploadHTTP(t, apiRouter, credentials, bucketName, source, uploadID,
|
||||
etags, partChecksums, nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: CompleteMultipartUpload failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
sourceInfo, err := obj.GetObjectInfo(t.Context(), bucketName, source, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("%s: source GetObjectInfo failed: %v", instanceType, err)
|
||||
}
|
||||
if _, multipart := sourceInfo.decryptChecksums(0, nil); !multipart {
|
||||
t.Fatalf("%s: source checksum is not multipart composite", instanceType)
|
||||
}
|
||||
|
||||
destination := "copy-checksum/multipart-copy.txt"
|
||||
rec = copyChecksumRequest(t, apiRouter, credentials, bucketName, source, destination, nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: CopyObject failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
assertCopyChecksumResponse(t, rec, typ, full)
|
||||
assertCopyChecksum(t, obj, bucketName, destination, typ, full, true, nil)
|
||||
if got := readCopyChecksumObject(t, obj, bucketName, destination, ObjectOptions{}); !bytes.Equal(got, full) {
|
||||
t.Fatalf("%s: multipart source round-trip body differs", instanceType)
|
||||
}
|
||||
})
|
||||
|
||||
for _, boundary := range []struct {
|
||||
name string
|
||||
data []byte
|
||||
compressed bool
|
||||
}{
|
||||
{name: "at-threshold", data: bytes.Repeat([]byte{'a'}, minCompressibleSize)},
|
||||
{name: "over-threshold", data: bytes.Repeat([]byte{'a'}, minCompressibleSize+1), compressed: true},
|
||||
{name: "indexed", data: bytes.Repeat([]byte{'a'}, compMinIndexSize+1), compressed: true},
|
||||
{name: "empty", data: nil},
|
||||
} {
|
||||
t.Run(boundary.name, func(t *testing.T) {
|
||||
source := "copy-checksum/" + boundary.name + "-source.bin"
|
||||
if _, err := obj.PutObject(t.Context(), bucketName, source,
|
||||
mustGetPutObjReader(t, bytes.NewReader(boundary.data), int64(len(boundary.data)), "", ""), ObjectOptions{}); err != nil {
|
||||
t.Fatalf("%s: source PutObject failed: %v", instanceType, err)
|
||||
}
|
||||
destination := "copy-checksum/" + boundary.name + "-copy.txt"
|
||||
rec := copyChecksumRequest(t, apiRouter, credentials, bucketName, source, destination,
|
||||
map[string]string{xhttp.AmzChecksumAlgo: hash.ChecksumCRC32.String()})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: CopyObject failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
assertCopyChecksumResponse(t, rec, hash.ChecksumCRC32, boundary.data)
|
||||
assertCopyChecksum(t, obj, bucketName, destination, hash.ChecksumCRC32, boundary.data, boundary.compressed, nil)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPutObjectRejectsMissingServerSideChecksum(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testPutObjectRejectsMissingServerSideChecksum,
|
||||
endpoints: []string{"PutObject"},
|
||||
})
|
||||
}
|
||||
|
||||
func testPutObjectRejectsMissingServerSideChecksum(obj ObjectLayer, instanceType, bucketName string,
|
||||
_ http.Handler, _ auth.Credentials, t *testing.T,
|
||||
) {
|
||||
data := []byte("the object layer must not silently omit a requested checksum")
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
hasherType hash.ChecksumType
|
||||
}{
|
||||
{name: "missing"},
|
||||
{name: "mismatched", hasherType: hash.ChecksumCRC32C},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
object := "copy-checksum/" + test.name + "-server-side-checksum"
|
||||
reader := mustGetPutObjReader(t, bytes.NewReader(data), int64(len(data)), "", "")
|
||||
if test.hasherType.IsSet() {
|
||||
reader.AddServerSideChecksumHasher(test.hasherType)
|
||||
}
|
||||
_, err := obj.PutObject(t.Context(), bucketName, object, reader,
|
||||
ObjectOptions{WantServerSideChecksumType: hash.ChecksumCRC32})
|
||||
if err == nil || !strings.Contains(err.Error(), "server-side checksum") {
|
||||
t.Fatalf("%s: PutObject error %v, want server-side checksum invariant error", instanceType, err)
|
||||
}
|
||||
if _, err = obj.GetObjectInfo(t.Context(), bucketName, object, ObjectOptions{}); !isErrObjectNotFound(err) {
|
||||
t.Fatalf("%s: failed PutObject left an object behind: %v", instanceType, err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,609 @@
|
||||
// Copyright (c) 2015-2026 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/minio/minio/internal/auth"
|
||||
"github.com/minio/minio/internal/hash"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
)
|
||||
|
||||
func TestAPICopyObjectMetadataOnlyCompression(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
for _, versioned := range []bool{false, true} {
|
||||
name := "unversioned"
|
||||
if versioned {
|
||||
name = "versioned"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPICopyObjectMetadataOnlyCompression,
|
||||
endpoints: []string{"CopyObject", "PutObject", "GetObject"},
|
||||
makeBucketOptions: MakeBucketOptions{VersioningEnabled: versioned},
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func testAPICopyObjectMetadataOnlyCompression(obj ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
data := bytes.Repeat([]byte("metadata-only-copy-plaintext-"), 64*1024)
|
||||
want := mustChecksum(t, hash.ChecksumCRC32, data)
|
||||
object := "copy-metadata/existing-checksum.txt"
|
||||
putCopyChecksumSource(t, apiRouter, credentials, bucketName, object, data,
|
||||
map[string]string{xhttp.AmzChecksumCRC32: want})
|
||||
before, err := obj.GetObjectInfo(t.Context(), bucketName, object, ObjectOptions{})
|
||||
if err != nil || before.IsCompressed() {
|
||||
t.Fatalf("%s: invalid metadata-copy precondition: compressed=%v size=%d err=%v",
|
||||
instanceType, before.IsCompressed(), before.Size, err)
|
||||
}
|
||||
|
||||
restoreCompression := setCopyChecksumCompression(true)
|
||||
compressionRestored := false
|
||||
defer func() {
|
||||
if !compressionRestored {
|
||||
restoreCompression()
|
||||
}
|
||||
}()
|
||||
|
||||
rec := copyChecksumRequest(t, apiRouter, credentials, bucketName, object, object,
|
||||
map[string]string{xhttp.AmzMetadataDirective: "REPLACE"})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: metadata-only CopyObject failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
assertCopyChecksum(t, obj, bucketName, object, hash.ChecksumCRC32, data, false, nil)
|
||||
if got := readCopyChecksumObject(t, obj, bucketName, object, ObjectOptions{}); !bytes.Equal(got, data) {
|
||||
prefix := got
|
||||
if len(prefix) > 100 {
|
||||
prefix = prefix[:100]
|
||||
}
|
||||
t.Fatalf("%s: metadata-only CopyObject body differs: got %d bytes, want %d, prefix %q",
|
||||
instanceType, len(got), len(data), prefix)
|
||||
}
|
||||
afterMetadataCopy, err := obj.GetObjectInfo(t.Context(), bucketName, object, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if before.VersionID != "" && afterMetadataCopy.VersionID == before.VersionID {
|
||||
t.Fatalf("%s: versioned metadata-only copy did not create a new version", instanceType)
|
||||
}
|
||||
|
||||
destination := "copy-metadata/rewritten.txt"
|
||||
rec = copyChecksumRequest(t, apiRouter, credentials, bucketName, object, destination, nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: data-rewriting CopyObject failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
assertCopyChecksum(t, obj, bucketName, destination, hash.ChecksumCRC32, data, true, nil)
|
||||
|
||||
compressedObject := "copy-metadata/preserve-compressed.txt"
|
||||
putCopyChecksumSource(t, apiRouter, credentials, bucketName, compressedObject, data,
|
||||
map[string]string{xhttp.AmzChecksumCRC32: want})
|
||||
assertCopyChecksum(t, obj, bucketName, compressedObject, hash.ChecksumCRC32, data, true, nil)
|
||||
|
||||
restoreCompression()
|
||||
compressionRestored = true
|
||||
rec = copyChecksumRequest(t, apiRouter, credentials, bucketName, compressedObject, compressedObject,
|
||||
map[string]string{xhttp.AmzMetadataDirective: "REPLACE"})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: compressed metadata-only CopyObject failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
assertCopyChecksum(t, obj, bucketName, compressedObject, hash.ChecksumCRC32, data, true, nil)
|
||||
if got := readCopyChecksumObject(t, obj, bucketName, compressedObject, ObjectOptions{}); !bytes.Equal(got, data) {
|
||||
t.Fatalf("%s: compressed metadata-only CopyObject body differs", instanceType)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPICopyObjectSSECKeyRotationKeepsCompressionState(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
for _, versioned := range []bool{false, true} {
|
||||
name := "unversioned"
|
||||
if versioned {
|
||||
name = "versioned"
|
||||
}
|
||||
t.Run(name, func(t *testing.T) {
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPICopyObjectSSECKeyRotationKeepsCompressionState,
|
||||
endpoints: []string{"CopyObject", "PutObject", "GetObject"},
|
||||
makeBucketOptions: MakeBucketOptions{VersioningEnabled: versioned},
|
||||
})
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func testAPICopyObjectSSECKeyRotationKeepsCompressionState(obj ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
previousTLS := globalIsTLS
|
||||
globalIsTLS = true
|
||||
defer func() { globalIsTLS = previousTLS }()
|
||||
|
||||
data := bytes.Repeat([]byte("key-rotation-plaintext-"), 64*1024)
|
||||
object := "copy-metadata/key-rotation.txt"
|
||||
oldKey := bytes.Repeat([]byte{0x11}, 32)
|
||||
oldMD5 := md5.Sum(oldKey)
|
||||
newKey := bytes.Repeat([]byte{0x22}, 32)
|
||||
newMD5 := md5.Sum(newKey)
|
||||
|
||||
putCopyChecksumSource(t, apiRouter, credentials, bucketName, object, data, map[string]string{
|
||||
xhttp.AmzChecksumCRC32: mustChecksum(t, hash.ChecksumCRC32, data),
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(oldKey),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(oldMD5[:]),
|
||||
})
|
||||
before, err := obj.GetObjectInfo(t.Context(), bucketName, object, ObjectOptions{})
|
||||
if err != nil || before.IsCompressed() {
|
||||
t.Fatalf("%s: invalid key-rotation precondition: compressed=%v err=%v", instanceType, before.IsCompressed(), err)
|
||||
}
|
||||
|
||||
restoreCompression := setCopyChecksumCompression(true)
|
||||
defer restoreCompression()
|
||||
rec := copyChecksumRequest(t, apiRouter, credentials, bucketName, object, object, map[string]string{
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(newKey),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(newMD5[:]),
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerKey: base64.StdEncoding.EncodeToString(oldKey),
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerKeyMD5: base64.StdEncoding.EncodeToString(oldMD5[:]),
|
||||
})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: key rotation failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
assertCopyChecksumResponse(t, rec, hash.ChecksumCRC32, data)
|
||||
after, err := obj.GetObjectInfo(t.Context(), bucketName, object, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if after.IsCompressed() {
|
||||
t.Fatalf("%s: metadata-only key rotation stamped compression metadata", instanceType)
|
||||
}
|
||||
if before.VersionID != "" && after.VersionID == before.VersionID {
|
||||
t.Fatalf("%s: versioned key rotation did not create a new version", instanceType)
|
||||
}
|
||||
|
||||
getHeaders := map[string]string{
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(newKey),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(newMD5[:]),
|
||||
}
|
||||
req, err := newTestSignedRequestV4(http.MethodGet, getGetObjectURL("", bucketName, object),
|
||||
0, nil, credentials.AccessKey, credentials.SecretKey, getHeaders)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to build GetObject request: %v", err)
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(response, req)
|
||||
if response.Code != http.StatusOK || !bytes.Equal(response.Body.Bytes(), data) {
|
||||
t.Fatalf("%s: post-rotation GetObject returned %d with %d bytes, want 200 with %d bytes: %s",
|
||||
instanceType, response.Code, response.Body.Len(), len(data), response.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPICopyObjectMetadataOnlyNullVersion covers the copy whose source is a
|
||||
// null version on a bucket that gained versioning after the object was written.
|
||||
// The object layer cannot reference such a version, so it rewrites the data and
|
||||
// the recorded compression metadata has to describe the rewritten bytes.
|
||||
func TestAPICopyObjectMetadataOnlyNullVersion(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPICopyObjectMetadataOnlyNullVersion,
|
||||
endpoints: []string{"CopyObject", "PutObject", "GetObject"},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPICopyObjectMetadataOnlyNullVersion(obj ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
restoreCompression := setCopyChecksumCompression(true)
|
||||
compressionRestored := false
|
||||
defer func() {
|
||||
if !compressionRestored {
|
||||
restoreCompression()
|
||||
}
|
||||
}()
|
||||
|
||||
data := bytes.Repeat([]byte("null-version-metadata-copy-"), 64*1024)
|
||||
want := mustChecksum(t, hash.ChecksumCRC32, data)
|
||||
object := "copy-metadata/null-version.txt"
|
||||
putCopyChecksumSource(t, apiRouter, credentials, bucketName, object, data,
|
||||
map[string]string{xhttp.AmzChecksumCRC32: want})
|
||||
|
||||
before, err := obj.GetObjectInfo(t.Context(), bucketName, object, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !before.IsCompressed() || before.VersionID != "" {
|
||||
t.Fatalf("%s: invalid null-version precondition: compressed=%v versionID=%q",
|
||||
instanceType, before.IsCompressed(), before.VersionID)
|
||||
}
|
||||
|
||||
// Versioning is enabled after the write, so the object keeps a null version.
|
||||
if _, err := globalBucketMetadataSys.Update(t.Context(), bucketName,
|
||||
bucketVersioningConfig, enabledBucketVersioningConfig); err != nil {
|
||||
t.Fatalf("%s: unable to enable versioning: %v", instanceType, err)
|
||||
}
|
||||
if !globalBucketVersioningSys.PrefixEnabled(bucketName, object) {
|
||||
t.Fatalf("%s: versioning did not become enabled", instanceType)
|
||||
}
|
||||
|
||||
// Without compression the rewritten destination stores plaintext.
|
||||
restoreCompression()
|
||||
compressionRestored = true
|
||||
|
||||
rec := copyChecksumRequest(t, apiRouter, credentials, bucketName, object, object,
|
||||
map[string]string{xhttp.AmzMetadataDirective: "REPLACE"})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: metadata-only CopyObject failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
after := assertCopyChecksum(t, obj, bucketName, object, hash.ChecksumCRC32, data, false, nil)
|
||||
if after.VersionID == "" {
|
||||
t.Fatalf("%s: versioned copy did not create a new version", instanceType)
|
||||
}
|
||||
if got := readCopyChecksumObject(t, obj, bucketName, object, ObjectOptions{}); !bytes.Equal(got, data) {
|
||||
t.Fatalf("%s: copied object body differs: got %d bytes, want %d", instanceType, len(got), len(data))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPICopyObjectMetadataOnlyNullVersionCompressesRewrite(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPICopyObjectMetadataOnlyNullVersionCompressesRewrite,
|
||||
endpoints: []string{"CopyObject", "PutObject", "GetObject"},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPICopyObjectMetadataOnlyNullVersionCompressesRewrite(obj ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
globalCompressConfigMu.Lock()
|
||||
previousCompression := globalCompressConfig
|
||||
globalCompressConfig.Enabled = false
|
||||
globalCompressConfigMu.Unlock()
|
||||
defer func() {
|
||||
globalCompressConfigMu.Lock()
|
||||
globalCompressConfig = previousCompression
|
||||
globalCompressConfigMu.Unlock()
|
||||
}()
|
||||
|
||||
data := bytes.Repeat([]byte("null-version-compress-rewrite-"), 64*1024)
|
||||
want := mustChecksum(t, hash.ChecksumCRC32, data)
|
||||
object := "copy-metadata/null-version-compress.txt"
|
||||
putCopyChecksumSource(t, apiRouter, credentials, bucketName, object, data,
|
||||
map[string]string{xhttp.AmzChecksumCRC32: want})
|
||||
|
||||
before, err := obj.GetObjectInfo(t.Context(), bucketName, object, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if before.IsCompressed() || before.VersionID != "" {
|
||||
t.Fatalf("%s: invalid null-version precondition: compressed=%v versionID=%q",
|
||||
instanceType, before.IsCompressed(), before.VersionID)
|
||||
}
|
||||
if _, err := globalBucketMetadataSys.Update(t.Context(), bucketName,
|
||||
bucketVersioningConfig, enabledBucketVersioningConfig); err != nil {
|
||||
t.Fatalf("%s: unable to enable versioning: %v", instanceType, err)
|
||||
}
|
||||
|
||||
restoreCopyCompression := setCopyChecksumCompression(false)
|
||||
defer restoreCopyCompression()
|
||||
rec := copyChecksumRequest(t, apiRouter, credentials, bucketName, object, object,
|
||||
map[string]string{xhttp.AmzMetadataDirective: "REPLACE"})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: metadata-only CopyObject failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
after := assertCopyChecksum(t, obj, bucketName, object, hash.ChecksumCRC32, data, true, nil)
|
||||
if after.VersionID == "" {
|
||||
t.Fatalf("%s: versioned copy did not create a new version", instanceType)
|
||||
}
|
||||
if got := readCopyChecksumObject(t, obj, bucketName, object, ObjectOptions{}); !bytes.Equal(got, data) {
|
||||
t.Fatalf("%s: copied object body differs: got %d bytes, want %d", instanceType, len(got), len(data))
|
||||
}
|
||||
}
|
||||
|
||||
func TestCopyRewritesObjectData(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
metadataOnly bool
|
||||
srcOpts ObjectOptions
|
||||
dstOpts ObjectOptions
|
||||
want bool
|
||||
}{
|
||||
{
|
||||
name: "data copy always rewrites",
|
||||
want: true,
|
||||
},
|
||||
// PostRestoreObjectHandler, updateRestoreMetadata and batchKeyRotate all
|
||||
// address the same version on both sides and never set Versioned, so they
|
||||
// only ever reach these two cases.
|
||||
{
|
||||
name: "unversioned in-place metadata update",
|
||||
metadataOnly: true,
|
||||
},
|
||||
{
|
||||
name: "addressed version updated in place",
|
||||
metadataOnly: true,
|
||||
srcOpts: ObjectOptions{VersionID: "v1"},
|
||||
dstOpts: ObjectOptions{VersionID: "v1"},
|
||||
},
|
||||
{
|
||||
name: "versioned self referential version",
|
||||
metadataOnly: true,
|
||||
srcOpts: ObjectOptions{VersionID: "v1"},
|
||||
dstOpts: ObjectOptions{Versioned: true},
|
||||
},
|
||||
{
|
||||
name: "versioned null source version cannot be referenced",
|
||||
metadataOnly: true,
|
||||
dstOpts: ObjectOptions{Versioned: true},
|
||||
want: true,
|
||||
},
|
||||
{
|
||||
name: "suspended destination with an addressed source version",
|
||||
metadataOnly: true,
|
||||
srcOpts: ObjectOptions{VersionID: "v1"},
|
||||
dstOpts: ObjectOptions{VersionSuspended: true, VersionID: nullVersionID},
|
||||
want: true,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
if got := copyRewritesObjectData(tt.metadataOnly, tt.srcOpts, tt.dstOpts); got != tt.want {
|
||||
t.Fatalf("copyRewritesObjectData() = %v, want %v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPICopyObjectSSECKeyRotationNullVersion covers an SSE-C key rotation whose
|
||||
// source is a null version on a bucket that gained versioning after the object
|
||||
// was written. A rotation only rewraps the object key held in metadata, so it
|
||||
// may not take the metadata-only path when the object layer stores new object
|
||||
// data; the rotation has to re-encrypt instead.
|
||||
func TestAPICopyObjectSSECKeyRotationNullVersion(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPICopyObjectSSECKeyRotationNullVersion,
|
||||
endpoints: []string{"CopyObject", "PutObject", "GetObject"},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPICopyObjectSSECKeyRotationNullVersion(obj ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
testAPICopyObjectSSECKeyRotationNullVersionWithCompression(obj, instanceType, bucketName,
|
||||
apiRouter, credentials, false, t)
|
||||
}
|
||||
|
||||
func TestAPICopyObjectSSECKeyRotationNullVersionCompressesRewrite(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPICopyObjectSSECKeyRotationNullVersionCompressesRewrite,
|
||||
endpoints: []string{"CopyObject", "PutObject", "GetObject"},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPICopyObjectSSECKeyRotationNullVersionCompressesRewrite(obj ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
testAPICopyObjectSSECKeyRotationNullVersionWithCompression(obj, instanceType, bucketName,
|
||||
apiRouter, credentials, true, t)
|
||||
}
|
||||
|
||||
func testAPICopyObjectSSECKeyRotationNullVersionWithCompression(obj ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, compressAtCopy bool, t *testing.T,
|
||||
) {
|
||||
previousTLS := globalIsTLS
|
||||
globalIsTLS = true
|
||||
defer func() { globalIsTLS = previousTLS }()
|
||||
|
||||
data := bytes.Repeat([]byte("key-rotation-null-version-"), 64*1024)
|
||||
object := "copy-metadata/key-rotation-null.txt"
|
||||
oldKey := bytes.Repeat([]byte{0x11}, 32)
|
||||
oldMD5 := md5.Sum(oldKey)
|
||||
newKey := bytes.Repeat([]byte{0x22}, 32)
|
||||
newMD5 := md5.Sum(newKey)
|
||||
|
||||
putCopyChecksumSource(t, apiRouter, credentials, bucketName, object, data, map[string]string{
|
||||
xhttp.AmzChecksumCRC32: mustChecksum(t, hash.ChecksumCRC32, data),
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(oldKey),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(oldMD5[:]),
|
||||
})
|
||||
before, err := obj.GetObjectInfo(t.Context(), bucketName, object, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if before.VersionID != "" {
|
||||
t.Fatalf("%s: invalid null-version precondition: versionID=%q", instanceType, before.VersionID)
|
||||
}
|
||||
|
||||
// Versioning is enabled after the write, so the object keeps a null version.
|
||||
if _, err := globalBucketMetadataSys.Update(t.Context(), bucketName,
|
||||
bucketVersioningConfig, enabledBucketVersioningConfig); err != nil {
|
||||
t.Fatalf("%s: unable to enable versioning: %v", instanceType, err)
|
||||
}
|
||||
if !globalBucketVersioningSys.PrefixEnabled(bucketName, object) {
|
||||
t.Fatalf("%s: versioning did not become enabled", instanceType)
|
||||
}
|
||||
if compressAtCopy {
|
||||
restoreCompression := setCopyChecksumCompression(true)
|
||||
defer restoreCompression()
|
||||
}
|
||||
|
||||
rec := copyChecksumRequest(t, apiRouter, credentials, bucketName, object, object, map[string]string{
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(newKey),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(newMD5[:]),
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerKey: base64.StdEncoding.EncodeToString(oldKey),
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerKeyMD5: base64.StdEncoding.EncodeToString(oldMD5[:]),
|
||||
})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: key rotation failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
assertCopyChecksumResponse(t, rec, hash.ChecksumCRC32, data)
|
||||
|
||||
getHeaders := map[string]string{
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(newKey),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(newMD5[:]),
|
||||
}
|
||||
req, err := newTestSignedRequestV4(http.MethodGet, getGetObjectURL("", bucketName, object),
|
||||
0, nil, credentials.AccessKey, credentials.SecretKey, getHeaders)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to build GetObject request: %v", err)
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(response, req)
|
||||
if response.Code != http.StatusOK || !bytes.Equal(response.Body.Bytes(), data) {
|
||||
t.Fatalf("%s: post-rotation GetObject returned %d with %d bytes, want 200 with %d bytes: %s",
|
||||
instanceType, response.Code, response.Body.Len(), len(data), response.Body.String())
|
||||
}
|
||||
|
||||
decryptHeaders := http.Header{}
|
||||
for key, value := range getHeaders {
|
||||
decryptHeaders.Set(key, value)
|
||||
}
|
||||
after := assertCopyChecksum(t, obj, bucketName, object, hash.ChecksumCRC32, data, compressAtCopy, decryptHeaders)
|
||||
if after.VersionID == "" {
|
||||
t.Fatalf("%s: rotation into a versioned bucket did not create a new version", instanceType)
|
||||
}
|
||||
// The rotation could not be applied in place, so the object was re-encrypted
|
||||
// under a fresh object key. That regenerates the encrypted ETag, unlike an
|
||||
// in-place rotation which leaves the stored bytes and the ETag alone.
|
||||
if after.ETag == before.ETag {
|
||||
t.Fatalf("%s: re-encrypting rotation kept the source ETag %q", instanceType, after.ETag)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPICopyObjectSSECKeyRotationNullVersionWrongKey pins source-key
|
||||
// authentication in both the standalone rotation fix and the later zero-byte
|
||||
// read hardening.
|
||||
func TestAPICopyObjectSSECKeyRotationNullVersionWrongKey(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPICopyObjectSSECKeyRotationNullVersionWrongKey,
|
||||
endpoints: []string{"CopyObject", "PutObject", "GetObject"},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPICopyObjectSSECKeyRotationNullVersionWrongKey(obj ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
previousTLS := globalIsTLS
|
||||
globalIsTLS = true
|
||||
defer func() { globalIsTLS = previousTLS }()
|
||||
|
||||
object := "copy-metadata/key-rotation-null-empty.txt"
|
||||
oldKey := bytes.Repeat([]byte{0x11}, 32)
|
||||
oldMD5 := md5.Sum(oldKey)
|
||||
wrongKey := bytes.Repeat([]byte{0x33}, 32)
|
||||
wrongMD5 := md5.Sum(wrongKey)
|
||||
newKey := bytes.Repeat([]byte{0x22}, 32)
|
||||
newMD5 := md5.Sum(newKey)
|
||||
|
||||
putCopyChecksumSource(t, apiRouter, credentials, bucketName, object, nil, map[string]string{
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(oldKey),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(oldMD5[:]),
|
||||
})
|
||||
before, err := obj.GetObjectInfo(t.Context(), bucketName, object, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if before.Size != 0 || before.VersionID != "" || len(before.Checksum) != 0 {
|
||||
t.Fatalf("%s: invalid empty null-version precondition: size=%d versionID=%q checksum=%d",
|
||||
instanceType, before.Size, before.VersionID, len(before.Checksum))
|
||||
}
|
||||
|
||||
if _, err := globalBucketMetadataSys.Update(t.Context(), bucketName,
|
||||
bucketVersioningConfig, enabledBucketVersioningConfig); err != nil {
|
||||
t.Fatalf("%s: unable to enable versioning: %v", instanceType, err)
|
||||
}
|
||||
|
||||
rec := copyChecksumRequest(t, apiRouter, credentials, bucketName, object, object, map[string]string{
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(newKey),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(newMD5[:]),
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerKey: base64.StdEncoding.EncodeToString(wrongKey),
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerKeyMD5: base64.StdEncoding.EncodeToString(wrongMD5[:]),
|
||||
})
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("%s: rotation with an incorrect source key returned %d, want %d: %s",
|
||||
instanceType, rec.Code, http.StatusForbidden, rec.Body.String())
|
||||
}
|
||||
|
||||
rec = copyChecksumRequest(t, apiRouter, credentials, bucketName, object, object, map[string]string{
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(newKey),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(newMD5[:]),
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerKey: base64.StdEncoding.EncodeToString(newKey),
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerKeyMD5: base64.StdEncoding.EncodeToString(newMD5[:]),
|
||||
})
|
||||
// The zero-byte read path authenticates the source key before the
|
||||
// rotation-specific equal-key distinction, matching non-empty reads.
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("%s: rotation with equal invalid keys returned %d, want %d: %s",
|
||||
instanceType, rec.Code, http.StatusForbidden, rec.Body.String())
|
||||
}
|
||||
|
||||
after, err := obj.GetObjectInfo(t.Context(), bucketName, object, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if after.VersionID != "" {
|
||||
t.Fatalf("%s: rejected rotation still created version %q", instanceType, after.VersionID)
|
||||
}
|
||||
|
||||
// The object stays readable with the key it was written under.
|
||||
req, err := newTestSignedRequestV4(http.MethodGet, getGetObjectURL("", bucketName, object),
|
||||
0, nil, credentials.AccessKey, credentials.SecretKey, map[string]string{
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(oldKey),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(oldMD5[:]),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("failed to build GetObject request: %v", err)
|
||||
}
|
||||
response := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(response, req)
|
||||
if response.Code != http.StatusOK || response.Body.Len() != 0 {
|
||||
t.Fatalf("%s: original object no longer readable: %d with %d bytes: %s",
|
||||
instanceType, response.Code, response.Body.Len(), response.Body.String())
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,79 @@
|
||||
// Copyright (c) 2015-2026 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/minio/minio/internal/auth"
|
||||
"github.com/minio/minio/internal/hash"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
)
|
||||
|
||||
func TestAPIPutObjectRejectsCRC64Composite(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPIPutObjectRejectsCRC64Composite,
|
||||
endpoints: []string{"PutObject"},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPIPutObjectRejectsCRC64Composite(obj ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
data := []byte("crc64-composite")
|
||||
object := "checksums/crc64-composite"
|
||||
req, err := newTestSignedRequestV4(http.MethodPut, getPutObjectURL("", bucketName, object),
|
||||
int64(len(data)), bytes.NewReader(data), credentials.AccessKey, credentials.SecretKey, map[string]string{
|
||||
xhttp.AmzChecksumCRC64NVME: mustChecksum(t, hash.ChecksumCRC64NVME, data),
|
||||
xhttp.AmzChecksumType: xhttp.AmzChecksumTypeComposite,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest || apiErrorCode(t, rec) != "InvalidArgument" {
|
||||
t.Fatalf("%s: CRC64NVME/COMPOSITE PutObject returned %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
if _, err := obj.GetObjectInfo(t.Context(), bucketName, object, ObjectOptions{}); !isErrObjectNotFound(err) {
|
||||
t.Fatalf("%s: rejected PutObject stored an object: %v", instanceType, err)
|
||||
}
|
||||
|
||||
trailerObject := "checksums/crc64-composite-trailer"
|
||||
req, err = newTestSignedRequestV4(http.MethodPut, getPutObjectURL("", bucketName, trailerObject),
|
||||
int64(len(data)), bytes.NewReader(data), credentials.AccessKey, credentials.SecretKey, map[string]string{
|
||||
xhttp.AmzTrailer: xhttp.AmzChecksumCRC64NVME,
|
||||
xhttp.AmzChecksumType: xhttp.AmzChecksumTypeComposite,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec = httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest || apiErrorCode(t, rec) != "InvalidArgument" {
|
||||
t.Fatalf("%s: trailing CRC64NVME/COMPOSITE PutObject returned %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
if _, err := obj.GetObjectInfo(t.Context(), bucketName, trailerObject, ObjectOptions{}); !isErrObjectNotFound(err) {
|
||||
t.Fatalf("%s: rejected trailing PutObject stored an object: %v", instanceType, err)
|
||||
}
|
||||
}
|
||||
@@ -353,6 +353,11 @@ func isETagEqual(left, right string) bool {
|
||||
// upon a success Put/Copy/CompleteMultipart/Delete requests
|
||||
// to activate delete only headers set delete as true
|
||||
func setPutObjHeaders(w http.ResponseWriter, objInfo ObjectInfo, del bool, h http.Header) {
|
||||
cs, _ := objInfo.decryptChecksums(0, h)
|
||||
setPutObjHeadersWithChecksum(w, objInfo, del, cs)
|
||||
}
|
||||
|
||||
func setPutObjHeadersWithChecksum(w http.ResponseWriter, objInfo ObjectInfo, del bool, cs map[string]string) {
|
||||
// We must not use the http.Header().Set method here because some (broken)
|
||||
// clients expect the ETag header key to be literally "ETag" - not "Etag" (case-sensitive).
|
||||
// Therefore, we have to set the ETag directly as map entry.
|
||||
@@ -374,7 +379,6 @@ func setPutObjHeaders(w http.ResponseWriter, objInfo ObjectInfo, del bool, h htt
|
||||
lc.SetPredictionHeaders(w, objInfo.ToLifecycleOpts())
|
||||
}
|
||||
}
|
||||
cs, _ := objInfo.decryptChecksums(0, h)
|
||||
hash.AddChecksumHeader(w, cs)
|
||||
}
|
||||
|
||||
|
||||
+317
-109
@@ -356,6 +356,18 @@ func (api objectAPIHandlers) getObjectHandler(ctx context.Context, objectAPI Obj
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Error), r.URL)
|
||||
return
|
||||
}
|
||||
if hasReplicationMarkerHeader(r.Header) {
|
||||
trusted := hasReplicationMarker(r.Header) &&
|
||||
replicationPermissionAllowed(ctx, r, bucket, object, policy.ReplicateObjectAction)
|
||||
ctx, r = applyReplicationTrust(ctx, r, trusted, trusted)
|
||||
if trusted {
|
||||
opts, err = getOpts(ctx, r, bucket, object)
|
||||
if err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getObjectNInfo := objectAPI.GetObjectNInfo
|
||||
|
||||
@@ -494,8 +506,8 @@ func (api objectAPIHandlers) getObjectHandler(ctx context.Context, objectAPI Obj
|
||||
}
|
||||
|
||||
// filter object lock metadata if permission does not permit
|
||||
getRetPerms := checkRequestAuthType(ctx, r, policy.GetObjectRetentionAction, bucket, object)
|
||||
legalHoldPerms := checkRequestAuthType(ctx, r, policy.GetObjectLegalHoldAction, bucket, object)
|
||||
getRetPerms := authorizeRequest(ctx, r, policy.GetObjectRetentionAction)
|
||||
legalHoldPerms := authorizeRequest(ctx, r, policy.GetObjectLegalHoldAction)
|
||||
|
||||
// filter object lock metadata if permission does not permit
|
||||
objInfo.UserDefined = objectlock.FilterObjectLockMetadata(objInfo.UserDefined, getRetPerms != ErrNone, legalHoldPerms != ErrNone)
|
||||
@@ -599,10 +611,16 @@ func (api objectAPIHandlers) getObjectAttributesHandler(ctx context.Context, obj
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Error), r.URL)
|
||||
return
|
||||
}
|
||||
if hasReplicationMarkerHeader(r.Header) {
|
||||
trusted := hasReplicationMarker(r.Header) &&
|
||||
replicationPermissionAllowed(ctx, r, bucket, object, policy.ReplicateObjectAction)
|
||||
ctx, r = applyReplicationTrust(ctx, r, trusted, trusted)
|
||||
opts.ReplicationRequest = trusted
|
||||
}
|
||||
|
||||
objInfo, err := objectAPI.GetObjectInfo(ctx, bucket, object, opts)
|
||||
if err != nil {
|
||||
s3Error = checkRequestAuthType(ctx, r, policy.ListBucketAction, bucket, object)
|
||||
s3Error = authorizeRequest(ctx, r, policy.ListBucketAction)
|
||||
if s3Error == ErrNone {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
@@ -619,6 +637,15 @@ func (api objectAPIHandlers) getObjectAttributesHandler(ctx context.Context, obj
|
||||
if checkPreconditions(ctx, w, r, objInfo, opts) {
|
||||
return
|
||||
}
|
||||
// Only a caller authorized to replicate this object may read SSE-C
|
||||
// attributes without presenting the customer key. The header alone is
|
||||
// client controlled, so it cannot stand in for that authorization.
|
||||
if crypto.SSEC.IsEncrypted(objInfo.UserDefined) && !isReplicaTrusted(ctx) {
|
||||
if _, err = crypto.SSEC.UnsealObjectKey(r.Header, objInfo.UserDefined, bucket, object); err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
OA := new(getObjectAttributesResponse)
|
||||
|
||||
@@ -789,6 +816,18 @@ func (api objectAPIHandlers) headObjectHandler(ctx context.Context, objectAPI Ob
|
||||
writeErrorResponseHeadersOnly(w, errorCodes.ToAPIErr(s3Error))
|
||||
return
|
||||
}
|
||||
if hasReplicationMarkerHeader(r.Header) {
|
||||
trusted := hasReplicationMarker(r.Header) &&
|
||||
replicationPermissionAllowed(ctx, r, bucket, object, policy.ReplicateObjectAction)
|
||||
ctx, r = applyReplicationTrust(ctx, r, trusted, trusted)
|
||||
if trusted {
|
||||
opts, err = getOpts(ctx, r, bucket, object)
|
||||
if err != nil {
|
||||
writeErrorResponseHeadersOnly(w, toAPIError(ctx, err))
|
||||
return
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Get request range.
|
||||
var rs *HTTPRangeSpec
|
||||
@@ -900,8 +939,8 @@ func (api objectAPIHandlers) headObjectHandler(ctx context.Context, objectAPI Ob
|
||||
}
|
||||
|
||||
// filter object lock metadata if permission does not permit
|
||||
getRetPerms := checkRequestAuthType(ctx, r, policy.GetObjectRetentionAction, bucket, object)
|
||||
legalHoldPerms := checkRequestAuthType(ctx, r, policy.GetObjectLegalHoldAction, bucket, object)
|
||||
getRetPerms := authorizeRequest(ctx, r, policy.GetObjectRetentionAction)
|
||||
legalHoldPerms := authorizeRequest(ctx, r, policy.GetObjectLegalHoldAction)
|
||||
|
||||
// filter object lock metadata if permission does not permit
|
||||
objInfo.UserDefined = objectlock.FilterObjectLockMetadata(objInfo.UserDefined, getRetPerms != ErrNone, legalHoldPerms != ErrNone)
|
||||
@@ -927,10 +966,12 @@ func (api objectAPIHandlers) headObjectHandler(ctx context.Context, objectAPI Ob
|
||||
w.Header().Set(xhttp.AmzServerSideEncryptionKmsContext, kmsCtx)
|
||||
}
|
||||
case crypto.SSEC:
|
||||
// Validate the SSE-C Key set in the header.
|
||||
if _, err = crypto.SSEC.UnsealObjectKey(r.Header, objInfo.UserDefined, bucket, object); err != nil {
|
||||
writeErrorResponseHeadersOnly(w, toAPIError(ctx, err))
|
||||
return
|
||||
if !isReplicaTrusted(ctx) {
|
||||
// Validate the SSE-C Key set in the header for ordinary reads.
|
||||
if _, err = crypto.SSEC.UnsealObjectKey(r.Header, objInfo.UserDefined, bucket, object); err != nil {
|
||||
writeErrorResponseHeadersOnly(w, toAPIError(ctx, err))
|
||||
return
|
||||
}
|
||||
}
|
||||
w.Header().Set(xhttp.AmzServerSideEncryptionCustomerAlgorithm, r.Header.Get(xhttp.AmzServerSideEncryptionCustomerAlgorithm))
|
||||
w.Header().Set(xhttp.AmzServerSideEncryptionCustomerKeyMD5, r.Header.Get(xhttp.AmzServerSideEncryptionCustomerKeyMD5))
|
||||
@@ -1082,29 +1123,12 @@ func getCpObjMetadataFromHeader(ctx context.Context, r *http.Request, userMeta m
|
||||
return defaultMeta, nil
|
||||
}
|
||||
|
||||
func cloneRequestWithoutCopyReplicationHeaders(r *http.Request) *http.Request {
|
||||
if r == nil {
|
||||
return nil
|
||||
}
|
||||
|
||||
clone := new(http.Request)
|
||||
*clone = *r
|
||||
clone.Header = r.Header.Clone()
|
||||
|
||||
for _, header := range []string{
|
||||
xhttp.MinIOSourceReplicationRequest,
|
||||
xhttp.MinIOSourceETag,
|
||||
xhttp.MinIOSourceMTime,
|
||||
xhttp.MinIOSourceTaggingTimestamp,
|
||||
xhttp.MinIOSourceObjectRetentionTimestamp,
|
||||
xhttp.MinIOSourceObjectLegalHoldTimestamp,
|
||||
xhttp.MinIOReplicationActualObjectSize,
|
||||
ReplicationSsecChecksumHeader,
|
||||
} {
|
||||
clone.Header.Del(header)
|
||||
}
|
||||
|
||||
return clone
|
||||
func copyDestinationSSEHeaders(h http.Header) http.Header {
|
||||
dst := h.Clone()
|
||||
dst.Del(xhttp.AmzServerSideEncryptionCopyCustomerAlgorithm)
|
||||
dst.Del(xhttp.AmzServerSideEncryptionCopyCustomerKey)
|
||||
dst.Del(xhttp.AmzServerSideEncryptionCopyCustomerKeyMD5)
|
||||
return dst
|
||||
}
|
||||
|
||||
// getRemoteInstanceTransport contains a roundtripper for external (not peers) servers
|
||||
@@ -1122,6 +1146,12 @@ func getRemoteInstanceTransport() http.RoundTripper {
|
||||
return nil
|
||||
}
|
||||
|
||||
// federatedInternalAppName is the minio-go application token that
|
||||
// getRemoteInstanceClient attaches to every legacy federation proxy request. It
|
||||
// is declared next to its only producer so that the literal keeps its historical
|
||||
// file attribution in the rebrand compatibility baseline.
|
||||
const federatedInternalAppName = "minio-federated"
|
||||
|
||||
// Returns a minio-go Client configured to access remote host described by destDNSRecord
|
||||
// Applicable only in a federated deployment
|
||||
var getRemoteInstanceClient = func(r *http.Request, host string) (*miniogo.Core, error) {
|
||||
@@ -1136,7 +1166,7 @@ var getRemoteInstanceClient = func(r *http.Request, host string) (*miniogo.Core,
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
core.SetAppInfo("minio-federated", ReleaseTag)
|
||||
core.SetAppInfo(federatedInternalAppName, ReleaseTag)
|
||||
return core, nil
|
||||
}
|
||||
|
||||
@@ -1165,6 +1195,31 @@ func isRemoteCallRequired(ctx context.Context, bucket string, objAPI ObjectLayer
|
||||
return false
|
||||
}
|
||||
|
||||
// copyRewritesObjectData reports whether the object layer stores new object data
|
||||
// for this copy instead of updating metadata in place or adding a
|
||||
// self-referential version. It mirrors the metadata-only decision taken by
|
||||
// erasureServerPools.CopyObject and erasureSets.CopyObject. CopyObjectHandler
|
||||
// has to predict that decision because the compression metadata it records must
|
||||
// describe whichever bytes are finally stored. metadataOnly already excludes
|
||||
// legacy sources, which the object layer always rewrites.
|
||||
func copyRewritesObjectData(metadataOnly bool, srcOpts, dstOpts ObjectOptions) bool {
|
||||
if !metadataOnly {
|
||||
return true
|
||||
}
|
||||
switch {
|
||||
case dstOpts.VersionID != "" && srcOpts.VersionID == dstOpts.VersionID:
|
||||
// In-place update of the addressed version.
|
||||
return false
|
||||
case !dstOpts.Versioned && srcOpts.VersionID == "":
|
||||
// In-place update of an unversioned object.
|
||||
return false
|
||||
case dstOpts.Versioned && srcOpts.VersionID != dstOpts.VersionID:
|
||||
// A new version referencing the existing data.
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// CopyObjectHandler - Copy Object
|
||||
// ----------
|
||||
// This implementation of the PUT operation adds an object to a bucket
|
||||
@@ -1253,28 +1308,30 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrInvalidStorageClass), r.URL)
|
||||
return
|
||||
}
|
||||
allowReplicationMetadata := false
|
||||
if r.Header.Get(xhttp.AmzBucketReplicationStatus) == replication.Replica.String() {
|
||||
if s3Error := checkRequestAuthType(ctx, r, policy.ReplicateObjectAction, dstBucket, dstObject); s3Error != ErrNone {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Error), r.URL)
|
||||
return
|
||||
}
|
||||
allowReplicationMetadata = true
|
||||
rawReplica := hasReplicaStatus(r.Header)
|
||||
markerExact := hasReplicationMarker(r.Header)
|
||||
replicationPermitted := false
|
||||
if rawReplica || markerExact {
|
||||
replicationPermitted = replicationPermissionAllowed(ctx, r, dstBucket, dstObject, policy.ReplicateObjectAction)
|
||||
}
|
||||
trustedReplicationRequest := allowReplicationMetadata && r.Header.Get(xhttp.MinIOSourceReplicationRequest) == "true"
|
||||
optsReq := r
|
||||
if !trustedReplicationRequest {
|
||||
optsReq = cloneRequestWithoutCopyReplicationHeaders(r)
|
||||
if rawReplica && !replicationPermitted {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrAccessDenied), r.URL)
|
||||
return
|
||||
}
|
||||
trustedReplication := markerExact && replicationPermitted
|
||||
replicaTrusted := trustedReplication && rawReplica
|
||||
if hasReplicationRequestHeaders(r.Header) {
|
||||
ctx, r = applyReplicationTrust(ctx, r, trustedReplication, replicaTrusted)
|
||||
}
|
||||
allowReplicationMetadata := replicaTrusted
|
||||
|
||||
// Check if bucket encryption is enabled
|
||||
sseConfig, _ := globalBucketSSEConfigSys.Get(dstBucket)
|
||||
sseConfig.Apply(r.Header, sse.ApplyOptions{
|
||||
AutoEncrypt: globalAutoEncryption,
|
||||
})
|
||||
|
||||
var srcOpts, dstOpts ObjectOptions
|
||||
srcOpts, err = copySrcOpts(ctx, optsReq, srcBucket, srcObject)
|
||||
srcOpts, err = copySrcOpts(ctx, r, srcBucket, srcObject)
|
||||
if err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
@@ -1286,14 +1343,14 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
VersionID: srcOpts.VersionID,
|
||||
Versioned: srcOpts.Versioned,
|
||||
VersionSuspended: srcOpts.VersionSuspended,
|
||||
ReplicationRequest: trustedReplicationRequest,
|
||||
ReplicationRequest: replicaTrusted,
|
||||
}
|
||||
getSSE := encrypt.SSE(srcOpts.ServerSideEncryption)
|
||||
if getSSE != srcOpts.ServerSideEncryption {
|
||||
getOpts.ServerSideEncryption = getSSE
|
||||
}
|
||||
|
||||
dstOpts, err = copyDstOpts(ctx, optsReq, dstBucket, dstObject, nil)
|
||||
dstOpts, err = copyDstOpts(ctx, r, dstBucket, dstObject, nil)
|
||||
if err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
@@ -1303,7 +1360,7 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
getObjectNInfo := objectAPI.GetObjectNInfo
|
||||
|
||||
checkCopyPrecondFn := func(o ObjectInfo) bool {
|
||||
if _, err := DecryptObjectInfo(&o, optsReq); err != nil {
|
||||
if _, err := DecryptObjectInfo(&o, r); err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return true
|
||||
}
|
||||
@@ -1357,6 +1414,15 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
} // no changes in storage-class expected so its a metadataonly operation.
|
||||
|
||||
var reader io.Reader = gr
|
||||
sourceCompressMetadata := make(map[string]string, 2)
|
||||
for _, key := range []string{
|
||||
ReservedMetadataPrefix + "compression",
|
||||
ReservedMetadataPrefix + "actual-size",
|
||||
} {
|
||||
if value, ok := srcInfo.UserDefined[key]; ok {
|
||||
sourceCompressMetadata[key] = value
|
||||
}
|
||||
}
|
||||
|
||||
// Set the actual size to the compressed/decrypted size if encrypted.
|
||||
actualSize, err := srcInfo.GetActualSize()
|
||||
@@ -1386,15 +1452,7 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
compressMetadata[ReservedMetadataPrefix+"actual-size"] = strconv.FormatInt(actualSize, 10)
|
||||
|
||||
reader = etag.NewReader(ctx, reader, nil, nil)
|
||||
wantEncryption := crypto.Requested(r.Header)
|
||||
s2c, cb := newS2CompressReader(reader, actualSize, wantEncryption)
|
||||
dstOpts.IndexCB = cb
|
||||
defer s2c.Close()
|
||||
reader = etag.Wrap(s2c, reader)
|
||||
length = -1
|
||||
} else {
|
||||
delete(srcInfo.UserDefined, ReservedMetadataPrefix+"compression")
|
||||
delete(srcInfo.UserDefined, ReservedMetadataPrefix+"actual-size")
|
||||
reader = gr
|
||||
}
|
||||
|
||||
@@ -1414,7 +1472,7 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
return
|
||||
}
|
||||
// Encryption parameters not present for this object.
|
||||
if crypto.SSEC.IsEncrypted(srcInfo.UserDefined) && !crypto.SSECopy.IsRequested(r.Header) && !trustedReplicationRequest {
|
||||
if crypto.SSEC.IsEncrypted(srcInfo.UserDefined) && !crypto.SSECopy.IsRequested(r.Header) && !replicaTrusted {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrInvalidSSECustomerAlgorithm), r.URL)
|
||||
return
|
||||
}
|
||||
@@ -1448,12 +1506,39 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
}
|
||||
}
|
||||
|
||||
// Name the source version explicitly so a metadata-only copy into a
|
||||
// versioned bucket adds a self-referential version instead of rewriting the
|
||||
// object data. A null source version cannot be referenced this way.
|
||||
copySrcOpts := srcOpts
|
||||
if dstOpts.Versioned && copySrcOpts.VersionID == "" {
|
||||
copySrcOpts.VersionID = srcInfo.VersionID
|
||||
}
|
||||
|
||||
// A key rotation rewraps the object key held in metadata; it never
|
||||
// re-encrypts the stored bytes. When the object layer stores new object
|
||||
// data instead, the rotation has to go through the regular re-encrypting
|
||||
// copy, or the destination ends up holding plaintext under metadata that
|
||||
// claims the object is encrypted.
|
||||
canRotateKeyInPlace := !srcInfo.Legacy &&
|
||||
!copyRewritesObjectData(srcInfo.metadataOnly, copySrcOpts, dstOpts)
|
||||
|
||||
// The rotation shortcut authenticates the source key by unsealing it. The
|
||||
// re-encrypting fallback authenticates it only through the source decryptor,
|
||||
// which GetObjectNInfo skips for a zero byte object, so check it here before
|
||||
// the destination is written under the new key.
|
||||
if cpSrcDstSame && sseCopyC && sseC && !chStorageClass && !canRotateKeyInPlace {
|
||||
if err := checkSSECCopySourceKey(r.Header, srcInfo.UserDefined, srcBucket, srcObject, newKey); err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// If src == dst and either
|
||||
// - the object is encrypted using SSE-C and two different SSE-C keys are present
|
||||
// - the object is encrypted using SSE-S3 and the SSE-S3 header is present
|
||||
// - the object storage class is not changing
|
||||
// then execute a key rotation.
|
||||
if cpSrcDstSame && (sseCopyC && sseC) && !chStorageClass {
|
||||
if cpSrcDstSame && (sseCopyC && sseC) && !chStorageClass && canRotateKeyInPlace {
|
||||
oldKey, err = ParseSSECopyCustomerRequest(r.Header, srcInfo.UserDefined)
|
||||
if err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
@@ -1541,6 +1626,23 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
}
|
||||
}
|
||||
|
||||
if isDstCompressed {
|
||||
checksumReader := srcInfo.Reader
|
||||
wantEncryption := crypto.Requested(r.Header)
|
||||
s2c, cb := newS2CompressReader(checksumReader, actualSize, wantEncryption)
|
||||
dstOpts.IndexCB = cb
|
||||
defer s2c.Close()
|
||||
reader = etag.Wrap(s2c, checksumReader)
|
||||
srcInfo.Reader, err = hash.NewReader(ctx, reader, -1, "", "", actualSize)
|
||||
if err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
// The storage reader consumes compressed data; checksums remain bound to plaintext.
|
||||
pReader = NewPutObjReader(srcInfo.Reader)
|
||||
pReader.setChecksumReader(checksumReader)
|
||||
}
|
||||
|
||||
if isTargetEncrypted {
|
||||
var encReader io.Reader
|
||||
kind, _ := crypto.IsRequested(r.Header)
|
||||
@@ -1621,7 +1723,7 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
getObjectInfo := objectAPI.GetObjectInfo
|
||||
|
||||
// apply default bucket configuration/governance headers for dest side.
|
||||
retentionMode, retentionDate, legalHold, s3Err := checkPutObjectLockAllowed(ctx, r, dstBucket, dstObject, getObjectInfo, retPerms, holdPerms)
|
||||
retentionMode, retentionDate, legalHold, s3Err := checkPutObjectLockAllowed(ctx, r, dstBucket, dstObject, getObjectInfo, retPerms, holdPerms, replicaTrusted)
|
||||
if s3Err == ErrNone && retentionMode.Valid() {
|
||||
lastretentionTimestamp := srcInfo.UserDefined[ReservedMetadataPrefixLower+ObjectLockRetentionTimestamp]
|
||||
if dstOpts.ReplicationRequest {
|
||||
@@ -1676,8 +1778,21 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
srcInfo.UserDefined[ReservedMetadataPrefixLower+ReplicationStatus] = dsc.PendingStatus()
|
||||
srcInfo.UserDefined[ReservedMetadataPrefixLower+ReplicationTimestamp] = UTCNow().Format(time.RFC3339Nano)
|
||||
}
|
||||
// Store the preserved compression metadata.
|
||||
maps.Copy(srcInfo.UserDefined, compressMetadata)
|
||||
// srcInfo.metadataOnly is still cleared below for legacy sources and for
|
||||
// server-side checksum recomputation; both of those rewrite the object data.
|
||||
metadataOnly := srcInfo.metadataOnly && !srcInfo.Legacy && !dstOpts.WantServerSideChecksumType.IsSet()
|
||||
|
||||
// Compression metadata must describe the bytes that are actually stored.
|
||||
if copyRewritesObjectData(metadataOnly, copySrcOpts, dstOpts) {
|
||||
if isDstCompressed {
|
||||
maps.Copy(srcInfo.UserDefined, compressMetadata)
|
||||
} else {
|
||||
delete(srcInfo.UserDefined, ReservedMetadataPrefix+"compression")
|
||||
delete(srcInfo.UserDefined, ReservedMetadataPrefix+"actual-size")
|
||||
}
|
||||
} else {
|
||||
maps.Copy(srcInfo.UserDefined, sourceCompressMetadata)
|
||||
}
|
||||
|
||||
// We need to preserve the encryption headers set in EncryptRequest,
|
||||
// so we do not want to override them, copy them instead.
|
||||
@@ -1769,7 +1884,7 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
|
||||
// Copy source object to destination, if source and destination
|
||||
// object is same then only metadata is updated.
|
||||
objInfo, err = copyObjectFn(ctx, srcBucket, srcObject, dstBucket, dstObject, srcInfo, srcOpts, dstOpts)
|
||||
objInfo, err = copyObjectFn(ctx, srcBucket, srcObject, dstBucket, dstObject, srcInfo, copySrcOpts, dstOpts)
|
||||
if err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
@@ -1778,14 +1893,16 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
|
||||
origETag := objInfo.ETag
|
||||
objInfo.ETag = getDecryptedETag(r.Header, objInfo, false)
|
||||
response := generateCopyObjectResponse(objInfo.ETag, objInfo.ModTime)
|
||||
dstHeaders := copyDestinationSSEHeaders(r.Header)
|
||||
checksums, _ := objInfo.decryptChecksums(0, dstHeaders)
|
||||
response := generateCopyObjectResponse(objInfo, checksums)
|
||||
encodedSuccessResponse := encodeResponse(response)
|
||||
|
||||
if dsc := mustReplicate(ctx, dstBucket, dstObject, objInfo.getMustReplicateOptions(replication.ObjectReplicationType, dstOpts)); dsc.ReplicateAny() {
|
||||
scheduleReplication(ctx, objInfo, objectAPI, dsc, replication.ObjectReplicationType)
|
||||
}
|
||||
|
||||
setPutObjHeaders(w, objInfo, false, r.Header)
|
||||
setPutObjHeadersWithChecksum(w, objInfo, false, checksums)
|
||||
// We must not use the http.Header().Set method here because some (broken)
|
||||
// clients expect the x-amz-copy-source-version-id header key to be literally
|
||||
// "x-amz-copy-source-version-id"- not in canonicalized form, preserve it.
|
||||
@@ -1956,6 +2073,16 @@ func (api objectAPIHandlers) PutObjectHandler(w http.ResponseWriter, r *http.Req
|
||||
}
|
||||
}
|
||||
|
||||
rawReplica := hasReplicaStatus(r.Header)
|
||||
markerExact := hasReplicationMarker(r.Header)
|
||||
replicationPermitted := false
|
||||
if rawReplica || markerExact {
|
||||
replicationPermitted = replicationPermissionAllowed(ctx, r, bucket, object, policy.ReplicateObjectAction)
|
||||
}
|
||||
if rawReplica && !replicationPermitted {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrAccessDenied), r.URL)
|
||||
return
|
||||
}
|
||||
if _, ok := r.Header[xhttp.MinIOSourceReplicationCheck]; ok {
|
||||
// requests to just validate replication settings and permissions are not allowed to write data
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrReplicationPermissionCheckError), r.URL)
|
||||
@@ -1966,18 +2093,22 @@ func (api objectAPIHandlers) PutObjectHandler(w http.ResponseWriter, r *http.Req
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
if r.Header.Get(xhttp.AmzBucketReplicationStatus) == replication.Replica.String() {
|
||||
if s3Err = isPutActionAllowed(ctx, getRequestAuthType(r), bucket, object, r, policy.ReplicateObjectAction); s3Err != ErrNone {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Err), r.URL)
|
||||
return
|
||||
}
|
||||
trustedReplication := markerExact && replicationPermitted
|
||||
replicaTrusted := trustedReplication && rawReplica
|
||||
if hasReplicationRequestHeaders(r.Header) {
|
||||
ctx, r = applyReplicationTrust(ctx, r, trustedReplication, replicaTrusted)
|
||||
}
|
||||
if replicaTrusted {
|
||||
if err = extractReplicationMetadataFromMime(ctx, textproto.MIMEHeader(r.Header), metadata); err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
metadata[xhttp.AmzBucketReplicationStatus] = replication.Replica.String()
|
||||
metadata[ReservedMetadataPrefixLower+ReplicaStatus] = replication.Replica.String()
|
||||
metadata[ReservedMetadataPrefixLower+ReplicaTimestamp] = UTCNow().Format(time.RFC3339Nano)
|
||||
defer globalReplicationStats.Load().UpdateReplicaStat(bucket, size)
|
||||
} else {
|
||||
delete(metadata, xhttp.AmzBucketReplicationStatus)
|
||||
}
|
||||
|
||||
// Check if bucket encryption is enabled
|
||||
@@ -2076,7 +2207,7 @@ func (api objectAPIHandlers) PutObjectHandler(w http.ResponseWriter, r *http.Req
|
||||
|
||||
getObjectInfo := objectAPI.GetObjectInfo
|
||||
|
||||
retentionMode, retentionDate, legalHold, s3Err := checkPutObjectLockAllowed(ctx, r, bucket, object, getObjectInfo, retPerms, holdPerms)
|
||||
retentionMode, retentionDate, legalHold, s3Err := checkPutObjectLockAllowed(ctx, r, bucket, object, getObjectInfo, retPerms, holdPerms, isReplicaTrusted(ctx))
|
||||
if s3Err == ErrNone && retentionMode.Valid() {
|
||||
metadata[strings.ToLower(xhttp.AmzObjectLockMode)] = string(retentionMode)
|
||||
metadata[strings.ToLower(xhttp.AmzObjectLockRetainUntilDate)] = amztime.ISO8601Format(retentionDate.UTC())
|
||||
@@ -2360,7 +2491,6 @@ func (api objectAPIHandlers) PutObjectExtractHandler(w http.ResponseWriter, r *h
|
||||
sha256hex = getContentSha256Cksum(r, serviceS3)
|
||||
}
|
||||
}
|
||||
|
||||
hreader, err := hash.NewReader(ctx, reader, size, md5hex, sha256hex, size)
|
||||
if err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
@@ -2381,14 +2511,26 @@ func (api objectAPIHandlers) PutObjectExtractHandler(w http.ResponseWriter, r *h
|
||||
sseConfig.Apply(r.Header, sse.ApplyOptions{
|
||||
AutoEncrypt: globalAutoEncryption,
|
||||
})
|
||||
entryRequestBase := r.Clone(ctx)
|
||||
// The streaming reader fills r.Trailer while untar writes small entries in
|
||||
// parallel. Entry authorization never consumes trailers, so keep them out
|
||||
// of the immutable request template cloned by those goroutines. Snapshot
|
||||
// after applying bucket defaults so extracted objects retain encryption.
|
||||
entryRequestBase.Trailer = nil
|
||||
rawReplica := hasReplicaStatus(r.Header)
|
||||
markerExact := hasReplicationMarker(r.Header)
|
||||
trustedRequestCtx := withReplicationTrust(ctx, true, rawReplica)
|
||||
trustedRequest := entryRequestBase.WithContext(trustedRequestCtx)
|
||||
cleanRequestCtx := withReplicationTrust(ctx, false, false)
|
||||
cleanRequest := cloneRequestWithoutReplicationHeaders(cleanRequestCtx, entryRequestBase)
|
||||
trustedReqParams := extractReqParams(trustedRequest)
|
||||
cleanReqParams := extractReqParams(cleanRequest)
|
||||
|
||||
retPerms := isPutActionAllowed(ctx, getRequestAuthType(r), bucket, object, r, policy.PutObjectRetentionAction)
|
||||
holdPerms := isPutActionAllowed(ctx, getRequestAuthType(r), bucket, object, r, policy.PutObjectLegalHoldAction)
|
||||
|
||||
getObjectInfo := objectAPI.GetObjectInfo
|
||||
|
||||
// These are static for all objects extracted.
|
||||
reqParams := extractReqParams(r)
|
||||
respElements := map[string]string{
|
||||
"requestId": w.Header().Get(xhttp.AmzRequestID),
|
||||
"nodeId": w.Header().Get(xhttp.AmzRequestHostID),
|
||||
@@ -2396,12 +2538,46 @@ func (api objectAPIHandlers) PutObjectExtractHandler(w http.ResponseWriter, r *h
|
||||
if sc == "" {
|
||||
sc = storageclass.STANDARD
|
||||
}
|
||||
reqInfo := logger.GetReqInfo(ctx)
|
||||
if reqInfo == nil {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrAccessDenied), r.URL)
|
||||
return
|
||||
}
|
||||
reqInfo.RLock()
|
||||
tarCred := reqInfo.Cred
|
||||
tarOwner := reqInfo.Owner
|
||||
reqInfo.RUnlock()
|
||||
var tarS3Err atomic.Int32
|
||||
setTarS3Err := func(code APIErrorCode) {
|
||||
tarS3Err.CompareAndSwap(int32(ErrNone), int32(code))
|
||||
}
|
||||
ignoreEntryErrors := opts.ignoreErrs
|
||||
|
||||
putObjectTar := func(reader io.Reader, info os.FileInfo, object string) error {
|
||||
size := info.Size()
|
||||
if s3Err = isPutActionAllowed(ctx, getRequestAuthType(r), bucket, object, r, policy.PutObjectAction); s3Err != ErrNone {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Err), r.URL)
|
||||
return errors.New(errorCodes.ToAPIErr(s3Err).Code)
|
||||
entryAuthReq := entryRequestBase.Clone(ctx)
|
||||
entryS3Err := isPutActionAllowedWithCred(bucket, object, entryAuthReq, policy.PutObjectAction, nil, tarCred, tarOwner)
|
||||
if entryS3Err != ErrNone {
|
||||
setTarS3Err(entryS3Err)
|
||||
return errors.New(errorCodes.ToAPIErr(entryS3Err).Code)
|
||||
}
|
||||
replicationPermitted := false
|
||||
if tarCred.AccessKey != "" && (rawReplica || markerExact) {
|
||||
replicationPermitted = isPutActionAllowedWithCred(bucket, object, entryAuthReq, policy.ReplicateObjectAction, nil, tarCred, tarOwner) == ErrNone
|
||||
}
|
||||
if rawReplica && !replicationPermitted {
|
||||
setTarS3Err(ErrAccessDenied)
|
||||
return errors.New(errorCodes.ToAPIErr(ErrAccessDenied).Code)
|
||||
}
|
||||
entryTrusted := markerExact && replicationPermitted
|
||||
replicaTrusted := entryTrusted && rawReplica
|
||||
entryCtx := cleanRequestCtx
|
||||
entryReq := cloneRequestWithoutReplicationHeaders(cleanRequestCtx, entryAuthReq)
|
||||
reqParams := cleanReqParams
|
||||
if entryTrusted {
|
||||
entryCtx = trustedRequestCtx
|
||||
entryReq = entryAuthReq.WithContext(trustedRequestCtx)
|
||||
reqParams = trustedReqParams
|
||||
}
|
||||
metadata := map[string]string{
|
||||
xhttp.AmzStorageClass: sc, // save same storage-class as incoming stream.
|
||||
@@ -2409,7 +2585,7 @@ func (api objectAPIHandlers) PutObjectExtractHandler(w http.ResponseWriter, r *h
|
||||
|
||||
actualSize := size
|
||||
var idxCb func() []byte
|
||||
if isCompressible(r.Header, object) && size > minCompressibleSize {
|
||||
if isCompressible(entryReq.Header, object) && size > minCompressibleSize {
|
||||
// Storing the compression metadata.
|
||||
metadata[ReservedMetadataPrefix+"compression"] = compressionAlgorithmV2
|
||||
metadata[ReservedMetadataPrefix+"actual-size"] = strconv.FormatInt(size, 10)
|
||||
@@ -2420,7 +2596,7 @@ func (api objectAPIHandlers) PutObjectExtractHandler(w http.ResponseWriter, r *h
|
||||
}
|
||||
|
||||
// Set compression metrics.
|
||||
wantEncryption := crypto.Requested(r.Header)
|
||||
wantEncryption := crypto.Requested(entryReq.Header)
|
||||
s2c, cb := newS2CompressReader(actualReader, actualSize, wantEncryption)
|
||||
defer s2c.Close()
|
||||
idxCb = cb
|
||||
@@ -2436,15 +2612,11 @@ func (api objectAPIHandlers) PutObjectExtractHandler(w http.ResponseWriter, r *h
|
||||
rawReader := hashReader
|
||||
pReader := NewPutObjReader(rawReader)
|
||||
|
||||
allowReplicationMetadata := false
|
||||
if r.Header.Get(xhttp.AmzBucketReplicationStatus) == replication.Replica.String() {
|
||||
if s3Err = isPutActionAllowed(ctx, getRequestAuthType(r), bucket, object, r, policy.ReplicateObjectAction); s3Err != ErrNone {
|
||||
return errors.New(errorCodes.ToAPIErr(s3Err).Code)
|
||||
}
|
||||
allowReplicationMetadata = true
|
||||
if err = extractReplicationMetadataFromMime(ctx, textproto.MIMEHeader(r.Header), metadata); err != nil {
|
||||
if replicaTrusted {
|
||||
if err := extractReplicationMetadataFromMime(entryCtx, textproto.MIMEHeader(entryReq.Header), metadata); err != nil {
|
||||
return err
|
||||
}
|
||||
metadata[xhttp.AmzBucketReplicationStatus] = replication.Replica.String()
|
||||
metadata[ReservedMetadataPrefixLower+ReplicaStatus] = replication.Replica.String()
|
||||
metadata[ReservedMetadataPrefixLower+ReplicaTimestamp] = UTCNow().Format(time.RFC3339Nano)
|
||||
}
|
||||
@@ -2466,22 +2638,25 @@ func (api objectAPIHandlers) PutObjectExtractHandler(w http.ResponseWriter, r *h
|
||||
hdrs.Set(k, v)
|
||||
}
|
||||
}
|
||||
m, err := extractMetadata(ctx, textproto.MIMEHeader(hdrs))
|
||||
if !entryTrusted {
|
||||
stripReplicationRequestHeaders(hdrs)
|
||||
}
|
||||
m, err := extractMetadata(entryCtx, textproto.MIMEHeader(hdrs))
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if allowReplicationMetadata {
|
||||
if err = extractReplicationMetadataFromMime(ctx, textproto.MIMEHeader(hdrs), m); err != nil {
|
||||
if replicaTrusted {
|
||||
if err = extractReplicationMetadataFromMime(entryCtx, textproto.MIMEHeader(hdrs), m); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
maps.Copy(metadata, m)
|
||||
} else {
|
||||
versionID = r.Form.Get(xhttp.VersionID)
|
||||
hdrs = r.Header
|
||||
versionID = entryReq.Form.Get(xhttp.VersionID)
|
||||
hdrs = entryReq.Header
|
||||
}
|
||||
|
||||
opts, err := putOpts(ctx, bucket, object, versionID, hdrs, metadata)
|
||||
opts, err := putOpts(entryCtx, bucket, object, versionID, hdrs, metadata, entryTrusted)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -2492,7 +2667,7 @@ func (api objectAPIHandlers) PutObjectExtractHandler(w http.ResponseWriter, r *h
|
||||
}
|
||||
opts.IndexCB = idxCb
|
||||
|
||||
retentionMode, retentionDate, legalHold, s3err := checkPutObjectLockAllowed(ctx, r, bucket, object, getObjectInfo, retPerms, holdPerms)
|
||||
retentionMode, retentionDate, legalHold, s3err := checkPutObjectLockAllowed(entryCtx, entryReq, bucket, object, getObjectInfo, retPerms, holdPerms, replicaTrusted)
|
||||
if s3err == ErrNone && retentionMode.Valid() {
|
||||
metadata[strings.ToLower(xhttp.AmzObjectLockMode)] = string(retentionMode)
|
||||
metadata[strings.ToLower(xhttp.AmzObjectLockRetainUntilDate)] = amztime.ISO8601Format(retentionDate.UTC())
|
||||
@@ -2503,7 +2678,9 @@ func (api objectAPIHandlers) PutObjectExtractHandler(w http.ResponseWriter, r *h
|
||||
}
|
||||
|
||||
if s3err != ErrNone {
|
||||
s3Err = s3err
|
||||
if !ignoreEntryErrors {
|
||||
setTarS3Err(s3err)
|
||||
}
|
||||
return ObjectLocked{}
|
||||
}
|
||||
|
||||
@@ -2513,12 +2690,12 @@ func (api objectAPIHandlers) PutObjectExtractHandler(w http.ResponseWriter, r *h
|
||||
}
|
||||
|
||||
var objectEncryptionKey crypto.ObjectKey
|
||||
if crypto.Requested(r.Header) {
|
||||
if crypto.SSECopy.IsRequested(r.Header) {
|
||||
if crypto.Requested(entryReq.Header) {
|
||||
if crypto.SSECopy.IsRequested(entryReq.Header) {
|
||||
return errInvalidEncryptionParameters
|
||||
}
|
||||
|
||||
reader, objectEncryptionKey, err = EncryptRequest(hashReader, r, bucket, object, metadata)
|
||||
reader, objectEncryptionKey, err = EncryptRequest(hashReader, entryReq, bucket, object, metadata)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
@@ -2563,7 +2740,7 @@ func (api objectAPIHandlers) PutObjectExtractHandler(w http.ResponseWriter, r *h
|
||||
}
|
||||
|
||||
origETag := objInfo.ETag
|
||||
objInfo.ETag = getDecryptedETag(r.Header, objInfo, false)
|
||||
objInfo.ETag = getDecryptedETag(entryReq.Header, objInfo, false)
|
||||
|
||||
if dsc := mustReplicate(ctx, bucket, object, getMustReplicateOptions(metadata, "", "", replication.ObjectReplicationType, opts)); dsc.ReplicateAny() {
|
||||
scheduleReplication(ctx, objInfo, objectAPI, dsc, replication.ObjectReplicationType)
|
||||
@@ -2576,8 +2753,8 @@ func (api objectAPIHandlers) PutObjectExtractHandler(w http.ResponseWriter, r *h
|
||||
Object: objInfo,
|
||||
ReqParams: reqParams,
|
||||
RespElements: respElements,
|
||||
UserAgent: r.UserAgent(),
|
||||
Host: handlers.GetSourceIP(r),
|
||||
UserAgent: entryReq.UserAgent(),
|
||||
Host: handlers.GetSourceIP(entryReq),
|
||||
}
|
||||
sendEvent(evt)
|
||||
|
||||
@@ -2592,7 +2769,14 @@ func (api objectAPIHandlers) PutObjectExtractHandler(w http.ResponseWriter, r *h
|
||||
return nil
|
||||
}
|
||||
|
||||
if err = untar(ctx, hreader, putObjectTar, opts); err != nil {
|
||||
err = untar(ctx, hreader, putObjectTar, opts)
|
||||
if code := APIErrorCode(tarS3Err.Load()); code != ErrNone {
|
||||
s3Err = code
|
||||
if err == nil {
|
||||
err = errors.New(errorCodes.ToAPIErr(code).Code)
|
||||
}
|
||||
}
|
||||
if err != nil {
|
||||
apiErr := errorCodes.ToAPIErr(s3Err)
|
||||
// If not set, convert or use BadRequest
|
||||
if s3Err == ErrNone {
|
||||
@@ -2637,7 +2821,35 @@ func (api objectAPIHandlers) DeleteObjectHandler(w http.ResponseWriter, r *http.
|
||||
return
|
||||
}
|
||||
|
||||
if s3Error := checkRequestAuthType(ctx, r, policy.DeleteObjectAction, bucket, object); s3Error != ErrNone {
|
||||
reqInfo := logger.GetReqInfo(ctx)
|
||||
if reqInfo == nil {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrAccessDenied), r.URL)
|
||||
return
|
||||
}
|
||||
reqInfo.BucketName = bucket
|
||||
reqInfo.ObjectName = object
|
||||
if s3Error := authenticateRequest(ctx, r, policy.DeleteObjectAction); s3Error != ErrNone {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Error), r.URL)
|
||||
return
|
||||
}
|
||||
rawReplica := hasReplicaStatus(r.Header)
|
||||
markerExact := hasReplicationMarker(r.Header)
|
||||
replicationPermitted := false
|
||||
if rawReplica || markerExact {
|
||||
replicationPermitted = replicationPermissionAllowed(ctx, r, bucket, object, policy.ReplicateDeleteAction)
|
||||
}
|
||||
if rawReplica && !replicationPermitted {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrAccessDenied), r.URL)
|
||||
return
|
||||
}
|
||||
trustedReplication := markerExact && replicationPermitted
|
||||
var s3Error APIErrorCode
|
||||
if trustedReplication {
|
||||
s3Error = authorizeReplicationDelete(ctx, r)
|
||||
} else {
|
||||
s3Error = authorizeRequest(ctx, r, deleteObjectAction(reqInfo.VersionID))
|
||||
}
|
||||
if s3Error != ErrNone {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Error), r.URL)
|
||||
return
|
||||
}
|
||||
@@ -2646,13 +2858,9 @@ func (api objectAPIHandlers) DeleteObjectHandler(w http.ResponseWriter, r *http.
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrReplicationPermissionCheckError), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
replica := r.Header.Get(xhttp.AmzBucketReplicationStatus) == replication.Replica.String()
|
||||
if replica {
|
||||
if s3Error := checkRequestAuthType(ctx, r, policy.ReplicateDeleteAction, bucket, object); s3Error != ErrNone {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Error), r.URL)
|
||||
return
|
||||
}
|
||||
replica := trustedReplication && rawReplica
|
||||
if hasReplicationRequestHeaders(r.Header) {
|
||||
ctx, r = applyReplicationTrust(ctx, r, trustedReplication, replica)
|
||||
}
|
||||
|
||||
if globalDNSConfig != nil {
|
||||
|
||||
@@ -43,6 +43,7 @@ import (
|
||||
"github.com/dustin/go-humanize"
|
||||
"github.com/minio/minio/internal/auth"
|
||||
"github.com/minio/minio/internal/crypto"
|
||||
minhash "github.com/minio/minio/internal/hash"
|
||||
"github.com/minio/minio/internal/hash/sha256"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
ioutilx "github.com/minio/minio/internal/ioutil"
|
||||
@@ -3386,6 +3387,62 @@ func testAPICompleteMultipartHandler(obj ObjectLayer, instanceType, bucketName s
|
||||
ExecObjectLayerAPINilTest(t, nilBucket, nilObject, instanceType, apiRouter, nilReq)
|
||||
}
|
||||
|
||||
// TestGenerateCompleteMultipartUploadResponseChecksumType verifies that
|
||||
// ChecksumType is populated as FULL_OBJECT/COMPOSITE when the object carries
|
||||
// a checksum, and omitted from the XML entirely when it doesn't.
|
||||
func TestGenerateCompleteMultipartUploadResponseChecksumType(t *testing.T) {
|
||||
bucket, key := "test-bucket", "test-object"
|
||||
|
||||
testCases := []struct {
|
||||
name string
|
||||
checksum *minhash.Checksum
|
||||
wantChecksumType string
|
||||
}{
|
||||
{
|
||||
name: "no checksum",
|
||||
checksum: nil,
|
||||
wantChecksumType: "",
|
||||
},
|
||||
{
|
||||
name: "full object checksum",
|
||||
checksum: minhash.NewChecksumFromData(minhash.ChecksumCRC32, []byte("full-object-data")),
|
||||
wantChecksumType: xhttp.AmzChecksumTypeFullObject,
|
||||
},
|
||||
{
|
||||
name: "composite multipart checksum",
|
||||
checksum: func() *minhash.Checksum {
|
||||
c := minhash.NewChecksumFromData(minhash.ChecksumCRC32C|minhash.ChecksumMultipart, []byte("combined-part-checksums"))
|
||||
c.WantParts = 2
|
||||
return c
|
||||
}(),
|
||||
wantChecksumType: xhttp.AmzChecksumTypeComposite,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range testCases {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
oi := ObjectInfo{ETag: "d41d8cd98f00b204e9800998ecf8427e"}
|
||||
if tt.checksum != nil {
|
||||
oi.Checksum = tt.checksum.AppendTo(nil, nil)
|
||||
}
|
||||
|
||||
resp := generateCompleteMultipartUploadResponse(bucket, key, getGetObjectURL("", bucket, key), oi, nil)
|
||||
if resp.ChecksumType != tt.wantChecksumType {
|
||||
t.Fatalf("ChecksumType: got %q, want %q", resp.ChecksumType, tt.wantChecksumType)
|
||||
}
|
||||
|
||||
encoded, err := xml.Marshal(resp)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to marshal response: %v", err)
|
||||
}
|
||||
gotTag := strings.Contains(string(encoded), "<ChecksumType>")
|
||||
if wantTag := tt.wantChecksumType != ""; gotTag != wantTag {
|
||||
t.Fatalf("ChecksumType tag presence: got %v, want %v (xml: %s)", gotTag, wantTag, encoded)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The UploadID from the response body is parsed and its existence is asserted with an attempt to ListParts using it.
|
||||
func TestAPIAbortMultipartHandler(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
|
||||
@@ -0,0 +1,367 @@
|
||||
// Copyright (c) 2015-2025 MinIO, Inc.
|
||||
// Copyright (c) 2025-2026 PGSTY
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
|
||||
miniogo "github.com/minio/minio-go/v7"
|
||||
miniocredentials "github.com/minio/minio-go/v7/pkg/credentials"
|
||||
"github.com/minio/minio-go/v7/pkg/set"
|
||||
"github.com/minio/minio/internal/auth"
|
||||
"github.com/minio/minio/internal/config/dns"
|
||||
"github.com/minio/minio/internal/hash"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
)
|
||||
|
||||
const federatedTestUserAgent = "MinIO (linux; amd64) minio-go/v7.3.1 minio-federated/RELEASE.TEST"
|
||||
|
||||
func TestAPIFederatedUploadPartChecksumResponse(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPIFederatedUploadPartChecksumResponse,
|
||||
endpoints: []string{"PutObjectPart", "NewMultipart"},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPIFederatedUploadPartChecksumResponse(_ ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
algorithms := []struct {
|
||||
name string
|
||||
typ hash.ChecksumType
|
||||
checksumType string
|
||||
}{
|
||||
{name: "crc32-full-object", typ: hash.ChecksumCRC32, checksumType: xhttp.AmzChecksumTypeFullObject},
|
||||
{name: "sha256-composite", typ: hash.ChecksumSHA256, checksumType: xhttp.AmzChecksumTypeComposite},
|
||||
}
|
||||
userAgents := []struct {
|
||||
name string
|
||||
ua string
|
||||
want bool
|
||||
}{
|
||||
{name: "absent"},
|
||||
{name: "ordinary-sdk", ua: "aws-sdk-go/1.55.5"},
|
||||
{name: "federation", ua: federatedTestUserAgent, want: true},
|
||||
{name: "lookalike-prefix", ua: "evil-minio-federated/RELEASE.TEST"},
|
||||
{name: "lookalike-suffix", ua: "minio-federated-extra/RELEASE.TEST"},
|
||||
{name: "missing-version", ua: "minio-federated"},
|
||||
{name: "empty-version", ua: "minio-federated/"},
|
||||
}
|
||||
data := []byte("federated upload part checksum response")
|
||||
|
||||
for _, algorithm := range algorithms {
|
||||
for _, userAgent := range userAgents {
|
||||
t.Run(algorithm.name+"/"+userAgent.name, func(t *testing.T) {
|
||||
object := "federation/response/" + algorithm.name + "/" + userAgent.name
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, bucketName, object,
|
||||
algorithm.typ.String(), algorithm.checksumType)
|
||||
headers := map[string]string{}
|
||||
if userAgent.ua != "" {
|
||||
headers["User-Agent"] = userAgent.ua
|
||||
}
|
||||
_, rec := uploadPartHTTP(t, apiRouter, credentials,
|
||||
bucketName, object, uploadID, 1, data, headers)
|
||||
|
||||
got := rec.Header().Get(algorithm.typ.Key())
|
||||
if userAgent.want {
|
||||
if want := mustChecksum(t, algorithm.typ, data); got != want {
|
||||
t.Fatalf("%s: checksum %q, want %q", instanceType, got, want)
|
||||
}
|
||||
} else if got != "" {
|
||||
t.Fatalf("%s: ordinary UploadPart exposed server checksum %q", instanceType, got)
|
||||
}
|
||||
if got := rec.Header().Get(xhttp.AmzChecksumType); got != "" {
|
||||
t.Fatalf("%s: UploadPart returned checksum type %q", instanceType, got)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIFederatedUploadPartChecksumMinIOGoWire(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPIFederatedUploadPartChecksumMinIOGoWire,
|
||||
endpoints: []string{"PutObjectPart", "NewMultipart"},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPIFederatedUploadPartChecksumMinIOGoWire(_ ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
server := httptest.NewServer(apiRouter)
|
||||
defer server.Close()
|
||||
|
||||
core, err := miniogo.NewCore(server.Listener.Addr().String(), &miniogo.Options{
|
||||
Creds: miniocredentials.NewStaticV4(credentials.AccessKey, credentials.SecretKey, ""),
|
||||
Secure: false,
|
||||
Region: globalMinioDefaultRegion,
|
||||
BucketLookup: miniogo.BucketLookupPath,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("%s: create minio-go Core: %v", instanceType, err)
|
||||
}
|
||||
core.SetAppInfo("minio-federated", ReleaseTag)
|
||||
|
||||
object := "federation/minio-go-wire"
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, bucketName, object,
|
||||
hash.ChecksumCRC32.String(), xhttp.AmzChecksumTypeFullObject)
|
||||
data := []byte("minio-go must parse the remote computed checksum")
|
||||
part, err := core.PutObjectPart(t.Context(), bucketName, object, uploadID, 1,
|
||||
bytes.NewReader(data), int64(len(data)), miniogo.PutObjectPartOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("%s: minio-go PutObjectPart: %v", instanceType, err)
|
||||
}
|
||||
if want := mustChecksum(t, hash.ChecksumCRC32, data); part.ChecksumCRC32 != want {
|
||||
t.Fatalf("%s: minio-go checksum %q, want %q", instanceType, part.ChecksumCRC32, want)
|
||||
}
|
||||
if part.ETag == "" {
|
||||
t.Fatalf("%s: minio-go returned an empty ETag", instanceType)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIFederatedUploadPartChecksumConcurrentOverwrite(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPIFederatedUploadPartChecksumConcurrentOverwrite,
|
||||
endpoints: []string{"PutObjectPart", "NewMultipart"},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPIFederatedUploadPartChecksumConcurrentOverwrite(_ ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
object := "federation/concurrent-overwrite"
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, bucketName, object,
|
||||
hash.ChecksumSHA256.String(), xhttp.AmzChecksumTypeComposite)
|
||||
data := [][]byte{
|
||||
bytes.Repeat([]byte("first-writer-"), 4096),
|
||||
bytes.Repeat([]byte("second-writer-"), 4096),
|
||||
}
|
||||
reqs := make([]*http.Request, len(data))
|
||||
recorders := make([]*httptest.ResponseRecorder, len(data))
|
||||
for i := range data {
|
||||
req, err := newTestSignedRequestV4(http.MethodPut,
|
||||
getPutObjectPartURL("", bucketName, object, uploadID, "1"),
|
||||
int64(len(data[i])), bytes.NewReader(data[i]), credentials.AccessKey, credentials.SecretKey,
|
||||
map[string]string{"User-Agent": federatedTestUserAgent})
|
||||
if err != nil {
|
||||
t.Fatalf("%s: build concurrent request %d: %v", instanceType, i, err)
|
||||
}
|
||||
reqs[i] = req
|
||||
recorders[i] = httptest.NewRecorder()
|
||||
}
|
||||
|
||||
start := make(chan struct{})
|
||||
var wg sync.WaitGroup
|
||||
for i := range reqs {
|
||||
wg.Add(1)
|
||||
go func() {
|
||||
defer wg.Done()
|
||||
<-start
|
||||
apiRouter.ServeHTTP(recorders[i], reqs[i])
|
||||
}()
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
|
||||
for i, rec := range recorders {
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: concurrent request %d failed: %d %s", instanceType, i, rec.Code, rec.Body.String())
|
||||
}
|
||||
got := rec.Header().Get(hash.ChecksumSHA256.Key())
|
||||
if want := mustChecksum(t, hash.ChecksumSHA256, data[i]); got != want {
|
||||
t.Fatalf("%s: concurrent request %d checksum %q, want %q", instanceType, i, got, want)
|
||||
}
|
||||
// The ETag and the checksum must describe the same write, so a losing
|
||||
// writer can never publish the winner's checksum next to its own ETag.
|
||||
etags := rec.Header()[xhttp.ETag]
|
||||
if len(etags) != 1 {
|
||||
t.Fatalf("%s: concurrent request %d returned %d ETags", instanceType, i, len(etags))
|
||||
}
|
||||
md5sum := md5.Sum(data[i])
|
||||
if want := hex.EncodeToString(md5sum[:]); canonicalizeETag(etags[0]) != want {
|
||||
t.Fatalf("%s: concurrent request %d ETag %q, want %q", instanceType, i, etags[0], want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// federationTestDNS is a minimal dns.Store so a single test process can play
|
||||
// both federation roles.
|
||||
type federationTestDNS struct {
|
||||
records map[string][]dns.SrvRecord
|
||||
}
|
||||
|
||||
func (f federationTestDNS) Put(string) error { return nil }
|
||||
|
||||
func (f federationTestDNS) Get(bucket string) ([]dns.SrvRecord, error) {
|
||||
records, ok := f.records[bucket]
|
||||
if !ok {
|
||||
return nil, dns.ErrNoEntriesFound
|
||||
}
|
||||
return records, nil
|
||||
}
|
||||
|
||||
func (f federationTestDNS) Delete(string) error { return nil }
|
||||
func (f federationTestDNS) List() (map[string][]dns.SrvRecord, error) { return f.records, nil }
|
||||
func (f federationTestDNS) DeleteRecord(dns.SrvRecord) error { return nil }
|
||||
func (f federationTestDNS) Close() error { return nil }
|
||||
func (f federationTestDNS) String() string { return "federation-test-dns" }
|
||||
|
||||
// remoteBucketObjectLayer reports one existing bucket as missing so that
|
||||
// isRemoteCopyRequired takes the legacy federation branch while the same
|
||||
// process can still serve that bucket as the remote deployment.
|
||||
type remoteBucketObjectLayer struct {
|
||||
ObjectLayer
|
||||
remoteBucket string
|
||||
}
|
||||
|
||||
func (l remoteBucketObjectLayer) GetBucketInfo(ctx context.Context, bucket string, opts BucketOptions) (BucketInfo, error) {
|
||||
if bucket == l.remoteBucket {
|
||||
return BucketInfo{}, toObjectErr(errVolumeNotFound, bucket)
|
||||
}
|
||||
return l.ObjectLayer.GetBucketInfo(ctx, bucket, opts)
|
||||
}
|
||||
|
||||
// TestAPIFederatedCopyObjectPartChecksum drives the legacy etcd federation
|
||||
// branch of CopyObjectPartHandler end to end: the proxy forwards the copied
|
||||
// bytes through the real getRemoteInstanceClient and minio-go, a second HTTP
|
||||
// endpoint serves the real PutObjectPartHandler, and CopyPartResult must carry
|
||||
// the checksum computed by that exact remote write.
|
||||
func TestAPIFederatedCopyObjectPartChecksum(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPIFederatedCopyObjectPartChecksum,
|
||||
endpoints: []string{
|
||||
"CopyObjectPart", "NewMultipart", "PutObjectPart",
|
||||
"ListObjectParts", "CompleteMultipart", "PutObject",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPIFederatedCopyObjectPartChecksum(objectAPI ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
algorithms := []struct {
|
||||
name string
|
||||
typ hash.ChecksumType
|
||||
checksumType string
|
||||
}{
|
||||
{name: "crc32-full-object", typ: hash.ChecksumCRC32, checksumType: xhttp.AmzChecksumTypeFullObject},
|
||||
{name: "sha256-composite", typ: hash.ChecksumSHA256, checksumType: xhttp.AmzChecksumTypeComposite},
|
||||
}
|
||||
|
||||
data := bytes.Repeat([]byte("federated-upload-part-copy-"), 1024)
|
||||
srcObject := "federation/copy-source.bin"
|
||||
putCopyChecksumSource(t, apiRouter, credentials, bucketName, srcObject, data, nil)
|
||||
|
||||
// The destination bucket really exists so the remote endpoint can serve it;
|
||||
// only the proxy's own bucket lookup is told that it lives elsewhere.
|
||||
remoteBucket := getRandomBucketName()
|
||||
if err := objectAPI.MakeBucket(t.Context(), remoteBucket, MakeBucketOptions{}); err != nil {
|
||||
t.Fatalf("%s: unable to create the remote bucket: %v", instanceType, err)
|
||||
}
|
||||
|
||||
remote := httptest.NewServer(apiRouter)
|
||||
defer remote.Close()
|
||||
host, port, _ := strings.Cut(remote.Listener.Addr().String(), ":")
|
||||
|
||||
globalObjLayerMutex.Lock()
|
||||
previousLayer := globalObjectAPI
|
||||
globalObjectAPI = remoteBucketObjectLayer{ObjectLayer: previousLayer, remoteBucket: remoteBucket}
|
||||
globalObjLayerMutex.Unlock()
|
||||
previousDNS, previousFederation, previousIPs := globalDNSConfig, globalBucketFederation, globalDomainIPs
|
||||
globalDNSConfig = federationTestDNS{records: map[string][]dns.SrvRecord{
|
||||
bucketName: {{Host: host, Port: json.Number(port)}},
|
||||
remoteBucket: {{Host: host, Port: json.Number(port)}},
|
||||
}}
|
||||
// Every DNS record resolves to this process, so the bucket forwarding
|
||||
// middleware always serves locally and only the handler proxies.
|
||||
globalDomainIPs = set.CreateStringSet(remote.Listener.Addr().String())
|
||||
globalBucketFederation = true
|
||||
defer func() {
|
||||
globalObjLayerMutex.Lock()
|
||||
globalObjectAPI = previousLayer
|
||||
globalObjLayerMutex.Unlock()
|
||||
globalDNSConfig, globalBucketFederation, globalDomainIPs = previousDNS, previousFederation, previousIPs
|
||||
}()
|
||||
|
||||
for _, algorithm := range algorithms {
|
||||
t.Run(algorithm.name, func(t *testing.T) {
|
||||
object := "federation/copy-destination-" + algorithm.name + ".bin"
|
||||
uploadID := newMultipartUploadHTTP(t, apiRouter, credentials, remoteBucket, object,
|
||||
algorithm.typ.String(), algorithm.checksumType)
|
||||
|
||||
req, err := newTestSignedRequestV4(http.MethodPut,
|
||||
getCopyObjectPartURL("", remoteBucket, object, uploadID, "1"),
|
||||
0, nil, credentials.AccessKey, credentials.SecretKey,
|
||||
map[string]string{xhttp.AmzCopySource: SlashSeparator + pathJoin(bucketName, srcObject)})
|
||||
if err != nil {
|
||||
t.Fatalf("%s: unable to build UploadPartCopy request: %v", instanceType, err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: federated UploadPartCopy failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
var response CopyObjectPartResponse
|
||||
if err := xml.Unmarshal(rec.Body.Bytes(), &response); err != nil {
|
||||
t.Fatalf("%s: unable to decode CopyPartResult: %v", instanceType, err)
|
||||
}
|
||||
want := mustChecksum(t, algorithm.typ, data)
|
||||
if got := copyPartChecksum(algorithm.typ, response); got != want {
|
||||
t.Fatalf("%s: CopyPartResult %s is %q, want %q: %s",
|
||||
instanceType, algorithm.typ.String(), got, want, rec.Body.String())
|
||||
}
|
||||
|
||||
// The persisted part must carry the same value, and the client must be
|
||||
// able to complete the upload with what CopyPartResult returned.
|
||||
parts := listPartsHTTP(t, apiRouter, credentials, remoteBucket, object, uploadID, nil)
|
||||
if len(parts.Parts) != 1 {
|
||||
t.Fatalf("%s: ListParts returned %d parts, want 1", instanceType, len(parts.Parts))
|
||||
}
|
||||
if got := partChecksum(algorithm.typ, parts.Parts[0]); got != want {
|
||||
t.Fatalf("%s: persisted part %s is %q, want %q", instanceType, algorithm.typ.String(), got, want)
|
||||
}
|
||||
etag := canonicalizeETag(response.ETag)
|
||||
completed := completePartsHTTP(t, apiRouter, credentials, remoteBucket, object, uploadID,
|
||||
[]CompletePart{completePartWithChecksum(algorithm.typ, 1, etag, want)}, nil)
|
||||
if completed.Code != http.StatusOK {
|
||||
t.Fatalf("%s: CompleteMultipartUpload rejected the federated part: %d %s",
|
||||
instanceType, completed.Code, completed.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -55,6 +55,88 @@ import (
|
||||
|
||||
// Multipart objectAPIHandlers
|
||||
|
||||
// isFederatedInternalRequest reports whether User-Agent carries the minio-go
|
||||
// application token attached by getRemoteInstanceClient.
|
||||
//
|
||||
// This is only a response-shape hint. User-Agent is not authenticated and must
|
||||
// never gate authorization, object visibility, or request validation. It is
|
||||
// safe here because the only effect is returning the checksum of the body the
|
||||
// caller was already authorized to upload.
|
||||
func isFederatedInternalRequest(userAgent string) bool {
|
||||
for _, product := range strings.Fields(userAgent) {
|
||||
name, version, ok := strings.Cut(product, "/")
|
||||
if ok && name == federatedInternalAppName && version != "" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// partChecksumMap returns the non-empty part checksums in the form expected by
|
||||
// hash.AddChecksumHeader. x-amz-checksum-type is deliberately excluded because
|
||||
// UploadPart does not return it and minio-go cannot carry it in ObjectPart.
|
||||
func partChecksumMap(partInfo PartInfo) map[string]string {
|
||||
checksums := make(map[string]string, 1)
|
||||
if partInfo.ChecksumCRC32 != "" {
|
||||
checksums[hash.ChecksumCRC32.String()] = partInfo.ChecksumCRC32
|
||||
}
|
||||
if partInfo.ChecksumCRC32C != "" {
|
||||
checksums[hash.ChecksumCRC32C.String()] = partInfo.ChecksumCRC32C
|
||||
}
|
||||
if partInfo.ChecksumSHA1 != "" {
|
||||
checksums[hash.ChecksumSHA1.String()] = partInfo.ChecksumSHA1
|
||||
}
|
||||
if partInfo.ChecksumSHA256 != "" {
|
||||
checksums[hash.ChecksumSHA256.String()] = partInfo.ChecksumSHA256
|
||||
}
|
||||
if partInfo.ChecksumCRC64NVME != "" {
|
||||
checksums[hash.ChecksumCRC64NVME.String()] = partInfo.ChecksumCRC64NVME
|
||||
}
|
||||
return checksums
|
||||
}
|
||||
|
||||
// multipartChecksumType returns the base checksum type recorded when a
|
||||
// multipart upload was created. The boolean reports whether an algorithm was
|
||||
// recorded at all.
|
||||
func multipartChecksumType(metadata map[string]string) (hash.ChecksumType, bool) {
|
||||
algorithm := metadata[hash.MinIOMultipartChecksum]
|
||||
if algorithm == "" {
|
||||
return hash.ChecksumNone, false
|
||||
}
|
||||
t := hash.NewChecksumType(algorithm, metadata[hash.MinIOMultipartChecksumType])
|
||||
if !t.IsSet() {
|
||||
return t, true
|
||||
}
|
||||
return t.Base(), true
|
||||
}
|
||||
|
||||
// prepareMultipartChecksumReader validates a supplied part checksum algorithm,
|
||||
// or installs a server-side hasher when the client omitted the optional
|
||||
// checksum. It must run before compression or encryption can consume reader.
|
||||
func prepareMultipartChecksumReader(reader *hash.Reader, metadata map[string]string, bucket, object string) error {
|
||||
want, ok := multipartChecksumType(metadata)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
got := reader.ContentCRCType()
|
||||
if !got.IsSet() && reader.ServerSideChecksumType.IsSet() {
|
||||
got = reader.ServerSideChecksumType
|
||||
}
|
||||
if !want.IsSet() || (got.IsSet() && got.Base() != want) {
|
||||
return InvalidArgument{
|
||||
Bucket: bucket,
|
||||
Object: object,
|
||||
Err: fmt.Errorf("checksum missing, want %q, got %q",
|
||||
metadata[hash.MinIOMultipartChecksum], got.String()),
|
||||
}
|
||||
}
|
||||
if !got.IsSet() {
|
||||
reader.AddServerSideChecksumHasher(want)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// NewMultipartUploadHandler - New multipart upload.
|
||||
// Notice: The S3 client can send secret keys in headers for encryption related jobs,
|
||||
// the handler should ensure to remove these keys before sending them to the object layer.
|
||||
@@ -89,6 +171,21 @@ func (api objectAPIHandlers) NewMultipartUploadHandler(w http.ResponseWriter, r
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Error), r.URL)
|
||||
return
|
||||
}
|
||||
rawReplica := hasReplicaStatus(r.Header)
|
||||
markerExact := hasReplicationMarker(r.Header)
|
||||
replicationPermitted := false
|
||||
if rawReplica || markerExact {
|
||||
replicationPermitted = replicationPermissionAllowed(ctx, r, bucket, object, policy.ReplicateObjectAction)
|
||||
}
|
||||
if rawReplica && !replicationPermitted {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrAccessDenied), r.URL)
|
||||
return
|
||||
}
|
||||
trustedReplication := markerExact && replicationPermitted
|
||||
replicaTrusted := trustedReplication && rawReplica
|
||||
if hasReplicationRequestHeaders(r.Header) {
|
||||
ctx, r = applyReplicationTrust(ctx, r, trustedReplication, replicaTrusted)
|
||||
}
|
||||
|
||||
// Check if bucket encryption is enabled
|
||||
sseConfig, _ := globalBucketSSEConfigSys.Get(bucket)
|
||||
@@ -123,7 +220,6 @@ func (api objectAPIHandlers) NewMultipartUploadHandler(w http.ResponseWriter, r
|
||||
return
|
||||
}
|
||||
|
||||
_, sourceReplReq := r.Header[xhttp.MinIOSourceReplicationRequest]
|
||||
ssecRepHeaders := []string{
|
||||
"X-Minio-Replication-Server-Side-Encryption-Seal-Algorithm",
|
||||
"X-Minio-Replication-Server-Side-Encryption-Sealed-Key",
|
||||
@@ -136,7 +232,7 @@ func (api objectAPIHandlers) NewMultipartUploadHandler(w http.ResponseWriter, r
|
||||
break
|
||||
}
|
||||
}
|
||||
if !ssecRep || !sourceReplReq {
|
||||
if !ssecRep || !replicaTrusted {
|
||||
if err = setEncryptionMetadata(r, bucket, object, encMetadata); err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
@@ -160,24 +256,23 @@ func (api objectAPIHandlers) NewMultipartUploadHandler(w http.ResponseWriter, r
|
||||
return
|
||||
}
|
||||
}
|
||||
if r.Header.Get(xhttp.AmzBucketReplicationStatus) == replication.Replica.String() {
|
||||
if s3Err := isPutActionAllowed(ctx, getRequestAuthType(r), bucket, object, r, policy.ReplicateObjectAction); s3Err != ErrNone {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Err), r.URL)
|
||||
return
|
||||
}
|
||||
if replicaTrusted {
|
||||
if err = extractReplicationMetadataFromMime(ctx, textproto.MIMEHeader(r.Header), metadata); err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
metadata[xhttp.AmzBucketReplicationStatus] = replication.Replica.String()
|
||||
metadata[ReservedMetadataPrefixLower+ReplicaStatus] = replication.Replica.String()
|
||||
metadata[ReservedMetadataPrefixLower+ReplicaTimestamp] = UTCNow().Format(time.RFC3339Nano)
|
||||
} else {
|
||||
delete(metadata, xhttp.AmzBucketReplicationStatus)
|
||||
}
|
||||
retPerms := isPutActionAllowed(ctx, getRequestAuthType(r), bucket, object, r, policy.PutObjectRetentionAction)
|
||||
holdPerms := isPutActionAllowed(ctx, getRequestAuthType(r), bucket, object, r, policy.PutObjectLegalHoldAction)
|
||||
|
||||
getObjectInfo := objectAPI.GetObjectInfo
|
||||
|
||||
retentionMode, retentionDate, legalHold, s3Err := checkPutObjectLockAllowed(ctx, r, bucket, object, getObjectInfo, retPerms, holdPerms)
|
||||
retentionMode, retentionDate, legalHold, s3Err := checkPutObjectLockAllowed(ctx, r, bucket, object, getObjectInfo, retPerms, holdPerms, replicaTrusted)
|
||||
if s3Err == ErrNone && retentionMode.Valid() {
|
||||
metadata[strings.ToLower(xhttp.AmzObjectLockMode)] = string(retentionMode)
|
||||
metadata[strings.ToLower(xhttp.AmzObjectLockRetainUntilDate)] = amztime.ISO8601Format(retentionDate.UTC())
|
||||
@@ -227,6 +322,10 @@ func (api objectAPIHandlers) NewMultipartUploadHandler(w http.ResponseWriter, r
|
||||
}
|
||||
}
|
||||
|
||||
if _, err := hash.GetContentChecksum(r.Header); err != nil {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrInvalidChecksum), r.URL)
|
||||
return
|
||||
}
|
||||
checksumType := hash.NewChecksumHeader(r.Header)
|
||||
if checksumType.Is(hash.ChecksumInvalid) {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrInvalidChecksum), r.URL)
|
||||
@@ -322,6 +421,14 @@ func (api objectAPIHandlers) CopyObjectPartHandler(w http.ResponseWriter, r *htt
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Error), r.URL)
|
||||
return
|
||||
}
|
||||
if hasReplicaStatus(r.Header) &&
|
||||
!replicationPermissionAllowed(ctx, r, dstBucket, dstObject, policy.ReplicateObjectAction) {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrAccessDenied), r.URL)
|
||||
return
|
||||
}
|
||||
if hasReplicationRequestHeaders(r.Header) {
|
||||
ctx, r = applyReplicationTrust(ctx, r, false, false)
|
||||
}
|
||||
|
||||
uploadID := r.Form.Get(xhttp.UploadID)
|
||||
partIDString := r.Form.Get(xhttp.PartNumber)
|
||||
@@ -465,7 +572,15 @@ func (api objectAPIHandlers) CopyObjectPartHandler(w http.ResponseWriter, r *htt
|
||||
return
|
||||
}
|
||||
|
||||
response := generateCopyObjectPartResponse(partInfo.ETag, partInfo.LastModified)
|
||||
response := generateCopyObjectPartResponse(PartInfo{
|
||||
ETag: partInfo.ETag,
|
||||
LastModified: partInfo.LastModified,
|
||||
ChecksumCRC32: partInfo.ChecksumCRC32,
|
||||
ChecksumCRC32C: partInfo.ChecksumCRC32C,
|
||||
ChecksumSHA1: partInfo.ChecksumSHA1,
|
||||
ChecksumSHA256: partInfo.ChecksumSHA256,
|
||||
ChecksumCRC64NVME: partInfo.ChecksumCRC64NVME,
|
||||
})
|
||||
encodedSuccessResponse := encodeResponse(response)
|
||||
|
||||
// Write success response.
|
||||
@@ -475,12 +590,25 @@ func (api objectAPIHandlers) CopyObjectPartHandler(w http.ResponseWriter, r *htt
|
||||
|
||||
actualPartSize = length
|
||||
var reader io.Reader = etag.NewReader(ctx, gr, nil, nil)
|
||||
var checksumReader *hash.Reader
|
||||
|
||||
mi, err := objectAPI.GetMultipartInfo(ctx, dstBucket, dstObject, uploadID, dstOpts)
|
||||
if err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
if _, ok := multipartChecksumType(mi.UserDefined); ok {
|
||||
checksumReader, err = hash.NewReader(ctx, reader, length, "", "", actualPartSize)
|
||||
if err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
if err = prepareMultipartChecksumReader(checksumReader, mi.UserDefined, dstBucket, dstObject); err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
reader = checksumReader
|
||||
}
|
||||
|
||||
_, isEncrypted := crypto.IsEncrypted(mi.UserDefined)
|
||||
|
||||
@@ -512,6 +640,7 @@ func (api objectAPIHandlers) CopyObjectPartHandler(w http.ResponseWriter, r *htt
|
||||
|
||||
rawReader := srcInfo.Reader
|
||||
pReader := NewPutObjReader(rawReader)
|
||||
pReader.setChecksumReader(checksumReader)
|
||||
|
||||
var objectEncryptionKey crypto.ObjectKey
|
||||
if isEncrypted {
|
||||
@@ -591,7 +720,7 @@ func (api objectAPIHandlers) CopyObjectPartHandler(w http.ResponseWriter, r *htt
|
||||
partInfo.ETag = tryDecryptETag(objectEncryptionKey[:], partInfo.ETag, sseS3)
|
||||
}
|
||||
|
||||
response := generateCopyObjectPartResponse(partInfo.ETag, partInfo.LastModified)
|
||||
response := generateCopyObjectPartResponse(partInfo)
|
||||
encodedSuccessResponse := encodeResponse(response)
|
||||
|
||||
// Write success response.
|
||||
@@ -741,10 +870,27 @@ func (api objectAPIHandlers) PutObjectPartHandler(w http.ResponseWriter, r *http
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
rawReplica := hasReplicaStatus(r.Header)
|
||||
markerExact := hasReplicationMarker(r.Header)
|
||||
replicationPermitted := false
|
||||
if rawReplica || markerExact {
|
||||
replicationPermitted = replicationPermissionAllowed(ctx, r, bucket, object, policy.ReplicateObjectAction)
|
||||
}
|
||||
if rawReplica && !replicationPermitted {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrAccessDenied), r.URL)
|
||||
return
|
||||
}
|
||||
trustedReplication := markerExact && replicationPermitted
|
||||
storedReplica := mi.UserDefined[xhttp.AmzBucketReplicationStatus] == replication.Replica.String()
|
||||
replicaTrusted := trustedReplication && storedReplica
|
||||
if hasReplicationRequestHeaders(r.Header) {
|
||||
ctx, r = applyReplicationTrust(ctx, r, trustedReplication, replicaTrusted)
|
||||
}
|
||||
|
||||
// Read compression metadata preserved in the init multipart for the decision.
|
||||
_, isCompressed := mi.UserDefined[ReservedMetadataPrefix+"compression"]
|
||||
var idxCb func() []byte
|
||||
var checksumReader *hash.Reader
|
||||
if isCompressed {
|
||||
actualReader, err := hash.NewReader(ctx, reader, size, md5hex, sha256hex, actualSize)
|
||||
if err != nil {
|
||||
@@ -755,6 +901,11 @@ func (api objectAPIHandlers) PutObjectPartHandler(w http.ResponseWriter, r *http
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrInvalidChecksum), r.URL)
|
||||
return
|
||||
}
|
||||
if err = prepareMultipartChecksumReader(actualReader, mi.UserDefined, bucket, object); err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
checksumReader = actualReader
|
||||
|
||||
// Set compression metrics.
|
||||
wantEncryption := crypto.Requested(r.Header)
|
||||
@@ -791,15 +942,21 @@ func (api objectAPIHandlers) PutObjectPartHandler(w http.ResponseWriter, r *http
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrInvalidChecksum), r.URL)
|
||||
return
|
||||
}
|
||||
if checksumReader == nil {
|
||||
if err = prepareMultipartChecksumReader(hashReader, mi.UserDefined, bucket, object); err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
}
|
||||
checksumReader = hashReader
|
||||
}
|
||||
|
||||
pReader := NewPutObjReader(hashReader)
|
||||
pReader.setChecksumReader(checksumReader)
|
||||
|
||||
_, isEncrypted := crypto.IsEncrypted(mi.UserDefined)
|
||||
_, replicationStatus := mi.UserDefined[xhttp.AmzBucketReplicationStatus]
|
||||
_, sourceReplReq := r.Header[xhttp.MinIOSourceReplicationRequest]
|
||||
var objectEncryptionKey crypto.ObjectKey
|
||||
if isEncrypted {
|
||||
if !crypto.SSEC.IsRequested(r.Header) && crypto.SSEC.IsEncrypted(mi.UserDefined) && !replicationStatus {
|
||||
if !crypto.SSEC.IsRequested(r.Header) && crypto.SSEC.IsEncrypted(mi.UserDefined) && !replicaTrusted {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrSSEMultipartEncrypted), r.URL)
|
||||
return
|
||||
}
|
||||
@@ -819,7 +976,7 @@ func (api objectAPIHandlers) PutObjectPartHandler(w http.ResponseWriter, r *http
|
||||
}
|
||||
}
|
||||
|
||||
if !sourceReplReq || !crypto.SSEC.IsEncrypted(mi.UserDefined) {
|
||||
if !replicaTrusted || !crypto.SSEC.IsEncrypted(mi.UserDefined) {
|
||||
// Calculating object encryption key
|
||||
key, err = decryptObjectMeta(key, bucket, object, mi.UserDefined)
|
||||
if err != nil {
|
||||
@@ -878,7 +1035,7 @@ func (api objectAPIHandlers) PutObjectPartHandler(w http.ResponseWriter, r *http
|
||||
}
|
||||
opts.IndexCB = idxCb
|
||||
|
||||
opts.ReplicationRequest = sourceReplReq
|
||||
opts.ReplicationRequest = trustedReplication
|
||||
putObjectPart := objectAPI.PutObjectPart
|
||||
|
||||
partInfo, err := putObjectPart(ctx, bucket, object, uploadID, partID, pReader, opts)
|
||||
@@ -918,6 +1075,13 @@ func (api objectAPIHandlers) PutObjectPartHandler(w http.ResponseWriter, r *http
|
||||
// Therefore, we have to set the ETag directly as map entry.
|
||||
w.Header()[xhttp.ETag] = []string{"\"" + etag + "\""}
|
||||
hash.TransferChecksumHeader(w, r)
|
||||
if isFederatedInternalRequest(r.UserAgent()) {
|
||||
// Legacy federation proxies UploadPartCopy through minio-go
|
||||
// Core.PutObjectPart, which can only recover checksums from response
|
||||
// headers. Use the PartInfo returned by this exact write so the ETag and
|
||||
// checksum cannot be mixed with a concurrent overwrite.
|
||||
hash.AddChecksumHeader(w, partChecksumMap(partInfo))
|
||||
}
|
||||
|
||||
writeSuccessResponseHeadersOnly(w)
|
||||
}
|
||||
@@ -946,6 +1110,20 @@ func (api objectAPIHandlers) CompleteMultipartUploadHandler(w http.ResponseWrite
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Error), r.URL)
|
||||
return
|
||||
}
|
||||
rawReplica := hasReplicaStatus(r.Header)
|
||||
markerExact := hasReplicationMarker(r.Header)
|
||||
replicationPermitted := false
|
||||
if rawReplica || markerExact {
|
||||
replicationPermitted = replicationPermissionAllowed(ctx, r, bucket, object, policy.ReplicateObjectAction)
|
||||
}
|
||||
if rawReplica && !replicationPermitted {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(ErrAccessDenied), r.URL)
|
||||
return
|
||||
}
|
||||
trustedReplication := markerExact && replicationPermitted
|
||||
if hasReplicationRequestHeaders(r.Header) {
|
||||
ctx, r = applyReplicationTrust(ctx, r, trustedReplication, trustedReplication && rawReplica)
|
||||
}
|
||||
|
||||
// Get upload id.
|
||||
uploadID, _, _, _, s3Error := getObjectResources(r.Form)
|
||||
@@ -988,7 +1166,7 @@ func (api objectAPIHandlers) CompleteMultipartUploadHandler(w http.ResponseWrite
|
||||
return
|
||||
}
|
||||
|
||||
if _, _, _, s3Err := checkPutObjectLockAllowed(ctx, r, bucket, object, objectAPI.GetObjectInfo, ErrNone, ErrNone); s3Err != ErrNone {
|
||||
if _, _, _, s3Err := checkPutObjectLockAllowed(ctx, r, bucket, object, objectAPI.GetObjectInfo, ErrNone, ErrNone, false); s3Err != ErrNone {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Err), r.URL)
|
||||
return
|
||||
}
|
||||
@@ -1071,7 +1249,7 @@ func (api objectAPIHandlers) CompleteMultipartUploadHandler(w http.ResponseWrite
|
||||
if dsc := mustReplicate(ctx, bucket, object, objInfo.getMustReplicateOptions(replication.ObjectReplicationType, opts)); dsc.ReplicateAny() {
|
||||
scheduleReplication(ctx, objInfo, objectAPI, dsc, replication.ObjectReplicationType)
|
||||
}
|
||||
if _, ok := r.Header[xhttp.MinIOSourceReplicationRequest]; ok {
|
||||
if isTrustedReplication(ctx) {
|
||||
actualSize, _ := objInfo.GetActualSize()
|
||||
defer globalReplicationStats.Load().UpdateReplicaStat(bucket, actualSize)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,226 @@
|
||||
// Copyright (c) 2015-2026 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
"encoding/xml"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/minio/minio/internal/auth"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
)
|
||||
|
||||
func TestAPIZeroByteSSECAuthenticatesKey(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPIZeroByteSSECAuthenticatesKey,
|
||||
endpoints: []string{"CopyObject", "CopyObjectPart", "PutObject", "GetObject", "HeadObject", "NewMultipart"},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPIZeroByteSSECAuthenticatesKey(obj ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
previousTLS := globalIsTLS
|
||||
globalIsTLS = true
|
||||
defer func() { globalIsTLS = previousTLS }()
|
||||
|
||||
object := "ssec/zero-byte"
|
||||
oldKey := bytes.Repeat([]byte{0x11}, 32)
|
||||
oldMD5 := md5.Sum(oldKey)
|
||||
wrongKey := bytes.Repeat([]byte{0x22}, 32)
|
||||
wrongMD5 := md5.Sum(wrongKey)
|
||||
putCopyChecksumSource(t, apiRouter, credentials, bucketName, object, nil, map[string]string{
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(oldKey),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(oldMD5[:]),
|
||||
})
|
||||
|
||||
correctHeaders := map[string]string{
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(oldKey),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(oldMD5[:]),
|
||||
}
|
||||
wrongHeaders := map[string]string{
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(wrongKey),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(wrongMD5[:]),
|
||||
}
|
||||
|
||||
if rec := ssecZeroByteRequest(t, apiRouter, credentials, http.MethodGet, bucketName, object, correctHeaders); rec.Code != http.StatusOK || rec.Body.Len() != 0 {
|
||||
t.Fatalf("%s: correct-key GET returned %d with %d bytes: %s", instanceType, rec.Code, rec.Body.Len(), rec.Body.String())
|
||||
}
|
||||
headRec := ssecZeroByteRequest(t, apiRouter, credentials, http.MethodHead, bucketName, object, correctHeaders)
|
||||
if headRec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: correct-key HEAD returned %d", instanceType, headRec.Code)
|
||||
}
|
||||
if rec := ssecZeroByteRequest(t, apiRouter, credentials, http.MethodGet, bucketName, object, wrongHeaders); rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("%s: wrong-key GET returned %d, want %d: %s", instanceType, rec.Code, http.StatusForbidden, rec.Body.String())
|
||||
}
|
||||
if rec := ssecZeroByteRequest(t, apiRouter, credentials, http.MethodHead, bucketName, object, wrongHeaders); rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("%s: wrong-key HEAD returned %d, want %d", instanceType, rec.Code, http.StatusForbidden)
|
||||
}
|
||||
conditionalHeaders := make(map[string]string, len(wrongHeaders)+1)
|
||||
for key, value := range wrongHeaders {
|
||||
conditionalHeaders[key] = value
|
||||
}
|
||||
conditionalInfo, err := obj.GetObjectInfo(t.Context(), bucketName, object, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conditionalRequest := httptest.NewRequest(http.MethodGet, getGetObjectURL("", bucketName, object), nil)
|
||||
for key, value := range wrongHeaders {
|
||||
conditionalRequest.Header.Set(key, value)
|
||||
}
|
||||
if _, err := DecryptObjectInfo(&conditionalInfo, conditionalRequest); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
conditionalHeaders[xhttp.IfNoneMatch] = conditionalInfo.ETag
|
||||
if rec := ssecZeroByteRequest(t, apiRouter, credentials, http.MethodGet, bucketName, object, conditionalHeaders); rec.Code != http.StatusNotModified {
|
||||
t.Fatalf("%s: conditional wrong-key GET returned %d, want %d: %s", instanceType, rec.Code, http.StatusNotModified, rec.Body.String())
|
||||
}
|
||||
if rec := ssecZeroByteRequest(t, apiRouter, credentials, http.MethodGet, bucketName, object, nil); rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("%s: missing-key GET returned %d, want %d: %s", instanceType, rec.Code, http.StatusBadRequest, rec.Body.String())
|
||||
}
|
||||
|
||||
nonEmptyObject := "ssec/one-byte"
|
||||
putCopyChecksumSource(t, apiRouter, credentials, bucketName, nonEmptyObject, []byte{1}, correctHeaders)
|
||||
if rec := ssecZeroByteRequest(t, apiRouter, credentials, http.MethodGet, bucketName, nonEmptyObject, wrongHeaders); rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("%s: one-byte wrong-key GET returned %d, want %d: %s", instanceType, rec.Code, http.StatusForbidden, rec.Body.String())
|
||||
}
|
||||
|
||||
plainObject := "ssec/plain-zero-byte"
|
||||
putCopyChecksumSource(t, apiRouter, credentials, bucketName, plainObject, nil, nil)
|
||||
if rec := ssecZeroByteRequest(t, apiRouter, credentials, http.MethodGet, bucketName, plainObject, wrongHeaders); rec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("%s: unencrypted wrong-key GET returned %d, want %d: %s", instanceType, rec.Code, http.StatusBadRequest, rec.Body.String())
|
||||
}
|
||||
|
||||
destination := "ssec/zero-byte-copy"
|
||||
rec := copyChecksumRequest(t, apiRouter, credentials, bucketName, object, destination, map[string]string{
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerKey: base64.StdEncoding.EncodeToString(wrongKey),
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerKeyMD5: base64.StdEncoding.EncodeToString(wrongMD5[:]),
|
||||
})
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("%s: wrong-key CopyObject returned %d, want %d: %s", instanceType, rec.Code, http.StatusForbidden, rec.Body.String())
|
||||
}
|
||||
if _, err := obj.GetObjectInfo(t.Context(), bucketName, destination, ObjectOptions{}); !isErrObjectNotFound(err) {
|
||||
t.Fatalf("%s: rejected CopyObject created the destination: %v", instanceType, err)
|
||||
}
|
||||
|
||||
rec = copyChecksumRequest(t, apiRouter, credentials, bucketName, object, object, map[string]string{
|
||||
xhttp.AmzStorageClass: "REDUCED_REDUNDANCY",
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerKey: base64.StdEncoding.EncodeToString(wrongKey),
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerKeyMD5: base64.StdEncoding.EncodeToString(wrongMD5[:]),
|
||||
})
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("%s: wrong-key storage-class CopyObject returned %d, want %d: %s", instanceType, rec.Code, http.StatusForbidden, rec.Body.String())
|
||||
}
|
||||
|
||||
multipartObject := "ssec/zero-byte-multipart-copy"
|
||||
req, err := newTestSignedRequestV4(http.MethodPost, getNewMultipartURL("", bucketName, multipartObject),
|
||||
0, nil, credentials.AccessKey, credentials.SecretKey, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec = httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: NewMultipartUpload returned %d: %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
var initiated InitiateMultipartUploadResponse
|
||||
if err := xml.Unmarshal(rec.Body.Bytes(), &initiated); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req, err = newTestSignedRequestV4(http.MethodPut,
|
||||
getCopyObjectPartURL("", bucketName, multipartObject, initiated.UploadID, "1"),
|
||||
0, nil, credentials.AccessKey, credentials.SecretKey, map[string]string{
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerKey: base64.StdEncoding.EncodeToString(wrongKey),
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerKeyMD5: base64.StdEncoding.EncodeToString(wrongMD5[:]),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set(xhttp.AmzCopySource, SlashSeparator+pathJoin(bucketName, object))
|
||||
rec = httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("%s: wrong-key UploadPartCopy returned %d, want %d: %s", instanceType, rec.Code, http.StatusForbidden, rec.Body.String())
|
||||
}
|
||||
parts, err := obj.ListObjectParts(t.Context(), bucketName, multipartObject, initiated.UploadID, 0, 1000, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(parts.Parts) != 0 {
|
||||
t.Fatalf("%s: rejected UploadPartCopy stored %d parts", instanceType, len(parts.Parts))
|
||||
}
|
||||
if err := obj.AbortMultipartUpload(t.Context(), bucketName, multipartObject, initiated.UploadID, ObjectOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
wrongHeader := http.Header{}
|
||||
for key, value := range wrongHeaders {
|
||||
wrongHeader.Set(key, value)
|
||||
}
|
||||
for _, test := range []struct {
|
||||
header http.Header
|
||||
opts ObjectOptions
|
||||
}{
|
||||
{header: nil, opts: ObjectOptions{}},
|
||||
{header: wrongHeader, opts: ObjectOptions{NoDecryption: true}},
|
||||
{header: wrongHeader, opts: ObjectOptions{ReplicationRequest: true}},
|
||||
{header: wrongHeader, opts: ObjectOptions{Transition: TransitionOptions{RestoreRequest: &RestoreObjectRequest{}}}},
|
||||
} {
|
||||
gr, err := obj.GetObjectNInfo(t.Context(), bucketName, object, nil, test.header, test.opts)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: internal zero-byte read with opts %+v failed: %v", instanceType, test.opts, err)
|
||||
}
|
||||
gr.Close()
|
||||
}
|
||||
|
||||
rangeHeaders := make(map[string]string, len(wrongHeaders)+1)
|
||||
for key, value := range wrongHeaders {
|
||||
rangeHeaders[key] = value
|
||||
}
|
||||
rangeHeaders[xhttp.Range] = "bytes=0-0"
|
||||
if rec := ssecZeroByteRequest(t, apiRouter, credentials, http.MethodGet, bucketName, object, rangeHeaders); rec.Code != http.StatusRequestedRangeNotSatisfiable {
|
||||
t.Fatalf("%s: ranged wrong-key GET returned %d, want %d: %s", instanceType, rec.Code, http.StatusRequestedRangeNotSatisfiable, rec.Body.String())
|
||||
}
|
||||
}
|
||||
|
||||
func ssecZeroByteRequest(t *testing.T, apiRouter http.Handler, credentials auth.Credentials,
|
||||
method, bucket, object string, headers map[string]string,
|
||||
) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req, err := newTestSignedRequestV4(method, getGetObjectURL("", bucket, object),
|
||||
0, nil, credentials.AccessKey, credentials.SecretKey, headers)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
@@ -849,6 +849,45 @@ func testListObjectsTestsForNonExistentBucket(obj ObjectLayer, instanceType stri
|
||||
}
|
||||
}
|
||||
|
||||
// Wrapper for calling testListObjectsShortcutsForNonExistentBucket for both
|
||||
// single-drive and multi-drive erasure setups.
|
||||
func TestListObjectsShortcutsForNonExistentBucket(t *testing.T) {
|
||||
ExecObjectLayerTest(t, testListObjectsShortcutsForNonExistentBucket)
|
||||
}
|
||||
|
||||
// Tests validate that storage-bypassing list shortcuts do not mask a missing
|
||||
// bucket as an empty result. The regular prefix case is a control for the
|
||||
// storage-backed listing path.
|
||||
func testListObjectsShortcutsForNonExistentBucket(obj ObjectLayer, instanceType string, t TestErrHandler) {
|
||||
testCases := []struct {
|
||||
name string
|
||||
prefix string
|
||||
marker string
|
||||
maxKeys int
|
||||
}{
|
||||
{name: "slash-prefixed prefix", prefix: "/", maxKeys: 1000},
|
||||
{name: "zero limit", prefix: "obj", maxKeys: 0},
|
||||
{name: "marker outside prefix", prefix: "a", marker: "b", maxKeys: 1000},
|
||||
{name: "regular prefix", prefix: "foo/bar", maxKeys: 1000},
|
||||
}
|
||||
for _, tc := range testCases {
|
||||
_, err := obj.ListObjects(context.Background(), "bucket", tc.prefix, tc.marker, "", tc.maxKeys)
|
||||
if !isErrBucketNotFound(err) {
|
||||
t.Errorf("%s: ListObjects %s: expected BucketNotFound, got %v", instanceType, tc.name, err)
|
||||
}
|
||||
|
||||
_, err = obj.ListObjectsV2(context.Background(), "bucket", tc.prefix, "", "", tc.maxKeys, false, tc.marker)
|
||||
if !isErrBucketNotFound(err) {
|
||||
t.Errorf("%s: ListObjectsV2 %s: expected BucketNotFound, got %v", instanceType, tc.name, err)
|
||||
}
|
||||
|
||||
_, err = obj.ListObjectVersions(context.Background(), "bucket", tc.prefix, tc.marker, "", "", tc.maxKeys)
|
||||
if !isErrBucketNotFound(err) {
|
||||
t.Errorf("%s: ListObjectVersions %s: expected BucketNotFound, got %v", instanceType, tc.name, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Wrapper for calling testNonExistentObjectInBucket for both Erasure and FS.
|
||||
func TestNonExistentObjectInBucket(t *testing.T) {
|
||||
ExecObjectLayerTest(t, testNonExistentObjectInBucket)
|
||||
|
||||
@@ -80,8 +80,6 @@ func setupTestReadDirFiles(t *testing.T) (testResults []result) {
|
||||
for i := range 10 {
|
||||
name := fmt.Sprintf("file-%d", i)
|
||||
if err := os.WriteFile(filepath.Join(dir, name), []byte{}, os.ModePerm); err != nil {
|
||||
// For cleanup, its required to add these entries into test results.
|
||||
testResults = append(testResults, result{dir, entries})
|
||||
t.Fatalf("Unable to create file, %s", err)
|
||||
}
|
||||
entries = append(entries, name)
|
||||
@@ -105,8 +103,6 @@ func setupTestReadDirGeneric(t *testing.T) (testResults []result) {
|
||||
for i := range 10 {
|
||||
name := fmt.Sprintf("file-%d", i)
|
||||
if err := os.WriteFile(filepath.Join(dir, "mydir", name), []byte{}, os.ModePerm); err != nil {
|
||||
// For cleanup, its required to add these entries into test results.
|
||||
testResults = append(testResults, result{dir, entries})
|
||||
t.Fatalf("Unable to write file, %s", err)
|
||||
}
|
||||
}
|
||||
@@ -130,8 +126,6 @@ func setupTestReadDirSymlink(t *testing.T) (testResults []result) {
|
||||
name1 := fmt.Sprintf("file-%d", i)
|
||||
name2 := fmt.Sprintf("file-%d", i+10)
|
||||
if err := os.WriteFile(filepath.Join(dir, name1), []byte{}, os.ModePerm); err != nil {
|
||||
// For cleanup, its required to add these entries into test results.
|
||||
testResults = append(testResults, result{dir, entries})
|
||||
t.Fatalf("Unable to create a file, %s", err)
|
||||
}
|
||||
// Symlink will not be added to entries.
|
||||
|
||||
@@ -33,6 +33,7 @@ import (
|
||||
"time"
|
||||
|
||||
"github.com/dustin/go-humanize"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
)
|
||||
|
||||
const (
|
||||
@@ -184,6 +185,49 @@ func TestPostPolicyBucketHandler(t *testing.T) {
|
||||
ExecObjectLayerTest(t, testPostPolicyBucketHandler)
|
||||
}
|
||||
|
||||
func TestPostPolicyCannotForgeReplicationStatus(t *testing.T) {
|
||||
ExecObjectLayerTest(t, testPostPolicyCannotForgeReplicationStatus)
|
||||
}
|
||||
|
||||
func testPostPolicyCannotForgeReplicationStatus(obj ObjectLayer, instanceType string, t TestErrHandler) {
|
||||
if err := newTestConfig(globalMinioDefaultRegion, obj); err != nil {
|
||||
t.Fatalf("Initializing config.json failed")
|
||||
}
|
||||
bucketName := getRandomBucketName()
|
||||
if err := obj.MakeBucket(context.Background(), bucketName, MakeBucketOptions{}); err != nil {
|
||||
t.Fatalf("%s: make bucket: %v", instanceType, err)
|
||||
}
|
||||
apiRouter := initTestAPIEndPoints(obj, []string{"PostPolicy"})
|
||||
credentials := globalActiveCred
|
||||
now := UTCNow()
|
||||
region := globalMinioDefaultRegion
|
||||
objectPrefix := "post-policy-replication-status"
|
||||
policyBytes := buildGenericPolicy(now, credentials.AccessKey, region, bucketName, objectPrefix, false)
|
||||
policyText := strings.TrimSuffix(string(policyBytes), "]}") +
|
||||
`,["eq","$x-amz-replication-status","REPLICA"]]}`
|
||||
req, err := newPostRequestV4Generic("", bucketName, objectPrefix, []byte("post policy payload"),
|
||||
credentials.AccessKey, credentials.SecretKey, region, now, []byte(policyText),
|
||||
map[string]string{xhttp.AmzBucketReplicationStatus: "REPLICA"}, false, false, false)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: create post request: %v", instanceType, err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("%s: POST status %d: %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
info, err := obj.GetObjectInfo(context.Background(), bucketName, objectPrefix+"/upload.txt", ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("%s: get object info: %v", instanceType, err)
|
||||
}
|
||||
if got := info.UserDefined[xhttp.AmzBucketReplicationStatus]; got != "" {
|
||||
t.Fatalf("%s: forged replication status persisted as %q", instanceType, got)
|
||||
}
|
||||
if !info.ReplicationStatus.Empty() {
|
||||
t.Fatalf("%s: forged replication status reached ObjectInfo: %q", instanceType, info.ReplicationStatus)
|
||||
}
|
||||
}
|
||||
|
||||
// testPostPolicyBucketHandler - Tests validate post policy handler uploading objects.
|
||||
func testPostPolicyBucketHandler(obj ObjectLayer, instanceType string, t TestErrHandler) {
|
||||
if err := newTestConfig(globalMinioDefaultRegion, obj); err != nil {
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
// Copyright (c) 2015-2026 MinIO, Inc.
|
||||
// Copyright (c) 2026 PGSTY
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
objectreplication "github.com/minio/minio/internal/bucket/replication"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
"github.com/minio/minio/internal/logger"
|
||||
"github.com/minio/pkg/v3/policy"
|
||||
)
|
||||
|
||||
type (
|
||||
replicationTrustKey struct{}
|
||||
replicaTrustKey struct{}
|
||||
)
|
||||
|
||||
// hasReplicationMarker reports whether the internal replication marker has
|
||||
// its one accepted wire value. Header presence alone is never a trust signal.
|
||||
func hasReplicationMarker(h http.Header) bool {
|
||||
values, ok := h[http.CanonicalHeaderKey(xhttp.MinIOSourceReplicationRequest)]
|
||||
return ok && len(values) == 1 && values[0] == "true"
|
||||
}
|
||||
|
||||
func hasReplicationMarkerHeader(h http.Header) bool {
|
||||
_, ok := h[http.CanonicalHeaderKey(xhttp.MinIOSourceReplicationRequest)]
|
||||
return ok
|
||||
}
|
||||
|
||||
func hasReplicaStatus(h http.Header) bool {
|
||||
return h.Get(xhttp.AmzBucketReplicationStatus) == objectreplication.Replica.String()
|
||||
}
|
||||
|
||||
func withReplicationTrust(ctx context.Context, trusted, replicaTrusted bool) context.Context {
|
||||
ctx = context.WithValue(ctx, replicationTrustKey{}, trusted)
|
||||
return context.WithValue(ctx, replicaTrustKey{}, trusted && replicaTrusted)
|
||||
}
|
||||
|
||||
func isTrustedReplication(ctx context.Context) bool {
|
||||
trusted, _ := ctx.Value(replicationTrustKey{}).(bool)
|
||||
return trusted
|
||||
}
|
||||
|
||||
func isReplicaTrusted(ctx context.Context) bool {
|
||||
trusted, _ := ctx.Value(replicaTrustKey{}).(bool)
|
||||
return trusted
|
||||
}
|
||||
|
||||
// replicationPermissionAllowed must be called only after the request's
|
||||
// existing authentication/signature path has succeeded and populated ReqInfo.
|
||||
// Replication peers are authenticated principals; an anonymous bucket-policy
|
||||
// grant must not turn client-controlled internal headers into trusted state.
|
||||
func replicationPermissionAllowed(ctx context.Context, r *http.Request, bucket, object string, action policy.Action) bool {
|
||||
reqInfo := logger.GetReqInfo(ctx)
|
||||
if reqInfo == nil || reqInfo.Cred.AccessKey == "" {
|
||||
return false
|
||||
}
|
||||
reqInfo.BucketName = bucket
|
||||
reqInfo.ObjectName = object
|
||||
return authorizeRequest(ctx, r, action) == ErrNone
|
||||
}
|
||||
|
||||
// replicationRequestHeaders are internal request controls. They are removed
|
||||
// only after signature verification when a request has not earned replication
|
||||
// trust. Public S3/SSE/checksum headers, proxy loop guards, and replication
|
||||
// validity/readiness probes are intentionally not listed here.
|
||||
var replicationRequestHeaders = []string{
|
||||
xhttp.MinIOSourceReplicationRequest,
|
||||
xhttp.MinIOSourceETag,
|
||||
xhttp.MinIOSourceMTime,
|
||||
xhttp.MinIOSourceDeleteMarker,
|
||||
xhttp.MinIOSourceDeleteMarkerDelete,
|
||||
xhttp.MinIOSourceTaggingTimestamp,
|
||||
xhttp.MinIOSourceObjectRetentionTimestamp,
|
||||
xhttp.MinIOSourceObjectLegalHoldTimestamp,
|
||||
"X-Minio-Replication-Server-Side-Encryption-Sealed-Key",
|
||||
"X-Minio-Replication-Server-Side-Encryption-Seal-Algorithm",
|
||||
"X-Minio-Replication-Server-Side-Encryption-Iv",
|
||||
"X-Minio-Replication-Encrypted-Multipart",
|
||||
xhttp.MinIOReplicationActualObjectSize,
|
||||
ReplicationSsecChecksumHeader,
|
||||
xhttp.AmzBucketReplicationStatus,
|
||||
}
|
||||
|
||||
func stripReplicationRequestHeaders(h http.Header) {
|
||||
for _, name := range replicationRequestHeaders {
|
||||
h.Del(name)
|
||||
}
|
||||
}
|
||||
|
||||
func hasReplicationRequestHeaders(h http.Header) bool {
|
||||
for _, name := range replicationRequestHeaders {
|
||||
if _, ok := h[http.CanonicalHeaderKey(name)]; ok {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func cloneRequestWithoutReplicationHeaders(ctx context.Context, r *http.Request) *http.Request {
|
||||
clone := r.Clone(ctx)
|
||||
stripReplicationRequestHeaders(clone.Header)
|
||||
return clone
|
||||
}
|
||||
|
||||
// applyReplicationTrust binds the handler context to the effective request.
|
||||
// The context marker is the authorization source of truth; header removal is
|
||||
// defense in depth for option builders and future call sites.
|
||||
func applyReplicationTrust(ctx context.Context, r *http.Request, trusted, replicaTrusted bool) (context.Context, *http.Request) {
|
||||
ctx = withReplicationTrust(ctx, trusted, replicaTrusted)
|
||||
if trusted {
|
||||
return ctx, r.WithContext(ctx)
|
||||
}
|
||||
return ctx, cloneRequestWithoutReplicationHeaders(ctx, r)
|
||||
}
|
||||
@@ -0,0 +1,832 @@
|
||||
// Copyright (c) 2015-2026 MinIO, Inc.
|
||||
// Copyright (c) 2026 PGSTY
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"archive/tar"
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/minio/internal/auth"
|
||||
"github.com/minio/minio/internal/crypto"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
"github.com/minio/minio/internal/kms"
|
||||
"github.com/minio/pkg/v3/policy"
|
||||
)
|
||||
|
||||
func TestAPIReplicationTrustProtectsSSECReads(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPIReplicationTrustProtectsSSECReads,
|
||||
})
|
||||
}
|
||||
|
||||
func testAPIReplicationTrustProtectsSSECReads(_ ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
previousTLS := globalIsTLS
|
||||
globalIsTLS = true
|
||||
defer func() { globalIsTLS = previousTLS }()
|
||||
|
||||
key := bytes.Repeat([]byte{0x31}, 32)
|
||||
keyMD5 := md5.Sum(key)
|
||||
data := bytes.Repeat([]byte("replication-trust-ssec-"), 256)
|
||||
sseHeaders := map[string]string{
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(key),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(keyMD5[:]),
|
||||
}
|
||||
object := "replication-trust/ssec-read"
|
||||
putCopyChecksumSource(t, apiRouter, credentials, bucketName, object, data, sseHeaders)
|
||||
|
||||
readerOnly := newObjectAttributesAuthzUser(t, instanceType, bucketName, `"s3:GetObject"`)
|
||||
replicator := newObjectAttributesAuthzUser(t, instanceType, bucketName, `"s3:GetObject","s3:ReplicateObject"`)
|
||||
|
||||
marker := map[string]string{xhttp.MinIOSourceReplicationRequest: "true"}
|
||||
wrongCaseMarker := map[string]string{xhttp.MinIOSourceReplicationRequest: "TRUE"}
|
||||
conditionalMarker := map[string]string{
|
||||
xhttp.MinIOSourceReplicationRequest: "true",
|
||||
xhttp.IfNoneMatch: "*",
|
||||
}
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
method string
|
||||
creds auth.Credentials
|
||||
headers map[string]string
|
||||
wantStatus int
|
||||
wantPlain bool
|
||||
wantCipher bool
|
||||
}{
|
||||
{name: "get/reader/fake-marker", method: http.MethodGet, creds: readerOnly, headers: marker, wantStatus: http.StatusBadRequest},
|
||||
{name: "get/replicator/trusted", method: http.MethodGet, creds: replicator, headers: marker, wantStatus: http.StatusOK, wantCipher: true},
|
||||
{name: "get/root/trusted", method: http.MethodGet, creds: credentials, headers: marker, wantStatus: http.StatusOK, wantCipher: true},
|
||||
{name: "get/replicator/wrong-case", method: http.MethodGet, creds: replicator, headers: wrongCaseMarker, wantStatus: http.StatusBadRequest},
|
||||
{name: "get/reader/key", method: http.MethodGet, creds: readerOnly, headers: sseHeaders, wantStatus: http.StatusOK, wantPlain: true},
|
||||
{name: "head/reader/fake-marker", method: http.MethodHead, creds: readerOnly, headers: marker, wantStatus: http.StatusBadRequest},
|
||||
{name: "head/reader/conditional-oracle", method: http.MethodHead, creds: readerOnly, headers: conditionalMarker, wantStatus: http.StatusBadRequest},
|
||||
{name: "head/replicator/trusted", method: http.MethodHead, creds: replicator, headers: marker, wantStatus: http.StatusOK},
|
||||
{name: "head/replicator/wrong-case", method: http.MethodHead, creds: replicator, headers: wrongCaseMarker, wantStatus: http.StatusBadRequest},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
req, err := newTestSignedRequestV4(test.method, getGetObjectURL("", bucketName, object), 0, nil,
|
||||
test.creds.AccessKey, test.creds.SecretKey, test.headers)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != test.wantStatus {
|
||||
t.Fatalf("%s: status %d, want %d: %s", instanceType, rec.Code, test.wantStatus, rec.Body.String())
|
||||
}
|
||||
if test.wantPlain && !bytes.Equal(rec.Body.Bytes(), data) {
|
||||
t.Fatal("ordinary SSE-C GET did not return plaintext")
|
||||
}
|
||||
if test.wantCipher && (len(rec.Body.Bytes()) == 0 || bytes.Equal(rec.Body.Bytes(), data)) {
|
||||
t.Fatal("trusted replication GET did not return ciphertext")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReplicationTrustControlsInternalOptionsAndEvents(t *testing.T) {
|
||||
mtime := time.Date(2026, 8, 31, 12, 34, 56, 123, time.UTC)
|
||||
headers := make(http.Header)
|
||||
headers.Set(xhttp.MinIOSourceReplicationRequest, "true")
|
||||
headers.Set(xhttp.MinIOSourceETag, "source-etag")
|
||||
headers.Set(xhttp.MinIOSourceMTime, mtime.Format(time.RFC3339Nano))
|
||||
headers.Set(xhttp.MinIOReplicationActualObjectSize, "123")
|
||||
headers.Set(ReplicationSsecChecksumHeader, "checksum")
|
||||
|
||||
ordinary, err := putOptsFromHeaders(t.Context(), headers, nil, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ordinary.ReplicationRequest || ordinary.PreserveETag != "" || !ordinary.MTime.IsZero() {
|
||||
t.Fatalf("ordinary options trusted internal headers: %#v", ordinary)
|
||||
}
|
||||
|
||||
trusted, err := putOptsFromHeaders(t.Context(), headers, nil, true)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !trusted.ReplicationRequest || trusted.PreserveETag != "source-etag" || !trusted.MTime.Equal(mtime) {
|
||||
t.Fatalf("trusted options lost source state: %#v", trusted)
|
||||
}
|
||||
|
||||
completeReq := &http.Request{Header: headers.Clone(), Form: make(url.Values)}
|
||||
ordinaryComplete, err := completeMultipartOpts(t.Context(), completeReq, "bucket", "object")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if ordinaryComplete.ReplicationRequest || len(ordinaryComplete.UserDefined) != 0 {
|
||||
t.Fatalf("ordinary completion trusted internal metadata: %#v", ordinaryComplete)
|
||||
}
|
||||
trustedCompleteCtx := withReplicationTrust(t.Context(), true, false)
|
||||
trustedComplete, err := completeMultipartOpts(trustedCompleteCtx, completeReq.WithContext(trustedCompleteCtx), "bucket", "object")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !trustedComplete.ReplicationRequest || trustedComplete.UserDefined[ReservedMetadataPrefix+"Actual-Object-Size"] != "123" ||
|
||||
trustedComplete.UserDefined[ReplicationSsecChecksumHeader] != "checksum" {
|
||||
t.Fatalf("trusted completion lost internal metadata: %#v", trustedComplete)
|
||||
}
|
||||
|
||||
req := &http.Request{Header: headers.Clone(), Form: make(url.Values)}
|
||||
req = req.WithContext(context.Background())
|
||||
if _, ok := extractReqParams(req)[xhttp.MinIOSourceReplicationRequest]; ok {
|
||||
t.Fatal("untrusted marker suppressed events")
|
||||
}
|
||||
trustedCtx := withReplicationTrust(req.Context(), true, false)
|
||||
req = req.WithContext(trustedCtx)
|
||||
if _, ok := extractReqParams(req)[xhttp.MinIOSourceReplicationRequest]; !ok {
|
||||
t.Fatal("trusted replication marker was not propagated to events")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIPutObjectReplicationTrust(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPIPutObjectReplicationTrust,
|
||||
})
|
||||
}
|
||||
|
||||
func testAPIPutObjectReplicationTrust(obj ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, _ auth.Credentials, t *testing.T,
|
||||
) {
|
||||
putOnly := newObjectAttributesAuthzUser(t, instanceType, bucketName, `"s3:PutObject"`)
|
||||
replicator := newObjectAttributesAuthzUser(t, instanceType, bucketName, `"s3:PutObject","s3:ReplicateObject"`)
|
||||
payload := []byte("replication trust put payload")
|
||||
sourceMTime := time.Date(2024, 1, 2, 3, 4, 5, 6, time.UTC)
|
||||
|
||||
request := func(t *testing.T, object string, creds auth.Credentials, status string, check bool) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
headers := map[string]string{
|
||||
xhttp.MinIOSourceReplicationRequest: "true",
|
||||
xhttp.MinIOSourceETag: "source-etag",
|
||||
xhttp.MinIOSourceMTime: sourceMTime.Format(time.RFC3339Nano),
|
||||
}
|
||||
if status != "" {
|
||||
headers[xhttp.AmzBucketReplicationStatus] = status
|
||||
}
|
||||
if check {
|
||||
headers[xhttp.MinIOSourceReplicationCheck] = "true"
|
||||
}
|
||||
req, err := newTestSignedRequestV4(http.MethodPut, getPutObjectURL("", bucketName, object),
|
||||
int64(len(payload)), bytes.NewReader(payload), creds.AccessKey, creds.SecretKey, headers)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
t.Run("untrusted marker is ordinary", func(t *testing.T) {
|
||||
object := "replication-trust/put-ordinary"
|
||||
if rec := request(t, object, putOnly, "PENDING", false); rec.Code != http.StatusOK {
|
||||
t.Fatalf("status %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
info, err := obj.GetObjectInfo(t.Context(), bucketName, object, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.ETag == "source-etag" || info.ModTime.Equal(sourceMTime) {
|
||||
t.Fatalf("untrusted source state was preserved: ETag=%q MTime=%v", info.ETag, info.ModTime)
|
||||
}
|
||||
assertObjectMetadataKeysAbsent(t, info.UserDefined, xhttp.AmzBucketReplicationStatus)
|
||||
})
|
||||
|
||||
t.Run("unauthorized replica is denied", func(t *testing.T) {
|
||||
object := "replication-trust/put-denied-replica"
|
||||
if rec := request(t, object, putOnly, "REPLICA", false); rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("status %d, want 403: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if _, err := obj.GetObjectInfo(t.Context(), bucketName, object, ObjectOptions{}); err == nil {
|
||||
t.Fatal("unauthorized replica write created an object")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("trusted batch preserves source state", func(t *testing.T) {
|
||||
object := "replication-trust/put-batch"
|
||||
if rec := request(t, object, replicator, "", false); rec.Code != http.StatusOK {
|
||||
t.Fatalf("status %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
info, err := obj.GetObjectInfo(t.Context(), bucketName, object, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.ETag != "source-etag" || !info.ModTime.Equal(sourceMTime) {
|
||||
t.Fatalf("trusted source state lost: ETag=%q MTime=%v", info.ETag, info.ModTime)
|
||||
}
|
||||
assertObjectMetadataKeysAbsent(t, info.UserDefined, xhttp.AmzBucketReplicationStatus)
|
||||
})
|
||||
|
||||
t.Run("trusted replica persists replica state", func(t *testing.T) {
|
||||
object := "replication-trust/put-replica"
|
||||
if rec := request(t, object, replicator, "REPLICA", false); rec.Code != http.StatusOK {
|
||||
t.Fatalf("status %d: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
info, err := obj.GetObjectInfo(t.Context(), bucketName, object, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.UserDefined[xhttp.AmzBucketReplicationStatus] != "REPLICA" {
|
||||
t.Fatalf("replica status not persisted: %#v", info.UserDefined)
|
||||
}
|
||||
})
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
creds auth.Credentials
|
||||
wantStatus int
|
||||
}{
|
||||
{name: "validity check requires ReplicateObject", creds: putOnly, wantStatus: http.StatusForbidden},
|
||||
{name: "validity check succeeds for replicator", creds: replicator, wantStatus: http.StatusBadRequest},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
object := "replication-trust/put-check-" + strconv.Itoa(test.wantStatus)
|
||||
if rec := request(t, object, test.creds, "REPLICA", true); rec.Code != test.wantStatus {
|
||||
t.Fatalf("status %d, want %d: %s", rec.Code, test.wantStatus, rec.Body.String())
|
||||
}
|
||||
if _, err := obj.GetObjectInfo(t.Context(), bucketName, object, ObjectOptions{}); err == nil {
|
||||
t.Fatal("replication validity check created an object")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPISnowballReplicationTrustIsPerEntry(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPISnowballReplicationTrustIsPerEntry,
|
||||
})
|
||||
}
|
||||
|
||||
func testAPISnowballReplicationTrustIsPerEntry(obj ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, _ auth.Credentials, t *testing.T,
|
||||
) {
|
||||
const (
|
||||
allowedPrefix = "snowball/allowed/"
|
||||
deniedPrefix = "snowball/denied/"
|
||||
sourceETag = "0123456789abcdef0123456789abcdef"
|
||||
)
|
||||
creds := newSnowballReplicationTrustUser(t, instanceType, bucketName, allowedPrefix)
|
||||
|
||||
var body bytes.Buffer
|
||||
tw := tar.NewWriter(&body)
|
||||
objects := make([]struct {
|
||||
name string
|
||||
trusted bool
|
||||
}, 0, 32)
|
||||
for i := 0; i < 16; i++ {
|
||||
for _, entry := range []struct {
|
||||
prefix string
|
||||
trusted bool
|
||||
}{
|
||||
{prefix: allowedPrefix, trusted: true},
|
||||
{prefix: deniedPrefix},
|
||||
} {
|
||||
name := entry.prefix + strconv.Itoa(i)
|
||||
data := []byte("snowball replication trust " + name)
|
||||
if err := tw.WriteHeader(&tar.Header{Name: name, Mode: 0o600, Size: int64(len(data))}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := tw.Write(data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
objects = append(objects, struct {
|
||||
name string
|
||||
trusted bool
|
||||
}{name: name, trusted: entry.trusted})
|
||||
}
|
||||
}
|
||||
if err := tw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
headers := map[string]string{
|
||||
xhttp.AmzSnowballExtract: "true",
|
||||
xhttp.MinIOSourceReplicationRequest: "true",
|
||||
xhttp.MinIOSourceETag: sourceETag,
|
||||
}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
trailer bool
|
||||
}{
|
||||
{name: "signed-v4"},
|
||||
{name: "streaming-unsigned-trailer", trailer: true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
var req *http.Request
|
||||
var err error
|
||||
if test.trailer {
|
||||
req, err = newStreamingUnsignedTrailerRequest(http.MethodPut,
|
||||
getPutObjectURL("", bucketName, "snowball.tar"), body.Bytes(), UTCNow())
|
||||
if err == nil {
|
||||
for name, value := range headers {
|
||||
req.Header.Set(name, value)
|
||||
}
|
||||
err = signRequestV4(req, creds.AccessKey, creds.SecretKey)
|
||||
}
|
||||
} else {
|
||||
req, err = newTestSignedRequestV4(http.MethodPut, getPutObjectURL("", bucketName, "snowball.tar"),
|
||||
int64(body.Len()), bytes.NewReader(body.Bytes()), creds.AccessKey, creds.SecretKey, headers)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: Snowball PUT status %d: %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
for _, object := range objects {
|
||||
info, err := obj.GetObjectInfo(t.Context(), bucketName, object.name, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("%s: get %s: %v", instanceType, object.name, err)
|
||||
}
|
||||
if object.trusted && info.ETag != sourceETag {
|
||||
t.Errorf("%s: trusted entry %s ETag = %q, want source ETag", instanceType, object.name, info.ETag)
|
||||
}
|
||||
if !object.trusted && info.ETag == sourceETag {
|
||||
t.Errorf("%s: untrusted entry %s preserved source ETag", instanceType, object.name)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPISnowballInheritsBucketEncryption(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPISnowballInheritsBucketEncryption,
|
||||
})
|
||||
}
|
||||
|
||||
func testAPISnowballInheritsBucketEncryption(obj ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
previousKMS := GlobalKMS
|
||||
GlobalKMS = kms.NewStub("snowball-default-encryption")
|
||||
defer func() { GlobalKMS = previousKMS }()
|
||||
sseXML := []byte(`<ServerSideEncryptionConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Rule><ApplyServerSideEncryptionByDefault><SSEAlgorithm>AES256</SSEAlgorithm></ApplyServerSideEncryptionByDefault></Rule></ServerSideEncryptionConfiguration>`)
|
||||
if _, err := globalBucketMetadataSys.Update(t.Context(), bucketName, bucketSSEConfig, sseXML); err != nil {
|
||||
t.Fatalf("%s: configure bucket encryption: %v", instanceType, err)
|
||||
}
|
||||
|
||||
var body bytes.Buffer
|
||||
tw := tar.NewWriter(&body)
|
||||
objects := []string{"encrypted/one", "encrypted/two"}
|
||||
for _, object := range objects {
|
||||
data := []byte("snowball bucket encryption " + object)
|
||||
if err := tw.WriteHeader(&tar.Header{Name: object, Mode: 0o600, Size: int64(len(data))}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := tw.Write(data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if err := tw.Close(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
req, err := newTestSignedRequestV4(http.MethodPut, getPutObjectURL("", bucketName, "encrypted-snowball.tar"),
|
||||
int64(body.Len()), bytes.NewReader(body.Bytes()), credentials.AccessKey, credentials.SecretKey,
|
||||
map[string]string{xhttp.AmzSnowballExtract: "true"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: Snowball PUT status %d: %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
for _, object := range objects {
|
||||
info, err := obj.GetObjectInfo(t.Context(), bucketName, object, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("%s: get %s: %v", instanceType, object, err)
|
||||
}
|
||||
if _, encrypted := crypto.IsEncrypted(info.UserDefined); !encrypted {
|
||||
t.Errorf("%s: extracted entry %s did not inherit bucket encryption", instanceType, object)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func newSnowballReplicationTrustUser(t *testing.T, instanceType, bucketName, allowedPrefix string) auth.Credentials {
|
||||
t.Helper()
|
||||
ctx := t.Context()
|
||||
accessKey, secretKey, err := auth.GenerateCredentials()
|
||||
if err != nil {
|
||||
t.Fatalf("%s: generate credentials: %v", instanceType, err)
|
||||
}
|
||||
creds := auth.Credentials{AccessKey: accessKey, SecretKey: secretKey}
|
||||
if _, err = globalIAMSys.CreateUser(ctx, creds.AccessKey, madmin.AddOrUpdateUserReq{
|
||||
SecretKey: creds.SecretKey,
|
||||
Status: madmin.AccountEnabled,
|
||||
}); err != nil {
|
||||
t.Fatalf("%s: create Snowball user: %v", instanceType, err)
|
||||
}
|
||||
|
||||
policyJSON := `{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:PutObject"],
|
||||
"Resource": ["arn:aws:s3:::` + bucketName + `/*"]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:ReplicateObject"],
|
||||
"Resource": ["arn:aws:s3:::` + bucketName + `/` + allowedPrefix + `*"]
|
||||
}
|
||||
]
|
||||
}`
|
||||
parsed, err := policy.ParseConfig(strings.NewReader(policyJSON))
|
||||
if err != nil {
|
||||
t.Fatalf("%s: parse Snowball policy: %v", instanceType, err)
|
||||
}
|
||||
policyName := "snowball-replication-trust-" + mustGetUUID()
|
||||
if _, err = globalIAMSys.SetPolicy(ctx, policyName, *parsed); err != nil {
|
||||
t.Fatalf("%s: install Snowball policy: %v", instanceType, err)
|
||||
}
|
||||
if _, err = globalIAMSys.PolicyDBSet(ctx, creds.AccessKey, policyName, regUser, false); err != nil {
|
||||
t.Fatalf("%s: attach Snowball policy: %v", instanceType, err)
|
||||
}
|
||||
return creds
|
||||
}
|
||||
|
||||
func TestAPICopyObjectMarkerOnlyDoesNotCopyCiphertext(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPICopyObjectMarkerOnlyDoesNotCopyCiphertext,
|
||||
})
|
||||
}
|
||||
|
||||
func testAPICopyObjectMarkerOnlyDoesNotCopyCiphertext(obj ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
previousTLS := globalIsTLS
|
||||
globalIsTLS = true
|
||||
defer func() { globalIsTLS = previousTLS }()
|
||||
|
||||
key := bytes.Repeat([]byte{0x57}, 32)
|
||||
keyMD5 := md5.Sum(key)
|
||||
data := bytes.Repeat([]byte("copy marker-only plaintext "), 256)
|
||||
sseHeaders := map[string]string{
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(key),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(keyMD5[:]),
|
||||
}
|
||||
srcObject := "replication-trust/copy-ssec-source"
|
||||
dstObject := "replication-trust/copy-marker-only"
|
||||
putCopyChecksumSource(t, apiRouter, credentials, bucketName, srcObject, data, sseHeaders)
|
||||
|
||||
replicator := newObjectAttributesAuthzUser(t, instanceType, bucketName,
|
||||
`"s3:GetObject","s3:PutObject","s3:ReplicateObject"`)
|
||||
headers := map[string]string{
|
||||
xhttp.AmzCopySource: url.QueryEscape(SlashSeparator + bucketName + SlashSeparator + srcObject),
|
||||
xhttp.MinIOSourceReplicationRequest: "true",
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerKey: base64.StdEncoding.EncodeToString(key),
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerKeyMD5: base64.StdEncoding.EncodeToString(keyMD5[:]),
|
||||
}
|
||||
req, err := newTestSignedRequestV4(http.MethodPut, getCopyObjectURL("", bucketName, dstObject), 0, nil,
|
||||
replicator.AccessKey, replicator.SecretKey, headers)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: CopyObject status %d: %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
assertObjectContents(t, obj, bucketName, dstObject, data)
|
||||
}
|
||||
|
||||
func TestAPIDeleteObjectReplicationTrust(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPIDeleteObjectReplicationTrust,
|
||||
})
|
||||
}
|
||||
|
||||
func testAPIDeleteObjectReplicationTrust(obj ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, _ auth.Credentials, t *testing.T,
|
||||
) {
|
||||
deleteOnly := newObjectAttributesAuthzUser(t, instanceType, bucketName, `"s3:DeleteObject"`)
|
||||
replicator := newObjectAttributesAuthzUser(t, instanceType, bucketName, `"s3:DeleteObject","s3:ReplicateDelete"`)
|
||||
payload := []byte("delete replication trust")
|
||||
|
||||
put := func(t *testing.T, object string) {
|
||||
t.Helper()
|
||||
if _, err := obj.PutObject(t.Context(), bucketName, object,
|
||||
mustGetPutObjReader(t, bytes.NewReader(payload), int64(len(payload)), "", ""), ObjectOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
remove := func(t *testing.T, object string, creds auth.Credentials, versionID string, deleteMarker, check bool) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
headers := map[string]string{
|
||||
xhttp.MinIOSourceReplicationRequest: "true",
|
||||
xhttp.AmzBucketReplicationStatus: "REPLICA",
|
||||
}
|
||||
if deleteMarker {
|
||||
headers[xhttp.MinIOSourceDeleteMarker] = "true"
|
||||
}
|
||||
if check {
|
||||
headers[xhttp.MinIOSourceReplicationCheck] = "true"
|
||||
}
|
||||
target := getDeleteObjectURL("", bucketName, object)
|
||||
if versionID != "" {
|
||||
target += "?" + url.Values{xhttp.VersionID: {versionID}}.Encode()
|
||||
}
|
||||
req, err := newTestSignedRequestV4(http.MethodDelete, target,
|
||||
0, nil, creds.AccessKey, creds.SecretKey, headers)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
t.Run("replica status without ReplicateDelete is denied", func(t *testing.T) {
|
||||
object := "replication-trust/delete-denied"
|
||||
put(t, object)
|
||||
if rec := remove(t, object, deleteOnly, "", false, false); rec.Code != http.StatusForbidden {
|
||||
t.Fatalf("status %d, want 403: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if _, err := obj.GetObjectInfo(t.Context(), bucketName, object, ObjectOptions{}); err != nil {
|
||||
t.Fatalf("denied delete removed object: %v", err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("trusted replica delete remains supported", func(t *testing.T) {
|
||||
object := "replication-trust/delete-allowed"
|
||||
put(t, object)
|
||||
if rec := remove(t, object, replicator, "", false, false); rec.Code != http.StatusNoContent {
|
||||
t.Fatalf("status %d, want 204: %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
|
||||
for _, shape := range []struct {
|
||||
name string
|
||||
deleteMarker bool
|
||||
}{
|
||||
{name: "delete-marker", deleteMarker: true},
|
||||
{name: "version-purge"},
|
||||
} {
|
||||
t.Run("validity check/"+shape.name, func(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
creds auth.Credentials
|
||||
wantStatus int
|
||||
}{
|
||||
{name: "requires ReplicateDelete", creds: deleteOnly, wantStatus: http.StatusForbidden},
|
||||
{name: "succeeds for replicator", creds: replicator, wantStatus: http.StatusBadRequest},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
object := "replication-trust/delete-check-" + shape.name + "-" + strconv.Itoa(test.wantStatus)
|
||||
put(t, object)
|
||||
if rec := remove(t, object, test.creds, mustGetUUID(), shape.deleteMarker, true); rec.Code != test.wantStatus {
|
||||
t.Fatalf("status %d, want %d: %s", rec.Code, test.wantStatus, rec.Body.String())
|
||||
}
|
||||
if _, err := obj.GetObjectInfo(t.Context(), bucketName, object, ObjectOptions{}); err != nil {
|
||||
t.Fatalf("replication validity check removed object: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPISSECMultipartReplicationTrust(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPISSECMultipartReplicationTrust,
|
||||
})
|
||||
}
|
||||
|
||||
func testAPISSECMultipartReplicationTrust(obj ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
previousTLS := globalIsTLS
|
||||
globalIsTLS = true
|
||||
defer func() { globalIsTLS = previousTLS }()
|
||||
|
||||
replicator := newObjectAttributesAuthzUser(t, instanceType, bucketName, `"s3:PutObject","s3:GetObject","s3:ReplicateObject"`)
|
||||
putOnly := newObjectAttributesAuthzUser(t, instanceType, bucketName, `"s3:PutObject"`)
|
||||
key := bytes.Repeat([]byte{0x42}, 32)
|
||||
keyMD5 := md5.Sum(key)
|
||||
data := bytes.Repeat([]byte("trusted multipart replication "), 4096)
|
||||
sseHeaders := map[string]string{
|
||||
xhttp.AmzServerSideEncryptionCustomerAlgorithm: xhttp.AmzEncryptionAES,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey: base64.StdEncoding.EncodeToString(key),
|
||||
xhttp.AmzServerSideEncryptionCustomerKeyMD5: base64.StdEncoding.EncodeToString(keyMD5[:]),
|
||||
}
|
||||
|
||||
// A marker alone must not let an ordinary writer upload raw bytes into an
|
||||
// SSE-C multipart upload without presenting the customer key.
|
||||
fakeObject := "replication-trust/ssec-multipart-fake"
|
||||
fakeNewReq, err := newTestSignedRequestV4(http.MethodPost, getNewMultipartURL("", bucketName, fakeObject),
|
||||
0, nil, credentials.AccessKey, credentials.SecretKey, sseHeaders)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fakeNewRec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(fakeNewRec, fakeNewReq)
|
||||
if fakeNewRec.Code != http.StatusOK {
|
||||
t.Fatalf("fake-path NewMultipart status %d: %s", fakeNewRec.Code, fakeNewRec.Body.String())
|
||||
}
|
||||
var fakeInit InitiateMultipartUploadResponse
|
||||
if err = xmlDecoder(fakeNewRec.Body, &fakeInit, int64(fakeNewRec.Body.Len())); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fakePartReq, err := newTestSignedRequestV4(http.MethodPut,
|
||||
getPutObjectPartURL("", bucketName, fakeObject, fakeInit.UploadID, "1"), int64(len(data)), bytes.NewReader(data),
|
||||
putOnly.AccessKey, putOnly.SecretKey, map[string]string{xhttp.MinIOSourceReplicationRequest: "true"})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
fakePartRec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(fakePartRec, fakePartReq)
|
||||
if fakePartRec.Code != http.StatusBadRequest {
|
||||
t.Fatalf("fake marker PutPart status %d, want 400: %s", fakePartRec.Code, fakePartRec.Body.String())
|
||||
}
|
||||
|
||||
object := "replication-trust/ssec-multipart"
|
||||
|
||||
// Create the source as a real SSE-C multipart object so the encrypted part
|
||||
// layout and metadata match what the replication worker reads.
|
||||
newReq, err := newTestSignedRequestV4(http.MethodPost, getNewMultipartURL("", bucketName, object),
|
||||
0, nil, credentials.AccessKey, credentials.SecretKey, sseHeaders)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
newRec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(newRec, newReq)
|
||||
if newRec.Code != http.StatusOK {
|
||||
t.Fatalf("source NewMultipart status %d: %s", newRec.Code, newRec.Body.String())
|
||||
}
|
||||
var sourceInit InitiateMultipartUploadResponse
|
||||
if err = xmlDecoder(newRec.Body, &sourceInit, int64(newRec.Body.Len())); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
partReq, err := newTestSignedRequestV4(http.MethodPut,
|
||||
getPutObjectPartURL("", bucketName, object, sourceInit.UploadID, "1"), int64(len(data)), bytes.NewReader(data),
|
||||
credentials.AccessKey, credentials.SecretKey, sseHeaders)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
partRec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(partRec, partReq)
|
||||
if partRec.Code != http.StatusOK {
|
||||
t.Fatalf("source PutPart status %d: %s", partRec.Code, partRec.Body.String())
|
||||
}
|
||||
sourcePartETag := canonicalizeETag(partRec.Header()[xhttp.ETag][0])
|
||||
sourceCompleteBody, err := xml.Marshal(CompleteMultipartUpload{Parts: []CompletePart{{PartNumber: 1, ETag: sourcePartETag}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
completeReq, err := newTestSignedRequestV4(http.MethodPost,
|
||||
getCompleteMultipartUploadURL("", bucketName, object, sourceInit.UploadID), int64(len(sourceCompleteBody)),
|
||||
bytes.NewReader(sourceCompleteBody), credentials.AccessKey, credentials.SecretKey, sseHeaders)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
completeRec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(completeRec, completeReq)
|
||||
if completeRec.Code != http.StatusOK {
|
||||
t.Fatalf("source Complete status %d: %s", completeRec.Code, completeRec.Body.String())
|
||||
}
|
||||
|
||||
gr, err := obj.GetObjectNInfo(t.Context(), bucketName, object, nil, http.Header{}, ObjectOptions{ReplicationRequest: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
sourceInfo := gr.ObjInfo
|
||||
rawPart, err := io.ReadAll(gr)
|
||||
gr.Close()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(rawPart) == 0 || bytes.Equal(rawPart, data) {
|
||||
t.Fatal("source replication read did not return encrypted bytes")
|
||||
}
|
||||
|
||||
replicationOpts, isMP, err := putReplicationOpts(t.Context(), "", sourceInfo)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !isMP {
|
||||
t.Fatal("SSE-C multipart source was not recognized as multipart")
|
||||
}
|
||||
replicationOpts.Internal.SourceMTime = time.Time{}
|
||||
replicationHeaders := make(map[string]string)
|
||||
for name, values := range replicationOpts.Header() {
|
||||
if len(values) > 0 {
|
||||
replicationHeaders[name] = values[0]
|
||||
}
|
||||
}
|
||||
|
||||
// Start the destination upload over the same key. The existing object stays
|
||||
// readable until Complete, so buffering rawPart above mirrors a remote peer.
|
||||
replNewReq, err := newTestSignedRequestV4(http.MethodPost, getNewMultipartURL("", bucketName, object),
|
||||
0, nil, replicator.AccessKey, replicator.SecretKey, replicationHeaders)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replNewRec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(replNewRec, replNewReq)
|
||||
if replNewRec.Code != http.StatusOK {
|
||||
t.Fatalf("replica NewMultipart status %d: %s", replNewRec.Code, replNewRec.Body.String())
|
||||
}
|
||||
var replicaInit InitiateMultipartUploadResponse
|
||||
if err = xmlDecoder(replNewRec.Body, &replicaInit, int64(replNewRec.Body.Len())); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
replPartHeaders := map[string]string{xhttp.MinIOSourceReplicationRequest: "true"}
|
||||
replPartReq, err := newTestSignedRequestV4(http.MethodPut,
|
||||
getPutObjectPartURL("", bucketName, object, replicaInit.UploadID, "1"), int64(len(rawPart)), bytes.NewReader(rawPart),
|
||||
replicator.AccessKey, replicator.SecretKey, replPartHeaders)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replPartRec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(replPartRec, replPartReq)
|
||||
if replPartRec.Code != http.StatusOK {
|
||||
t.Fatalf("replica PutPart status %d: %s", replPartRec.Code, replPartRec.Body.String())
|
||||
}
|
||||
replPartETag := canonicalizeETag(replPartRec.Header()[xhttp.ETag][0])
|
||||
replCompleteBody, err := xml.Marshal(CompleteMultipartUpload{Parts: []CompletePart{{PartNumber: 1, ETag: replPartETag}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actualSize, err := sourceInfo.GetActualSize()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replCompleteHeaders := map[string]string{
|
||||
xhttp.MinIOSourceReplicationRequest: "true",
|
||||
xhttp.MinIOSourceMTime: sourceInfo.ModTime.Format(time.RFC3339Nano),
|
||||
xhttp.MinIOSourceETag: sourceInfo.ETag,
|
||||
xhttp.MinIOReplicationActualObjectSize: strconv.FormatInt(actualSize, 10),
|
||||
}
|
||||
replCompleteReq, err := newTestSignedRequestV4(http.MethodPost,
|
||||
getCompleteMultipartUploadURL("", bucketName, object, replicaInit.UploadID), int64(len(replCompleteBody)),
|
||||
bytes.NewReader(replCompleteBody), replicator.AccessKey, replicator.SecretKey, replCompleteHeaders)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
replCompleteRec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(replCompleteRec, replCompleteReq)
|
||||
if replCompleteRec.Code != http.StatusOK {
|
||||
t.Fatalf("replica Complete status %d: %s", replCompleteRec.Code, replCompleteRec.Body.String())
|
||||
}
|
||||
|
||||
getReq, err := newTestSignedRequestV4(http.MethodGet, getGetObjectURL("", bucketName, object),
|
||||
0, nil, credentials.AccessKey, credentials.SecretKey, sseHeaders)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
getRec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(getRec, getReq)
|
||||
if getRec.Code != http.StatusOK {
|
||||
t.Fatalf("GET replicated object status %d: %s", getRec.Code, getRec.Body.String())
|
||||
}
|
||||
if !bytes.Equal(getRec.Body.Bytes(), data) {
|
||||
t.Fatal("replicated SSE-C multipart object did not decrypt to source plaintext")
|
||||
}
|
||||
}
|
||||
+15
-3
@@ -48,6 +48,7 @@ import (
|
||||
"github.com/minio/minio/internal/color"
|
||||
"github.com/minio/minio/internal/config"
|
||||
"github.com/minio/minio/internal/config/api"
|
||||
"github.com/minio/minio/internal/config/notify"
|
||||
"github.com/minio/minio/internal/handlers"
|
||||
"github.com/minio/minio/internal/hash/sha256"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
@@ -535,6 +536,15 @@ func configRetriableErrors(err error) bool {
|
||||
notInitialized
|
||||
}
|
||||
|
||||
func fatalServerConfigError(err error) bool {
|
||||
var configErr config.Err
|
||||
if errors.As(err, &configErr) {
|
||||
return true
|
||||
}
|
||||
var migrationErr *notify.LegacyDatabaseTargetError
|
||||
return errors.As(err, &migrationErr)
|
||||
}
|
||||
|
||||
func bootstrapTraceMsg(msg string) {
|
||||
info := madmin.TraceInfo{
|
||||
TraceType: madmin.TraceBootstrap,
|
||||
@@ -632,7 +642,10 @@ func initConfigSubsystem(ctx context.Context, newObject ObjectLayer) error {
|
||||
|
||||
// Initialize config system.
|
||||
if err := globalConfigSys.Init(newObject); err != nil {
|
||||
if configRetriableErrors(err) {
|
||||
var migrationErr *notify.LegacyDatabaseTargetError
|
||||
// Do not use fatalServerConfigError here: existing config.Err values
|
||||
// retain the historical log-and-continue behavior at this boundary.
|
||||
if configRetriableErrors(err) || errors.As(err, &migrationErr) {
|
||||
return fmt.Errorf("Unable to initialize config system: %w", err)
|
||||
}
|
||||
|
||||
@@ -965,10 +978,9 @@ func serverMain(ctx *cli.Context) {
|
||||
var err error
|
||||
bootstrapTrace("initServerConfig", func() {
|
||||
if err = initServerConfig(GlobalContext, newObject); err != nil {
|
||||
var cerr config.Err
|
||||
// For any config error, we don't need to drop into safe-mode
|
||||
// instead its a user error and should be fixed by user.
|
||||
if errors.As(err, &cerr) {
|
||||
if fatalServerConfigError(err) {
|
||||
logger.FatalIf(err, "Unable to initialize the server")
|
||||
}
|
||||
|
||||
|
||||
@@ -46,7 +46,9 @@ func oldLinux() bool {
|
||||
|
||||
func setMaxResources(ctx serverCtxt) (err error) {
|
||||
// Set the Go runtime max threads threshold to 90% of kernel setting.
|
||||
//nolint:staticcheck // Linux implementations can fail; BSD stubs return a constant nil error.
|
||||
sysMaxThreads, err := sys.GetMaxThreads()
|
||||
//nolint:staticcheck // Keep the shared cross-platform error handling.
|
||||
if err == nil {
|
||||
minioMaxThreads := (sysMaxThreads * 90) / 100
|
||||
// Only set max threads if it is greater than the default one
|
||||
|
||||
@@ -0,0 +1,190 @@
|
||||
// Copyright (c) 2015-2026 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio/internal/auth"
|
||||
)
|
||||
|
||||
func TestPeerBucketAdoptionPreservesLockAndVersioningConfigs(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testPeerBucketAdoptionPreservesLockAndVersioningConfigs,
|
||||
makeBucketOptions: MakeBucketOptions{LockEnabled: true},
|
||||
})
|
||||
}
|
||||
|
||||
func testPeerBucketAdoptionPreservesLockAndVersioningConfigs(_ ObjectLayer, instanceType, bucketName string,
|
||||
_ http.Handler, _ auth.Credentials, t *testing.T,
|
||||
) {
|
||||
objectLockXML := []byte(`<ObjectLockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><ObjectLockEnabled>Enabled</ObjectLockEnabled><Rule><DefaultRetention><Mode>GOVERNANCE</Mode><Days>30</Days></DefaultRetention></Rule></ObjectLockConfiguration>`)
|
||||
versioningXML := []byte(`<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Status>Enabled</Status><ExcludeFolders>true</ExcludeFolders><ExcludedPrefixes><Prefix>temporary/</Prefix></ExcludedPrefixes></VersioningConfiguration>`)
|
||||
if _, err := globalBucketMetadataSys.Update(t.Context(), bucketName, objectLockConfig, objectLockXML); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := globalBucketMetadataSys.Update(t.Context(), bucketName, bucketVersioningConfig, versioningXML); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := globalBucketMetadataSys.Get(bucketName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if err := globalSiteReplicationSys.PeerBucketMakeWithVersioningHandler(t.Context(), bucketName, MakeBucketOptions{
|
||||
CreatedAt: before.Created.Add(-time.Hour),
|
||||
LockEnabled: true,
|
||||
}); err != nil {
|
||||
t.Fatalf("%s: adopting existing bucket failed: %v", instanceType, err)
|
||||
}
|
||||
after, err := globalBucketMetadataSys.Get(bucketName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(after.ObjectLockConfigXML, before.ObjectLockConfigXML) || !after.ObjectLockConfigUpdatedAt.Equal(before.ObjectLockConfigUpdatedAt) {
|
||||
t.Fatalf("%s: Object Lock config changed during adoption", instanceType)
|
||||
}
|
||||
if !bytes.Equal(after.VersioningConfigXML, before.VersioningConfigXML) || !after.VersioningConfigUpdatedAt.Equal(before.VersioningConfigUpdatedAt) {
|
||||
t.Fatalf("%s: versioning config changed during adoption", instanceType)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerBucketAdoptionBootstrapsMissingConfigs(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testPeerBucketAdoptionBootstrapsMissingConfigs,
|
||||
})
|
||||
}
|
||||
|
||||
func TestPeerBucketAdoptionPreservesCustomVersioningWhenEnablingLock(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testPeerBucketAdoptionPreservesCustomVersioningWhenEnablingLock,
|
||||
})
|
||||
}
|
||||
|
||||
func testPeerBucketAdoptionPreservesCustomVersioningWhenEnablingLock(_ ObjectLayer, instanceType, bucketName string,
|
||||
_ http.Handler, _ auth.Credentials, t *testing.T,
|
||||
) {
|
||||
versioningXML := []byte(`<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Status>Enabled</Status><ExcludeFolders>true</ExcludeFolders><ExcludedPrefixes><Prefix>temporary/</Prefix></ExcludedPrefixes></VersioningConfiguration>`)
|
||||
if _, err := globalBucketMetadataSys.Update(t.Context(), bucketName, bucketVersioningConfig, versioningXML); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := globalBucketMetadataSys.Get(bucketName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := globalSiteReplicationSys.PeerBucketMakeWithVersioningHandler(t.Context(), bucketName, MakeBucketOptions{
|
||||
CreatedAt: before.Created,
|
||||
LockEnabled: true,
|
||||
}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, err := globalBucketMetadataSys.Get(bucketName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(after.VersioningConfigXML, before.VersioningConfigXML) || !after.VersioningConfigUpdatedAt.Equal(before.VersioningConfigUpdatedAt) {
|
||||
t.Fatalf("%s: custom versioning changed while enabling Object Lock", instanceType)
|
||||
}
|
||||
if !bytes.Equal(after.ObjectLockConfigXML, enabledBucketObjectLockConfig) {
|
||||
t.Fatalf("%s: Object Lock was not bootstrapped", instanceType)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerBucketAdoptionEnablesSuspendedVersioning(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testPeerBucketAdoptionEnablesSuspendedVersioning,
|
||||
})
|
||||
}
|
||||
|
||||
func testPeerBucketAdoptionEnablesSuspendedVersioning(_ ObjectLayer, instanceType, bucketName string,
|
||||
_ http.Handler, _ auth.Credentials, t *testing.T,
|
||||
) {
|
||||
suspended := []byte(`<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Status>Suspended</Status></VersioningConfiguration>`)
|
||||
if _, err := globalBucketMetadataSys.Update(t.Context(), bucketName, bucketVersioningConfig, suspended); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
before, err := globalBucketMetadataSys.Get(bucketName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err := globalSiteReplicationSys.PeerBucketMakeWithVersioningHandler(t.Context(), bucketName, MakeBucketOptions{CreatedAt: before.Created}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
after, err := globalBucketMetadataSys.Get(bucketName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if after.versioningConfig == nil || !after.versioningConfig.Enabled() {
|
||||
t.Fatalf("%s: versioning remained disabled: %q", instanceType, after.VersioningConfigXML)
|
||||
}
|
||||
if !after.VersioningConfigUpdatedAt.After(before.VersioningConfigUpdatedAt) {
|
||||
t.Fatalf("%s: versioning update time = %v, want after %v", instanceType, after.VersioningConfigUpdatedAt, before.VersioningConfigUpdatedAt)
|
||||
}
|
||||
}
|
||||
|
||||
func TestEnablePeerBucketVersioningRepairsInvalidConfig(t *testing.T) {
|
||||
meta := newBucketMetadata("bucket")
|
||||
meta.Created = time.Date(2026, time.August, 29, 8, 0, 0, 0, time.UTC)
|
||||
meta.VersioningConfigXML = []byte(`<VersioningConfiguration>`)
|
||||
if err := enablePeerBucketVersioning(&meta); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(meta.VersioningConfigXML, enabledBucketVersioningConfig) || meta.VersioningConfigUpdatedAt.IsZero() {
|
||||
t.Fatalf("invalid versioning was not repaired: xml=%q updatedAt=%v", meta.VersioningConfigXML, meta.VersioningConfigUpdatedAt)
|
||||
}
|
||||
}
|
||||
|
||||
func testPeerBucketAdoptionBootstrapsMissingConfigs(_ ObjectLayer, instanceType, bucketName string,
|
||||
_ http.Handler, _ auth.Credentials, t *testing.T,
|
||||
) {
|
||||
before, err := globalBucketMetadataSys.Get(bucketName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(before.ObjectLockConfigXML) != 0 || len(before.VersioningConfigXML) != 0 {
|
||||
t.Fatalf("%s: invalid bootstrap precondition", instanceType)
|
||||
}
|
||||
if err := globalSiteReplicationSys.PeerBucketMakeWithVersioningHandler(t.Context(), bucketName, MakeBucketOptions{
|
||||
CreatedAt: before.Created,
|
||||
LockEnabled: true,
|
||||
}); err != nil {
|
||||
t.Fatalf("%s: adopting existing bucket failed: %v", instanceType, err)
|
||||
}
|
||||
after, err := globalBucketMetadataSys.Get(bucketName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !bytes.Equal(after.ObjectLockConfigXML, enabledBucketObjectLockConfig) || !bytes.Equal(after.VersioningConfigXML, enabledBucketVersioningConfig) {
|
||||
t.Fatalf("%s: missing bootstrap configs: objectLock=%q versioning=%q", instanceType, after.ObjectLockConfigXML, after.VersioningConfigXML)
|
||||
}
|
||||
if !after.ObjectLockConfigUpdatedAt.Equal(before.Created) || !after.VersioningConfigUpdatedAt.Equal(before.Created) {
|
||||
t.Fatalf("%s: bootstrap timestamps = (%v, %v), want %v", instanceType,
|
||||
after.ObjectLockConfigUpdatedAt, after.VersioningConfigUpdatedAt, before.Created)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,266 @@
|
||||
// Copyright (c) 2015-2026 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/minio/internal/auth"
|
||||
"github.com/minio/mux"
|
||||
)
|
||||
|
||||
func TestSRBucketObjectLockMetadata(t *testing.T) {
|
||||
updatedAt := time.Date(2026, time.August, 29, 8, 0, 0, 0, time.UTC)
|
||||
current := "current"
|
||||
legacy := "legacy"
|
||||
|
||||
event := newSRBucketObjectLockMeta("bucket", ¤t, updatedAt)
|
||||
if event.Type != madmin.SRBucketMetaTypeObjectLockConfig || event.Bucket != "bucket" ||
|
||||
event.ObjectLockConfig == nil || *event.ObjectLockConfig != current || event.Tags != nil || !event.UpdatedAt.Equal(updatedAt) {
|
||||
t.Fatalf("unexpected Object Lock event: %#v", event)
|
||||
}
|
||||
|
||||
encoded, err := json.Marshal(event)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var roundTrip madmin.SRBucketMeta
|
||||
if err := json.Unmarshal(encoded, &roundTrip); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if roundTrip.ObjectLockConfig == nil || *roundTrip.ObjectLockConfig != current || roundTrip.Tags != nil {
|
||||
t.Fatalf("unexpected JSON round trip: %#v", roundTrip)
|
||||
}
|
||||
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
item madmin.SRBucketMeta
|
||||
want *string
|
||||
}{
|
||||
{name: "current", item: madmin.SRBucketMeta{ObjectLockConfig: ¤t}, want: ¤t},
|
||||
{name: "legacy", item: madmin.SRBucketMeta{Tags: &legacy}, want: &legacy},
|
||||
{name: "current wins", item: madmin.SRBucketMeta{ObjectLockConfig: ¤t, Tags: &legacy}, want: ¤t},
|
||||
{name: "missing", item: madmin.SRBucketMeta{}},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got := srObjectLockPayload(test.item)
|
||||
if test.want == nil {
|
||||
if got != nil {
|
||||
t.Fatalf("payload = %q, want nil", *got)
|
||||
}
|
||||
return
|
||||
}
|
||||
if got == nil || *got != *test.want {
|
||||
t.Fatalf("payload = %v, want %q", got, *test.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPeerBucketObjectLockMetadataCurrentAndLegacyPayloads(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testPeerBucketObjectLockMetadataCurrentAndLegacyPayloads,
|
||||
makeBucketOptions: MakeBucketOptions{LockEnabled: true},
|
||||
})
|
||||
}
|
||||
|
||||
func applySRBucketMetaViaAdmin(t *testing.T, credentials auth.Credentials, item madmin.SRBucketMeta) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
body, err := json.Marshal(item)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
adminRouter := mux.NewRouter()
|
||||
registerAdminRouter(adminRouter, true)
|
||||
path := adminPathPrefix + adminAPIVersionPrefix + "/site-replication/peer/bucket-meta"
|
||||
req, err := newTestSignedRequestV4(http.MethodPut, path, int64(len(body)), bytes.NewReader(body),
|
||||
credentials.AccessKey, credentials.SecretKey, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
adminRouter.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func testPeerBucketObjectLockMetadataCurrentAndLegacyPayloads(_ ObjectLayer, instanceType, bucketName string,
|
||||
_ http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
apply := func(item madmin.SRBucketMeta, wantDays uint64) {
|
||||
t.Helper()
|
||||
rec := applySRBucketMetaViaAdmin(t, credentials, item)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: admin Object Lock apply returned %d: %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
config, _, err := globalBucketMetadataSys.GetObjectLockConfig(bucketName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if config.Rule == nil || config.Rule.DefaultRetention.Mode != "GOVERNANCE" ||
|
||||
config.Rule.DefaultRetention.Days == nil || *config.Rule.DefaultRetention.Days != wantDays {
|
||||
t.Fatalf("%s: persisted Object Lock config = %s, want GOVERNANCE/%d days", instanceType, config, wantDays)
|
||||
}
|
||||
}
|
||||
|
||||
config30 := base64.StdEncoding.EncodeToString([]byte(`<ObjectLockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><ObjectLockEnabled>Enabled</ObjectLockEnabled><Rule><DefaultRetention><Mode>GOVERNANCE</Mode><Days>30</Days></DefaultRetention></Rule></ObjectLockConfiguration>`))
|
||||
apply(newSRBucketObjectLockMeta(bucketName, &config30, UTCNow().Add(time.Hour)), 30)
|
||||
|
||||
config45 := base64.StdEncoding.EncodeToString([]byte(`<ObjectLockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><ObjectLockEnabled>Enabled</ObjectLockEnabled><Rule><DefaultRetention><Mode>GOVERNANCE</Mode><Days>45</Days></DefaultRetention></Rule></ObjectLockConfiguration>`))
|
||||
apply(madmin.SRBucketMeta{
|
||||
Type: madmin.SRBucketMetaTypeObjectLockConfig,
|
||||
Bucket: bucketName,
|
||||
Tags: &config45,
|
||||
UpdatedAt: UTCNow().Add(2 * time.Hour),
|
||||
}, 45)
|
||||
}
|
||||
|
||||
func TestPeerBucketObjectLockMetadataWithoutLockEnabled(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testPeerBucketObjectLockMetadataWithoutLockEnabled,
|
||||
})
|
||||
}
|
||||
|
||||
func testPeerBucketObjectLockMetadataWithoutLockEnabled(_ ObjectLayer, instanceType, bucketName string,
|
||||
_ http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
config := base64.StdEncoding.EncodeToString([]byte(`<ObjectLockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><ObjectLockEnabled>Enabled</ObjectLockEnabled><Rule><DefaultRetention><Mode>GOVERNANCE</Mode><Days>30</Days></DefaultRetention></Rule></ObjectLockConfiguration>`))
|
||||
item := newSRBucketObjectLockMeta(bucketName, &config, UTCNow().Add(time.Hour))
|
||||
rec := applySRBucketMetaViaAdmin(t, credentials, item)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: admin Object Lock apply returned %d: %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
meta, err := globalBucketMetadataSys.Get(bucketName)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if meta.objectLockConfig == nil || len(meta.VersioningConfigXML) != 0 {
|
||||
t.Fatalf("%s: unlocked bucket metadata = objectLock:%v versioning:%q", instanceType, meta.objectLockConfig, meta.VersioningConfigXML)
|
||||
}
|
||||
}
|
||||
|
||||
func TestHealObjectLockMetadataUsesObjectLockField(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testHealObjectLockMetadataUsesObjectLockField,
|
||||
})
|
||||
}
|
||||
|
||||
func testHealObjectLockMetadataUsesObjectLockField(obj ObjectLayer, instanceType, bucketName string,
|
||||
_ http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
ctx := t.Context()
|
||||
localID := globalDeploymentID()
|
||||
remoteID := "remote-object-lock-heal"
|
||||
updatedAt := UTCNow().Add(time.Hour)
|
||||
createdAt := updatedAt.Add(-time.Hour)
|
||||
config := base64.StdEncoding.EncodeToString([]byte(`<ObjectLockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><ObjectLockEnabled>Enabled</ObjectLockEnabled><Rule><DefaultRetention><Mode>GOVERNANCE</Mode><Days>30</Days></DefaultRetention></Rule></ObjectLockConfiguration>`))
|
||||
|
||||
remoteApplies := make(chan madmin.SRBucketMeta, 1)
|
||||
remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var applied madmin.SRBucketMeta
|
||||
if err := json.NewDecoder(r.Body).Decode(&applied); err != nil {
|
||||
t.Errorf("%s: decode remote apply: %v", instanceType, err)
|
||||
w.WriteHeader(http.StatusBadRequest)
|
||||
return
|
||||
}
|
||||
remoteApplies <- applied
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
defer remote.Close()
|
||||
|
||||
serviceCred, err := auth.CreateCredentials("object-lock-heal-svc", "object-lock-heal-service-secret")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
serviceCred.ParentUser = credentials.AccessKey
|
||||
if _, err = globalIAMSys.store.AddServiceAccount(ctx, serviceCred); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer globalIAMSys.DeleteServiceAccount(ctx, serviceCred.AccessKey, false)
|
||||
|
||||
globalSiteReplicationSys.Lock()
|
||||
oldEnabled := globalSiteReplicationSys.enabled
|
||||
oldState := globalSiteReplicationSys.state
|
||||
globalSiteReplicationSys.enabled = true
|
||||
globalSiteReplicationSys.state = srState{
|
||||
Name: "object-lock-heal-test",
|
||||
ServiceAccountAccessKey: serviceCred.AccessKey,
|
||||
Peers: map[string]madmin.PeerInfo{
|
||||
localID: {Name: "local", DeploymentID: localID},
|
||||
remoteID: {Name: "remote", DeploymentID: remoteID, Endpoint: remote.URL},
|
||||
},
|
||||
}
|
||||
globalSiteReplicationSys.Unlock()
|
||||
defer func() {
|
||||
globalSiteReplicationSys.Lock()
|
||||
globalSiteReplicationSys.enabled = oldEnabled
|
||||
globalSiteReplicationSys.state = oldState
|
||||
globalSiteReplicationSys.Unlock()
|
||||
}()
|
||||
|
||||
status := srStatusInfo{
|
||||
Sites: map[string]madmin.PeerInfo{
|
||||
localID: {Name: "local", DeploymentID: localID},
|
||||
remoteID: {Name: "remote", DeploymentID: remoteID, Endpoint: remote.URL},
|
||||
},
|
||||
BucketStats: map[string]map[string]srBucketStatsSummary{
|
||||
bucketName: {
|
||||
localID: {
|
||||
SRBucketStatsSummary: madmin.SRBucketStatsSummary{OLockConfigMismatch: true},
|
||||
meta: srBucketMetaInfo{SRBucketInfo: madmin.SRBucketInfo{
|
||||
Bucket: bucketName,
|
||||
CreatedAt: createdAt,
|
||||
ObjectLockConfig: &config,
|
||||
ObjectLockConfigUpdatedAt: updatedAt,
|
||||
}, DeploymentID: localID},
|
||||
},
|
||||
remoteID: {
|
||||
SRBucketStatsSummary: madmin.SRBucketStatsSummary{OLockConfigMismatch: true},
|
||||
meta: srBucketMetaInfo{SRBucketInfo: madmin.SRBucketInfo{
|
||||
Bucket: bucketName,
|
||||
CreatedAt: createdAt,
|
||||
}, DeploymentID: remoteID},
|
||||
},
|
||||
},
|
||||
},
|
||||
}
|
||||
if err := globalSiteReplicationSys.healOLockConfigMetadata(ctx, obj, bucketName, status); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
select {
|
||||
case applied := <-remoteApplies:
|
||||
if applied.Type != madmin.SRBucketMetaTypeObjectLockConfig || applied.Bucket != bucketName ||
|
||||
applied.ObjectLockConfig == nil || *applied.ObjectLockConfig != config || applied.Tags != nil || !applied.UpdatedAt.Equal(updatedAt) {
|
||||
t.Fatalf("%s: remote heal apply = %#v", instanceType, applied)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatalf("%s: remote heal did not dispatch Object Lock metadata", instanceType)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,192 @@
|
||||
// Copyright (c) 2015-2026 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful,
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/minio/internal/auth"
|
||||
)
|
||||
|
||||
func TestSiteReplicationStatusAccountsPerSiteAndSurvivesMalformedConfig(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testSiteReplicationStatusAccountsPerSiteAndSurvivesMalformedConfig,
|
||||
})
|
||||
}
|
||||
|
||||
func testSiteReplicationStatusAccountsPerSiteAndSurvivesMalformedConfig(obj ObjectLayer, instanceType, localBucket string,
|
||||
_ http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
ctx := t.Context()
|
||||
remoteBucket := getRandomBucketName()
|
||||
if err := obj.MakeBucket(ctx, remoteBucket, MakeBucketOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remoteBucketMeta, err := loadBucketMetadata(ctx, obj, remoteBucket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
globalBucketMetadataSys.Set(remoteBucket, remoteBucketMeta)
|
||||
globalNotificationSys.LoadBucketMetadata(ctx, remoteBucket)
|
||||
|
||||
tagXML := []byte(`<Tagging><TagSet><Tag><Key>key</Key><Value>value</Value></Tag></TagSet></Tagging>`)
|
||||
versioningXML := []byte(`<VersioningConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Status>Enabled</Status></VersioningConfiguration>`)
|
||||
objectLockXML := []byte(`<ObjectLockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><ObjectLockEnabled>Enabled</ObjectLockEnabled><Rule><DefaultRetention><Mode>GOVERNANCE</Mode><Days>30</Days></DefaultRetention></Rule></ObjectLockConfiguration>`)
|
||||
sseXML := []byte(`<ServerSideEncryptionConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><Rule><ApplyServerSideEncryptionByDefault><SSEAlgorithm>AES256</SSEAlgorithm></ApplyServerSideEncryptionByDefault></Rule></ServerSideEncryptionConfiguration>`)
|
||||
quotaJSON, err := json.Marshal(madmin.BucketQuota{Type: madmin.HardQuota, Quota: 1024})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
policyJSON := []byte(fmt.Sprintf(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":["*"]},"Action":["s3:GetObject"],"Resource":["arn:aws:s3:::%s/*"]}]}`, localBucket))
|
||||
|
||||
for configFile, data := range map[string][]byte{
|
||||
bucketTaggingConfig: tagXML,
|
||||
bucketVersioningConfig: versioningXML,
|
||||
objectLockConfig: objectLockXML,
|
||||
bucketSSEConfig: sseXML,
|
||||
bucketQuotaConfigFile: quotaJSON,
|
||||
bucketPolicyConfig: policyJSON,
|
||||
bucketCorsConfig: []byte(testSiteReplicationCORSDoc),
|
||||
} {
|
||||
if _, err := globalBucketMetadataSys.Update(ctx, localBucket, configFile, data); err != nil {
|
||||
t.Fatalf("%s: update %s: %v", instanceType, configFile, err)
|
||||
}
|
||||
}
|
||||
|
||||
encode := func(data []byte) *string {
|
||||
encoded := base64.StdEncoding.EncodeToString(data)
|
||||
return &encoded
|
||||
}
|
||||
remotePolicy := []byte(fmt.Sprintf(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":["*"]},"Action":["s3:GetObject"],"Resource":["arn:aws:s3:::%s/*"]}]}`, remoteBucket))
|
||||
localMeta, err := globalBucketMetadataSys.Get(localBucket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
remoteInfo := madmin.SRInfo{
|
||||
DeploymentID: "remote-status-accounting",
|
||||
Buckets: map[string]madmin.SRBucketInfo{
|
||||
localBucket: {
|
||||
Bucket: localBucket,
|
||||
CreatedAt: localMeta.Created,
|
||||
},
|
||||
remoteBucket: {
|
||||
Bucket: remoteBucket,
|
||||
CreatedAt: remoteBucketMeta.Created,
|
||||
Tags: encode(tagXML),
|
||||
Versioning: encode(versioningXML),
|
||||
ObjectLockConfig: encode(objectLockXML),
|
||||
SSEConfig: encode(sseXML),
|
||||
QuotaConfig: encode(quotaJSON),
|
||||
Policy: remotePolicy,
|
||||
CorsConfig: encode([]byte(testSiteReplicationCORSDoc)),
|
||||
CorsConfigUpdatedAt: remoteBucketMeta.Created,
|
||||
},
|
||||
},
|
||||
}
|
||||
remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if err := json.NewEncoder(w).Encode(remoteInfo); err != nil {
|
||||
t.Errorf("%s: encode remote metadata: %v", instanceType, err)
|
||||
}
|
||||
}))
|
||||
defer remote.Close()
|
||||
|
||||
serviceCred, err := auth.CreateCredentials("status-accounting-svc", "status-accounting-service-secret")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
serviceCred.ParentUser = credentials.AccessKey
|
||||
if _, err = globalIAMSys.store.AddServiceAccount(ctx, serviceCred); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer globalIAMSys.DeleteServiceAccount(ctx, serviceCred.AccessKey, false)
|
||||
|
||||
localID := globalDeploymentID()
|
||||
remoteID := remoteInfo.DeploymentID
|
||||
globalSiteReplicationSys.Lock()
|
||||
oldEnabled := globalSiteReplicationSys.enabled
|
||||
oldState := globalSiteReplicationSys.state
|
||||
globalSiteReplicationSys.enabled = true
|
||||
globalSiteReplicationSys.state = srState{
|
||||
Name: "status-accounting-test",
|
||||
ServiceAccountAccessKey: serviceCred.AccessKey,
|
||||
Peers: map[string]madmin.PeerInfo{
|
||||
localID: {Name: "local", DeploymentID: localID},
|
||||
remoteID: {Name: "remote", DeploymentID: remoteID, Endpoint: remote.URL},
|
||||
},
|
||||
}
|
||||
globalSiteReplicationSys.Unlock()
|
||||
defer func() {
|
||||
globalSiteReplicationSys.Lock()
|
||||
globalSiteReplicationSys.enabled = oldEnabled
|
||||
globalSiteReplicationSys.state = oldState
|
||||
globalSiteReplicationSys.Unlock()
|
||||
}()
|
||||
|
||||
check := func(name string, wantRemoteTags, wantRemoteQuota int) {
|
||||
t.Helper()
|
||||
status, err := globalSiteReplicationSys.siteReplicationStatus(ctx, obj, madmin.SRStatusOptions{Buckets: true})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
local := status.StatsSummary[localID]
|
||||
remote := status.StatsSummary[remoteID]
|
||||
if local.TotalBucketsCount != 2 || remote.TotalBucketsCount != 2 {
|
||||
t.Fatalf("%s: bucket totals = local:%d remote:%d", name, local.TotalBucketsCount, remote.TotalBucketsCount)
|
||||
}
|
||||
if local.TotalTagsCount != 1 || remote.TotalTagsCount != wantRemoteTags ||
|
||||
local.TotalLockConfigCount != 1 || remote.TotalLockConfigCount != 1 ||
|
||||
local.TotalSSEConfigCount != 1 || remote.TotalSSEConfigCount != 1 ||
|
||||
local.TotalVersioningConfigCount != 1 || remote.TotalVersioningConfigCount != 1 ||
|
||||
local.TotalBucketPoliciesCount != 1 || remote.TotalBucketPoliciesCount != 1 ||
|
||||
local.TotalQuotaConfigCount != 1 || remote.TotalQuotaConfigCount != wantRemoteQuota ||
|
||||
local.TotalCorsConfigCount != 1 || remote.TotalCorsConfigCount != 1 {
|
||||
t.Fatalf("%s: site totals = local:%+v remote:%+v", name, local, remote)
|
||||
}
|
||||
if local.ReplicatedTags != 0 || remote.ReplicatedTags != 0 ||
|
||||
local.ReplicatedBucketPolicies != 0 || remote.ReplicatedBucketPolicies != 0 ||
|
||||
local.ReplicatedQuotaConfig != 0 || remote.ReplicatedQuotaConfig != 0 {
|
||||
t.Fatalf("%s: asymmetric configs counted as replicated: local:%+v remote:%+v", name, local, remote)
|
||||
}
|
||||
remoteBucketStatus := status.BucketStats[remoteBucket][remoteID]
|
||||
if remoteBucketStatus.HasTagsSet != (wantRemoteTags != 0) || remoteBucketStatus.HasQuotaCfgSet != (wantRemoteQuota != 0) {
|
||||
t.Fatalf("%s: remote bucket presence = tags:%v quota:%v", name, remoteBucketStatus.HasTagsSet, remoteBucketStatus.HasQuotaCfgSet)
|
||||
}
|
||||
}
|
||||
|
||||
check("valid asymmetric configs", 1, 1)
|
||||
invalidTags := "not-base64"
|
||||
info := remoteInfo.Buckets[remoteBucket]
|
||||
info.Tags = &invalidTags
|
||||
remoteInfo.Buckets[remoteBucket] = info
|
||||
check("malformed tags do not drop site", 0, 1)
|
||||
|
||||
emptyQuota := base64.StdEncoding.EncodeToString([]byte(`{}`))
|
||||
info = remoteInfo.Buckets[remoteBucket]
|
||||
info.QuotaConfig = &emptyQuota
|
||||
remoteInfo.Buckets[remoteBucket] = info
|
||||
check("empty quota is absent", 0, 0)
|
||||
}
|
||||
+498
-69
@@ -43,8 +43,10 @@ import (
|
||||
"github.com/minio/minio-go/v7/pkg/replication"
|
||||
"github.com/minio/minio-go/v7/pkg/set"
|
||||
"github.com/minio/minio/internal/auth"
|
||||
"github.com/minio/minio/internal/bucket/cors"
|
||||
"github.com/minio/minio/internal/bucket/lifecycle"
|
||||
sreplication "github.com/minio/minio/internal/bucket/replication"
|
||||
"github.com/minio/minio/internal/bucket/versioning"
|
||||
"github.com/minio/minio/internal/logger"
|
||||
xldap "github.com/minio/pkg/v3/ldap"
|
||||
"github.com/minio/pkg/v3/policy"
|
||||
@@ -887,6 +889,32 @@ func (c *SiteReplicationSys) DeleteBucketHook(ctx context.Context, bucket string
|
||||
return errors.Unwrap(cerr)
|
||||
}
|
||||
|
||||
func enablePeerBucketVersioning(meta *BucketMetadata) error {
|
||||
if len(meta.VersioningConfigXML) == 0 {
|
||||
meta.VersioningConfigXML = enabledBucketVersioningConfig
|
||||
if meta.VersioningConfigUpdatedAt.IsZero() {
|
||||
meta.VersioningConfigUpdatedAt = meta.Created
|
||||
}
|
||||
return nil
|
||||
}
|
||||
config, err := versioning.ParseConfig(bytes.NewReader(meta.VersioningConfigXML))
|
||||
if err != nil {
|
||||
meta.VersioningConfigXML = enabledBucketVersioningConfig
|
||||
meta.VersioningConfigUpdatedAt = UTCNow()
|
||||
return nil
|
||||
}
|
||||
if config.Enabled() {
|
||||
return nil
|
||||
}
|
||||
config.Status = versioning.Enabled
|
||||
meta.VersioningConfigXML, err = xml.Marshal(config)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
meta.VersioningConfigUpdatedAt = UTCNow()
|
||||
return nil
|
||||
}
|
||||
|
||||
// PeerBucketMakeWithVersioningHandler - creates bucket and enables versioning.
|
||||
func (c *SiteReplicationSys) PeerBucketMakeWithVersioningHandler(ctx context.Context, bucket string, opts MakeBucketOptions) error {
|
||||
objAPI := newObjectLayerFn()
|
||||
@@ -915,9 +943,14 @@ func (c *SiteReplicationSys) PeerBucketMakeWithVersioningHandler(ctx context.Con
|
||||
|
||||
meta.SetCreatedAt(opts.CreatedAt)
|
||||
|
||||
meta.VersioningConfigXML = enabledBucketVersioningConfig
|
||||
if opts.LockEnabled {
|
||||
if err := enablePeerBucketVersioning(&meta); err != nil {
|
||||
return wrapSRErr(err)
|
||||
}
|
||||
if opts.LockEnabled && len(meta.ObjectLockConfigXML) == 0 {
|
||||
meta.ObjectLockConfigXML = enabledBucketObjectLockConfig
|
||||
if meta.ObjectLockConfigUpdatedAt.IsZero() {
|
||||
meta.ObjectLockConfigUpdatedAt = meta.Created
|
||||
}
|
||||
}
|
||||
|
||||
if err := meta.Save(context.Background(), objAPI); err != nil {
|
||||
@@ -1577,12 +1610,33 @@ func (c *SiteReplicationSys) PeerBucketMetadataUpdateHandler(ctx context.Context
|
||||
return wrapSRErr(errInvalidArgument)
|
||||
}
|
||||
|
||||
var corsConfigData []byte
|
||||
if item.Cors != nil {
|
||||
var err error
|
||||
corsConfigData, err = decodeCORSReplicationPayload(item.Cors)
|
||||
if err != nil {
|
||||
return wrapSRErr(err)
|
||||
}
|
||||
if err = validateCORSReplicationPayload(corsConfigData); err != nil {
|
||||
return wrapSRErr(err)
|
||||
}
|
||||
var unlock func()
|
||||
ctx, unlock, err = lockBucketCORSMetadata(ctx, objectAPI, item.Bucket)
|
||||
if err != nil {
|
||||
return wrapSRErr(err)
|
||||
}
|
||||
defer unlock()
|
||||
}
|
||||
|
||||
meta, err := readBucketMetadata(ctx, objectAPI, item.Bucket)
|
||||
if err != nil {
|
||||
return wrapSRErr(err)
|
||||
}
|
||||
|
||||
if meta.Created.After(item.UpdatedAt) {
|
||||
if item.Cors != nil {
|
||||
replLogOnceIf(ctx, fmt.Errorf("ignoring CORS event for bucket %s from %v before bucket creation at %v", item.Bucket, item.UpdatedAt, meta.Created), "cors-event-before-bucket-creation-"+item.Bucket)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -1632,6 +1686,15 @@ func (c *SiteReplicationSys) PeerBucketMetadataUpdateHandler(ctx context.Context
|
||||
meta.QuotaConfigUpdatedAt = item.UpdatedAt
|
||||
}
|
||||
|
||||
if item.Cors != nil {
|
||||
localState := newCORSReplicationState(meta.CorsConfigXML, meta.CorsConfigUpdatedAt)
|
||||
incoming := newCORSReplicationState(corsConfigData, item.UpdatedAt)
|
||||
if compareCORSReplicationStates(localState, incoming) < 0 {
|
||||
meta.CorsConfigXML = bytes.Clone(corsConfigData)
|
||||
meta.CorsConfigUpdatedAt = item.UpdatedAt
|
||||
}
|
||||
}
|
||||
|
||||
return globalBucketMetadataSys.save(ctx, meta)
|
||||
}
|
||||
|
||||
@@ -1696,6 +1759,26 @@ func (c *SiteReplicationSys) PeerBucketTaggingHandler(ctx context.Context, bucke
|
||||
return nil
|
||||
}
|
||||
|
||||
func newSRBucketObjectLockMeta(bucket string, config *string, updatedAt time.Time) madmin.SRBucketMeta {
|
||||
return madmin.SRBucketMeta{
|
||||
Type: madmin.SRBucketMetaTypeObjectLockConfig,
|
||||
Bucket: bucket,
|
||||
ObjectLockConfig: config,
|
||||
UpdatedAt: updatedAt,
|
||||
}
|
||||
}
|
||||
|
||||
func srObjectLockPayload(item madmin.SRBucketMeta) *string {
|
||||
if item.ObjectLockConfig != nil {
|
||||
return item.ObjectLockConfig
|
||||
}
|
||||
return item.Tags
|
||||
}
|
||||
|
||||
func (c *SiteReplicationSys) peerBucketObjectLockConfigItem(ctx context.Context, item madmin.SRBucketMeta) error {
|
||||
return c.PeerBucketObjectLockConfigHandler(ctx, item.Bucket, srObjectLockPayload(item), item.UpdatedAt)
|
||||
}
|
||||
|
||||
// PeerBucketObjectLockConfigHandler - sets object lock on local bucket.
|
||||
func (c *SiteReplicationSys) PeerBucketObjectLockConfigHandler(ctx context.Context, bucket string, objectLockData *string, updatedAt time.Time) error {
|
||||
if objectLockData != nil {
|
||||
@@ -1749,6 +1832,227 @@ func (c *SiteReplicationSys) PeerBucketSSEConfigHandler(ctx context.Context, buc
|
||||
return nil
|
||||
}
|
||||
|
||||
type corsReplicationStateKind uint8
|
||||
|
||||
const (
|
||||
corsReplicationBaseline corsReplicationStateKind = iota
|
||||
corsReplicationLive
|
||||
corsReplicationTombstone
|
||||
)
|
||||
|
||||
type corsReplicationState struct {
|
||||
kind corsReplicationStateKind
|
||||
payload []byte
|
||||
updatedAt time.Time
|
||||
}
|
||||
|
||||
func newCORSReplicationState(payload []byte, updatedAt time.Time) corsReplicationState {
|
||||
state := corsReplicationState{updatedAt: updatedAt.UTC()}
|
||||
switch {
|
||||
case len(payload) > 0:
|
||||
state.kind = corsReplicationLive
|
||||
state.payload = bytes.Clone(payload)
|
||||
case updatedAt.IsZero():
|
||||
state.kind = corsReplicationBaseline
|
||||
default:
|
||||
state.kind = corsReplicationTombstone
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
func compareCORSReplicationStates(a, b corsReplicationState) int {
|
||||
switch {
|
||||
case a.updatedAt.Before(b.updatedAt):
|
||||
return -1
|
||||
case a.updatedAt.After(b.updatedAt):
|
||||
return 1
|
||||
case a.kind < b.kind:
|
||||
return -1
|
||||
case a.kind > b.kind:
|
||||
return 1
|
||||
case a.kind == corsReplicationLive:
|
||||
return bytes.Compare(a.payload, b.payload)
|
||||
default:
|
||||
return 0
|
||||
}
|
||||
}
|
||||
|
||||
func equalCORSReplicationStates(a, b corsReplicationState) bool {
|
||||
return compareCORSReplicationStates(a, b) == 0
|
||||
}
|
||||
|
||||
func decodeCORSReplicationPayload(encoded *string) ([]byte, error) {
|
||||
if encoded == nil {
|
||||
return nil, nil
|
||||
}
|
||||
payload, err := base64.StdEncoding.Strict().DecodeString(*encoded)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("invalid CORS replication payload: %w", err)
|
||||
}
|
||||
if len(payload) == 0 || base64.StdEncoding.EncodeToString(payload) != *encoded {
|
||||
return nil, fmt.Errorf("invalid CORS replication payload: %w", errInvalidArgument)
|
||||
}
|
||||
return payload, nil
|
||||
}
|
||||
|
||||
func validateCORSReplicationPayload(payload []byte) error {
|
||||
if payload == nil {
|
||||
return nil
|
||||
}
|
||||
config, err := cors.ParseBucketCorsConfig(bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
return fmt.Errorf("invalid CORS replication payload: %w", errInvalidArgument)
|
||||
}
|
||||
if err = config.Validate(); err != nil {
|
||||
return fmt.Errorf("invalid CORS replication payload: %w: %v", errInvalidArgument, err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func corsReplicationStateFromInfo(info madmin.SRBucketInfo) (corsReplicationState, error) {
|
||||
payload, err := decodeCORSReplicationPayload(info.CorsConfig)
|
||||
if err != nil {
|
||||
return corsReplicationState{}, err
|
||||
}
|
||||
if err = validateCORSReplicationPayload(payload); err != nil {
|
||||
return corsReplicationState{}, err
|
||||
}
|
||||
if info.CorsConfig != nil && info.CorsConfigUpdatedAt.IsZero() {
|
||||
return corsReplicationState{}, fmt.Errorf("live CORS replication payload has no source timestamp: %w", errInvalidArgument)
|
||||
}
|
||||
return newCORSReplicationState(payload, info.CorsConfigUpdatedAt), nil
|
||||
}
|
||||
|
||||
func areCORSReplicationStatesEqual(sites []srBucketMetaInfo) bool {
|
||||
if len(sites) == 0 {
|
||||
return true
|
||||
}
|
||||
reference, err := corsReplicationStateFromInfo(sites[0].SRBucketInfo)
|
||||
if err != nil {
|
||||
return false
|
||||
}
|
||||
for _, site := range sites[1:] {
|
||||
state, err := corsReplicationStateFromInfo(site.SRBucketInfo)
|
||||
if err != nil || !equalCORSReplicationStates(reference, state) {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func (s corsReplicationState) encodedPayload() *string {
|
||||
if s.kind != corsReplicationLive {
|
||||
return nil
|
||||
}
|
||||
encoded := base64.StdEncoding.EncodeToString(s.payload)
|
||||
return &encoded
|
||||
}
|
||||
|
||||
func newBucketCORSReplicationEvent(bucket string, meta BucketMetadata) (madmin.SRBucketMeta, bool) {
|
||||
if meta.CorsConfigUpdatedAt.IsZero() {
|
||||
return madmin.SRBucketMeta{}, false
|
||||
}
|
||||
return madmin.SRBucketMeta{
|
||||
Type: madmin.SRBucketMetaTypeCorsConfig,
|
||||
Bucket: bucket,
|
||||
Cors: newCORSReplicationState(meta.CorsConfigXML, meta.CorsConfigUpdatedAt).encodedPayload(),
|
||||
UpdatedAt: meta.CorsConfigUpdatedAt,
|
||||
}, true
|
||||
}
|
||||
|
||||
func lockBucketCORSMetadata(ctx context.Context, objectAPI ObjectLayer, bucket string) (context.Context, func(), error) {
|
||||
// The lock name is deliberately different from .metadata.bin. Saving the
|
||||
// metadata locks that object internally, and namespace locks are not
|
||||
// re-entrant.
|
||||
lock := objectAPI.NewNSLock(minioMetaBucket, pathJoin(bucketMetaPrefix, bucket, "cors-config.lock"))
|
||||
lkctx, err := lock.GetLock(ctx, globalOperationTimeout)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
}
|
||||
return lkctx.Context(), func() { lock.Unlock(lkctx) }, nil
|
||||
}
|
||||
|
||||
func updateLocalBucketCORSMetadata(ctx context.Context, objectAPI ObjectLayer, bucket string, configData []byte) (time.Time, error) {
|
||||
return applyBucketCORSMetadata(ctx, objectAPI, bucket, configData, time.Time{}, true)
|
||||
}
|
||||
|
||||
func applyBucketCORSMetadata(ctx context.Context, objectAPI ObjectLayer, bucket string, configData []byte, sourceUpdatedAt time.Time, local bool) (time.Time, error) {
|
||||
if bucket == "" || (configData != nil && len(configData) == 0) {
|
||||
return time.Time{}, errInvalidArgument
|
||||
}
|
||||
if err := validateCORSReplicationPayload(configData); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
ctx, unlock, err := lockBucketCORSMetadata(ctx, objectAPI, bucket)
|
||||
if err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
defer unlock()
|
||||
|
||||
var meta BucketMetadata
|
||||
if local {
|
||||
meta, err = loadBucketMetadataParse(ctx, objectAPI, bucket, true)
|
||||
} else {
|
||||
meta, err = readBucketMetadata(ctx, objectAPI, bucket)
|
||||
}
|
||||
if err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
|
||||
localState := newCORSReplicationState(meta.CorsConfigXML, meta.CorsConfigUpdatedAt)
|
||||
updatedAt := sourceUpdatedAt.UTC()
|
||||
if local {
|
||||
updatedAt = UTCNow()
|
||||
floor := meta.Created
|
||||
if localState.updatedAt.After(floor) {
|
||||
floor = localState.updatedAt
|
||||
}
|
||||
if !updatedAt.After(floor) {
|
||||
updatedAt = floor.Add(time.Nanosecond)
|
||||
}
|
||||
} else {
|
||||
// CreatedAt is the bucket-lineage floor: an event from an older
|
||||
// incarnation of the bucket must not change the current one.
|
||||
if updatedAt.Before(meta.Created) {
|
||||
replLogOnceIf(ctx, fmt.Errorf("ignoring CORS event for bucket %s from %v before bucket creation at %v", bucket, updatedAt, meta.Created), "cors-event-before-bucket-creation-"+bucket)
|
||||
return localState.updatedAt, nil
|
||||
}
|
||||
incoming := newCORSReplicationState(configData, updatedAt)
|
||||
if compareCORSReplicationStates(localState, incoming) >= 0 {
|
||||
return localState.updatedAt, nil
|
||||
}
|
||||
}
|
||||
|
||||
meta.CorsConfigXML = bytes.Clone(configData)
|
||||
meta.CorsConfigUpdatedAt = updatedAt
|
||||
if err = globalBucketMetadataSys.save(ctx, meta); err != nil {
|
||||
return time.Time{}, err
|
||||
}
|
||||
return updatedAt, nil
|
||||
}
|
||||
|
||||
// PeerBucketCorsConfigHandler - copies/deletes CORS config to local cluster.
|
||||
func (c *SiteReplicationSys) PeerBucketCorsConfigHandler(ctx context.Context, bucket string, corsConfig *string, updatedAt time.Time) error {
|
||||
objectAPI := newObjectLayerFn()
|
||||
if objectAPI == nil {
|
||||
return errSRObjectLayerNotReady
|
||||
}
|
||||
|
||||
if bucket == "" || updatedAt.IsZero() {
|
||||
return wrapSRErr(errInvalidArgument)
|
||||
}
|
||||
|
||||
configData, err := decodeCORSReplicationPayload(corsConfig)
|
||||
if err != nil {
|
||||
return wrapSRErr(err)
|
||||
}
|
||||
if _, err = applyBucketCORSMetadata(ctx, objectAPI, bucket, configData, updatedAt, false); err != nil {
|
||||
return wrapSRErr(err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// PeerBucketQuotaConfigHandler - copies/deletes policy to local cluster.
|
||||
func (c *SiteReplicationSys) PeerBucketQuotaConfigHandler(ctx context.Context, bucket string, quota *madmin.BucketQuota, updatedAt time.Time) error {
|
||||
// skip overwrite if local update is newer than peer update.
|
||||
@@ -1924,12 +2228,7 @@ func (c *SiteReplicationSys) syncToAllPeers(ctx context.Context, addOpts madmin.
|
||||
objLockCfgData, tm := meta.ObjectLockConfigXML, meta.ObjectLockConfigUpdatedAt
|
||||
if len(objLockCfgData) > 0 {
|
||||
objLockStr := base64.StdEncoding.EncodeToString(objLockCfgData)
|
||||
err = c.BucketMetaHook(ctx, madmin.SRBucketMeta{
|
||||
Type: madmin.SRBucketMetaTypeObjectLockConfig,
|
||||
Bucket: bucket,
|
||||
Tags: &objLockStr,
|
||||
UpdatedAt: tm,
|
||||
})
|
||||
err = c.BucketMetaHook(ctx, newSRBucketObjectLockMeta(bucket, &objLockStr, tm))
|
||||
if err != nil {
|
||||
return errSRBucketMetaError(err)
|
||||
}
|
||||
@@ -1950,6 +2249,14 @@ func (c *SiteReplicationSys) syncToAllPeers(ctx context.Context, addOpts madmin.
|
||||
}
|
||||
}
|
||||
|
||||
// Replicate existing bucket CORS settings
|
||||
if corsEvent, ok := newBucketCORSReplicationEvent(bucket, meta); ok {
|
||||
err = c.BucketMetaHook(ctx, corsEvent)
|
||||
if err != nil {
|
||||
return errSRBucketMetaError(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Replicate existing bucket quotas settings
|
||||
quotaConfigJSON, tm := meta.QuotaConfigJSON, meta.QuotaConfigUpdatedAt
|
||||
if len(quotaConfigJSON) > 0 {
|
||||
@@ -2720,6 +3027,7 @@ func (c *SiteReplicationSys) SiteReplicationStatus(ctx context.Context, objAPI O
|
||||
st.VersioningConfigMismatch ||
|
||||
st.OLockConfigMismatch ||
|
||||
st.SSEConfigMismatch ||
|
||||
st.CorsCfgMismatch ||
|
||||
st.PolicyMismatch ||
|
||||
st.ReplicationCfgMismatch ||
|
||||
st.QuotaCfgMismatch ||
|
||||
@@ -3145,77 +3453,117 @@ func (c *SiteReplicationSys) siteReplicationStatus(ctx context.Context, objAPI O
|
||||
quotaCfgs := make([]*madmin.BucketQuota, numSites)
|
||||
sseCfgSet := set.NewStringSet()
|
||||
versionCfgSet := set.NewStringSet()
|
||||
var tagCount, olockCfgCount, sseCfgCount, versionCfgCount int
|
||||
validReplCfg := make([]bool, numSites)
|
||||
validVersionCfg := make([]bool, numSites)
|
||||
validQuotaCfg := make([]bool, numSites)
|
||||
validTags := make([]bool, numSites)
|
||||
validPolicies := make([]bool, numSites)
|
||||
validObjectLockCfg := make([]bool, numSites)
|
||||
validSSECfg := make([]bool, numSites)
|
||||
validCorsCfg := make([]bool, numSites)
|
||||
var tagCount, olockCfgCount, policyCount, quotaCfgCount, sseCfgCount, corsCfgCount, versionCfgCount int
|
||||
for i, s := range slc {
|
||||
logInvalid := func(configType string, err error) {
|
||||
replLogOnceIf(ctx,
|
||||
fmt.Errorf("unable to parse %s metadata for bucket %s from site %s: %w", configType, b, s.DeploymentID, err),
|
||||
"site-replication-status-"+configType+"-"+b+"-"+s.DeploymentID)
|
||||
}
|
||||
if s.ReplicationConfig != nil {
|
||||
cfgBytes, err := base64.StdEncoding.DecodeString(*s.ReplicationConfig)
|
||||
if err != nil {
|
||||
continue
|
||||
if err == nil {
|
||||
cfg, err := sreplication.ParseConfig(bytes.NewReader(cfgBytes))
|
||||
if err == nil {
|
||||
replCfgs[i] = cfg
|
||||
validReplCfg[i] = true
|
||||
} else {
|
||||
logInvalid("replication", err)
|
||||
}
|
||||
} else {
|
||||
logInvalid("replication", err)
|
||||
}
|
||||
cfg, err := sreplication.ParseConfig(bytes.NewReader(cfgBytes))
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
replCfgs[i] = cfg
|
||||
}
|
||||
if s.Versioning != nil {
|
||||
configData, err := base64.StdEncoding.DecodeString(*s.Versioning)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
versionCfgCount++
|
||||
if !versionCfgSet.Contains(string(configData)) {
|
||||
versionCfgSet.Add(string(configData))
|
||||
if err == nil {
|
||||
validVersionCfg[i] = true
|
||||
versionCfgCount++
|
||||
if !versionCfgSet.Contains(string(configData)) {
|
||||
versionCfgSet.Add(string(configData))
|
||||
}
|
||||
} else {
|
||||
logInvalid("versioning", err)
|
||||
}
|
||||
}
|
||||
if s.QuotaConfig != nil {
|
||||
cfgBytes, err := base64.StdEncoding.DecodeString(*s.QuotaConfig)
|
||||
if err != nil {
|
||||
continue
|
||||
if err == nil {
|
||||
cfg, err := parseBucketQuota(b, cfgBytes)
|
||||
if err == nil {
|
||||
if cfg != nil && *cfg != (madmin.BucketQuota{}) {
|
||||
quotaCfgs[i] = cfg
|
||||
validQuotaCfg[i] = true
|
||||
quotaCfgCount++
|
||||
}
|
||||
} else {
|
||||
logInvalid("quota", err)
|
||||
}
|
||||
} else {
|
||||
logInvalid("quota", err)
|
||||
}
|
||||
cfg, err := parseBucketQuota(b, cfgBytes)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
quotaCfgs[i] = cfg
|
||||
}
|
||||
if s.Tags != nil {
|
||||
tagBytes, err := base64.StdEncoding.DecodeString(*s.Tags)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
tagCount++
|
||||
if !tagSet.Contains(string(tagBytes)) {
|
||||
tagSet.Add(string(tagBytes))
|
||||
if err == nil {
|
||||
validTags[i] = true
|
||||
tagCount++
|
||||
if !tagSet.Contains(string(tagBytes)) {
|
||||
tagSet.Add(string(tagBytes))
|
||||
}
|
||||
} else {
|
||||
logInvalid("tags", err)
|
||||
}
|
||||
}
|
||||
if len(s.Policy) > 0 {
|
||||
plcy, err := policy.ParseBucketPolicyConfig(bytes.NewReader(s.Policy), b)
|
||||
if err != nil {
|
||||
continue
|
||||
if err == nil {
|
||||
policies[i] = plcy
|
||||
validPolicies[i] = true
|
||||
policyCount++
|
||||
} else {
|
||||
logInvalid("policy", err)
|
||||
}
|
||||
policies[i] = plcy
|
||||
}
|
||||
if s.ObjectLockConfig != nil {
|
||||
configData, err := base64.StdEncoding.DecodeString(*s.ObjectLockConfig)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
olockCfgCount++
|
||||
if !olockConfigSet.Contains(string(configData)) {
|
||||
olockConfigSet.Add(string(configData))
|
||||
if err == nil {
|
||||
validObjectLockCfg[i] = true
|
||||
olockCfgCount++
|
||||
if !olockConfigSet.Contains(string(configData)) {
|
||||
olockConfigSet.Add(string(configData))
|
||||
}
|
||||
} else {
|
||||
logInvalid("object-lock", err)
|
||||
}
|
||||
}
|
||||
if s.SSEConfig != nil {
|
||||
configData, err := base64.StdEncoding.DecodeString(*s.SSEConfig)
|
||||
if err != nil {
|
||||
continue
|
||||
}
|
||||
sseCfgCount++
|
||||
if !sseCfgSet.Contains(string(configData)) {
|
||||
sseCfgSet.Add(string(configData))
|
||||
if err == nil {
|
||||
validSSECfg[i] = true
|
||||
sseCfgCount++
|
||||
if !sseCfgSet.Contains(string(configData)) {
|
||||
sseCfgSet.Add(string(configData))
|
||||
}
|
||||
} else {
|
||||
logInvalid("sse", err)
|
||||
}
|
||||
}
|
||||
corsState, err := corsReplicationStateFromInfo(s.SRBucketInfo)
|
||||
if err != nil {
|
||||
logInvalid("cors", err)
|
||||
} else if corsState.kind == corsReplicationLive {
|
||||
validCorsCfg[i] = true
|
||||
corsCfgCount++
|
||||
}
|
||||
ss, ok := info.StatsSummary[s.DeploymentID]
|
||||
if !ok {
|
||||
ss = madmin.SRSiteSummary{}
|
||||
@@ -3225,26 +3573,33 @@ func (c *SiteReplicationSys) siteReplicationStatus(ctx context.Context, objAPI O
|
||||
ss.ReplicatedBuckets++
|
||||
}
|
||||
ss.TotalBucketsCount++
|
||||
if tagCount > 0 {
|
||||
if validTags[i] {
|
||||
ss.TotalTagsCount++
|
||||
}
|
||||
if olockCfgCount > 0 {
|
||||
if validObjectLockCfg[i] {
|
||||
ss.TotalLockConfigCount++
|
||||
}
|
||||
if sseCfgCount > 0 {
|
||||
if validSSECfg[i] {
|
||||
ss.TotalSSEConfigCount++
|
||||
}
|
||||
if versionCfgCount > 0 {
|
||||
if validCorsCfg[i] {
|
||||
ss.TotalCorsConfigCount++
|
||||
}
|
||||
if validVersionCfg[i] {
|
||||
ss.TotalVersioningConfigCount++
|
||||
}
|
||||
if len(policies) > 0 {
|
||||
if validPolicies[i] {
|
||||
ss.TotalBucketPoliciesCount++
|
||||
}
|
||||
if validQuotaCfg[i] {
|
||||
ss.TotalQuotaConfigCount++
|
||||
}
|
||||
info.StatsSummary[s.DeploymentID] = ss
|
||||
}
|
||||
tagMismatch := !isReplicated(tagCount, numSites, tagSet)
|
||||
olockCfgMismatch := !isReplicated(olockCfgCount, numSites, olockConfigSet)
|
||||
sseCfgMismatch := !isReplicated(sseCfgCount, numSites, sseCfgSet)
|
||||
corsCfgMismatch := !areCORSReplicationStatesEqual(slc)
|
||||
versionCfgMismatch := !isReplicated(versionCfgCount, numSites, versionCfgSet)
|
||||
policyMismatch := !isBktPolicyReplicated(numSites, policies)
|
||||
replCfgMismatch := !isBktReplCfgReplicated(numSites, replCfgs)
|
||||
@@ -3267,16 +3622,18 @@ func (c *SiteReplicationSys) siteReplicationStatus(ctx context.Context, objAPI O
|
||||
TagMismatch: tagMismatch,
|
||||
OLockConfigMismatch: olockCfgMismatch,
|
||||
SSEConfigMismatch: sseCfgMismatch,
|
||||
CorsCfgMismatch: corsCfgMismatch,
|
||||
VersioningConfigMismatch: versionCfgMismatch,
|
||||
PolicyMismatch: policyMismatch,
|
||||
ReplicationCfgMismatch: replCfgMismatch,
|
||||
QuotaCfgMismatch: quotaCfgMismatch,
|
||||
HasReplicationCfg: s.ReplicationConfig != nil,
|
||||
HasTagsSet: s.Tags != nil,
|
||||
HasOLockConfigSet: s.ObjectLockConfig != nil,
|
||||
HasPolicySet: s.Policy != nil,
|
||||
HasReplicationCfg: validReplCfg[i],
|
||||
HasTagsSet: validTags[i],
|
||||
HasOLockConfigSet: validObjectLockCfg[i],
|
||||
HasPolicySet: validPolicies[i],
|
||||
HasQuotaCfgSet: quotaCfgSet,
|
||||
HasSSECfgSet: s.SSEConfig != nil,
|
||||
HasSSECfgSet: validSSECfg[i],
|
||||
HasCorsCfgSet: validCorsCfg[i],
|
||||
}
|
||||
var m srBucketMetaInfo
|
||||
if len(bucketStats[s.Bucket]) > dIdx {
|
||||
@@ -3299,12 +3656,18 @@ func (c *SiteReplicationSys) siteReplicationStatus(ctx context.Context, objAPI O
|
||||
if !sseCfgMismatch && sseCfgCount == numSites {
|
||||
sum.ReplicatedSSEConfig++
|
||||
}
|
||||
if !policyMismatch && len(policies) == numSites {
|
||||
if !corsCfgMismatch && corsCfgCount == numSites {
|
||||
sum.ReplicatedCorsConfig++
|
||||
}
|
||||
if !policyMismatch && policyCount == numSites {
|
||||
sum.ReplicatedBucketPolicies++
|
||||
}
|
||||
if !tagMismatch && tagCount == numSites {
|
||||
sum.ReplicatedTags++
|
||||
}
|
||||
if !quotaCfgMismatch && quotaCfgCount == numSites {
|
||||
sum.ReplicatedQuotaConfig++
|
||||
}
|
||||
info.StatsSummary[s.DeploymentID] = sum
|
||||
}
|
||||
}
|
||||
@@ -3709,6 +4072,12 @@ func (c *SiteReplicationSys) SiteReplicationMetaInfo(ctx context.Context, objAPI
|
||||
bms.SSEConfigUpdatedAt = meta.EncryptionConfigUpdatedAt
|
||||
}
|
||||
|
||||
bms.CorsConfigUpdatedAt = meta.CorsConfigUpdatedAt
|
||||
if len(meta.CorsConfigXML) > 0 {
|
||||
corsConfigStr := base64.StdEncoding.EncodeToString(meta.CorsConfigXML)
|
||||
bms.CorsConfig = &corsConfigStr
|
||||
}
|
||||
|
||||
if len(meta.ReplicationConfigXML) > 0 {
|
||||
rcfgXMLStr := base64.StdEncoding.EncodeToString(meta.ReplicationConfigXML)
|
||||
bms.ReplicationConfig = &rcfgXMLStr
|
||||
@@ -3734,7 +4103,7 @@ func (c *SiteReplicationSys) SiteReplicationMetaInfo(ctx context.Context, objAPI
|
||||
bms.ExpiryLCConfig = &expLclCfgStr
|
||||
// if all non expiry rules only, ExpiryUpdatedAt would be nil
|
||||
if meta.lifecycleConfig.ExpiryUpdatedAt != nil {
|
||||
bms.ExpiryLCConfigUpdatedAt = *(meta.lifecycleConfig.ExpiryUpdatedAt)
|
||||
bms.ExpiryLCConfigUpdatedAt = *meta.lifecycleConfig.ExpiryUpdatedAt
|
||||
}
|
||||
}
|
||||
|
||||
@@ -4459,6 +4828,7 @@ func (c *SiteReplicationSys) healBuckets(ctx context.Context, objAPI ObjectLayer
|
||||
c.healVersioningMetadata(ctx, objAPI, bucket, info)
|
||||
c.healOLockConfigMetadata(ctx, objAPI, bucket, info)
|
||||
c.healSSEMetadata(ctx, objAPI, bucket, info)
|
||||
c.healCORSMetadata(ctx, objAPI, bucket, info)
|
||||
c.healBucketReplicationConfig(ctx, objAPI, bucket, info, &opts)
|
||||
c.healBucketPolicies(ctx, objAPI, bucket, info)
|
||||
c.healTagMetadata(ctx, objAPI, bucket, info)
|
||||
@@ -4916,6 +5286,70 @@ func (c *SiteReplicationSys) healSSEMetadata(ctx context.Context, objAPI ObjectL
|
||||
return nil
|
||||
}
|
||||
|
||||
func latestCORSConfig(bs map[string]srBucketStatsSummary) (latestID string, latest corsReplicationState, ok bool) {
|
||||
for dID, status := range bs {
|
||||
state, err := corsReplicationStateFromInfo(status.meta.SRBucketInfo)
|
||||
if err != nil || state.kind == corsReplicationBaseline {
|
||||
continue
|
||||
}
|
||||
cmp := compareCORSReplicationStates(latest, state)
|
||||
if !ok || cmp < 0 || (cmp == 0 && dID > latestID) {
|
||||
latestID = dID
|
||||
latest = state
|
||||
ok = true
|
||||
}
|
||||
}
|
||||
return latestID, latest, ok
|
||||
}
|
||||
|
||||
func (c *SiteReplicationSys) healCORSMetadata(ctx context.Context, objAPI ObjectLayer, bucket string, info srStatusInfo) error {
|
||||
c.RLock()
|
||||
defer c.RUnlock()
|
||||
if !c.enabled {
|
||||
return nil
|
||||
}
|
||||
|
||||
bs := info.BucketStats[bucket]
|
||||
latestID, latestState, ok := latestCORSConfig(bs)
|
||||
if !ok {
|
||||
return nil
|
||||
}
|
||||
|
||||
latestPeerName := info.Sites[latestID].Name
|
||||
latestCorsConfig := latestState.encodedPayload()
|
||||
|
||||
for dID, bStatus := range bs {
|
||||
currentState, err := corsReplicationStateFromInfo(bStatus.meta.SRBucketInfo)
|
||||
if err == nil && equalCORSReplicationStates(latestState, currentState) {
|
||||
continue
|
||||
}
|
||||
if dID == globalDeploymentID() {
|
||||
if err := c.PeerBucketCorsConfigHandler(ctx, bucket, latestCorsConfig, latestState.updatedAt); err != nil {
|
||||
replLogIf(ctx, fmt.Errorf("Unable to heal CORS metadata from peer site %s : %w", latestPeerName, err))
|
||||
}
|
||||
continue
|
||||
}
|
||||
|
||||
admClient, err := c.getAdminClient(ctx, dID)
|
||||
if err != nil {
|
||||
return wrapSRErr(err)
|
||||
}
|
||||
peerName := info.Sites[dID].Name
|
||||
err = admClient.SRPeerReplicateBucketMeta(ctx, madmin.SRBucketMeta{
|
||||
Type: madmin.SRBucketMetaTypeCorsConfig,
|
||||
Bucket: bucket,
|
||||
Cors: latestCorsConfig,
|
||||
UpdatedAt: latestState.updatedAt,
|
||||
})
|
||||
if err != nil {
|
||||
replLogIf(ctx, c.annotatePeerErr(peerName, replicateBucketMetadata,
|
||||
fmt.Errorf("Unable to heal CORS config metadata for peer %s from peer %s : %w",
|
||||
peerName, latestPeerName, err)))
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (c *SiteReplicationSys) healOLockConfigMetadata(ctx context.Context, objAPI ObjectLayer, bucket string, info srStatusInfo) error {
|
||||
bs := info.BucketStats[bucket]
|
||||
|
||||
@@ -4976,12 +5410,7 @@ func (c *SiteReplicationSys) healOLockConfigMetadata(ctx context.Context, objAPI
|
||||
return wrapSRErr(err)
|
||||
}
|
||||
peerName := info.Sites[dID].Name
|
||||
err = admClient.SRPeerReplicateBucketMeta(ctx, madmin.SRBucketMeta{
|
||||
Type: madmin.SRBucketMetaTypeObjectLockConfig,
|
||||
Bucket: bucket,
|
||||
Tags: latestObjLockConfig,
|
||||
UpdatedAt: lastUpdate,
|
||||
})
|
||||
err = admClient.SRPeerReplicateBucketMeta(ctx, newSRBucketObjectLockMeta(bucket, latestObjLockConfig, lastUpdate))
|
||||
if err != nil {
|
||||
replLogIf(ctx, c.annotatePeerErr(peerName, replicateBucketMetadata,
|
||||
fmt.Errorf("Unable to heal object lock config metadata for peer %s from peer %s : %w",
|
||||
@@ -5232,7 +5661,7 @@ func isBucketMetadataEqual(one, two *string) bool {
|
||||
case one == nil || two == nil:
|
||||
return false
|
||||
default:
|
||||
return strings.EqualFold(*one, *two)
|
||||
return *one == *two
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -18,7 +18,10 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/minio-go/v7/pkg/set"
|
||||
@@ -66,3 +69,92 @@ func TestGetMissingSiteNames(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestSRBucketMetaCorsRoundTrip verifies that a CORS bucket-meta item
|
||||
// survives the JSON transport used by SRPeerReplicateBucketItem and that
|
||||
// the base64-encoded payload decodes back to the original XML bytes. This
|
||||
// mirrors the initial-sync push, the peer-apply path, and the heal path,
|
||||
// all of which carry the config through SRBucketMeta.Cors as base64.
|
||||
func TestSRBucketMetaCorsRoundTrip(t *testing.T) {
|
||||
const corsXML = `<CORSConfiguration><CORSRule><AllowedOrigin>https://app.example.com</AllowedOrigin><AllowedMethod>GET</AllowedMethod></CORSRule></CORSConfiguration>`
|
||||
b64 := base64.StdEncoding.EncodeToString([]byte(corsXML))
|
||||
updatedAt := time.Now().UTC().Truncate(time.Second)
|
||||
|
||||
item := madmin.SRBucketMeta{
|
||||
Type: madmin.SRBucketMetaTypeCorsConfig,
|
||||
Bucket: "testbucket",
|
||||
Cors: &b64,
|
||||
UpdatedAt: updatedAt,
|
||||
}
|
||||
|
||||
data, err := json.Marshal(item)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal failed: %v", err)
|
||||
}
|
||||
|
||||
var got madmin.SRBucketMeta
|
||||
if err := json.Unmarshal(data, &got); err != nil {
|
||||
t.Fatalf("unmarshal failed: %v", err)
|
||||
}
|
||||
|
||||
if got.Type != madmin.SRBucketMetaTypeCorsConfig {
|
||||
t.Fatalf("type mismatch: got %q", got.Type)
|
||||
}
|
||||
if got.Cors == nil {
|
||||
t.Fatal("expected non-nil Cors after round-trip")
|
||||
}
|
||||
decoded, err := base64.StdEncoding.DecodeString(*got.Cors)
|
||||
if err != nil {
|
||||
t.Fatalf("decode failed: %v", err)
|
||||
}
|
||||
if string(decoded) != corsXML {
|
||||
t.Fatalf("payload mismatch:\n got %q\nwant %q", decoded, corsXML)
|
||||
}
|
||||
if !got.UpdatedAt.Equal(updatedAt) {
|
||||
t.Fatalf("UpdatedAt mismatch: got %v want %v", got.UpdatedAt, updatedAt)
|
||||
}
|
||||
|
||||
// A deletion is signaled with a nil Cors pointer; it must survive too.
|
||||
del := madmin.SRBucketMeta{
|
||||
Type: madmin.SRBucketMetaTypeCorsConfig,
|
||||
Bucket: "testbucket",
|
||||
Cors: nil,
|
||||
UpdatedAt: updatedAt,
|
||||
}
|
||||
data, err = json.Marshal(del)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal (delete) failed: %v", err)
|
||||
}
|
||||
var gotDel madmin.SRBucketMeta
|
||||
if err := json.Unmarshal(data, &gotDel); err != nil {
|
||||
t.Fatalf("unmarshal (delete) failed: %v", err)
|
||||
}
|
||||
if gotDel.Cors != nil {
|
||||
t.Fatalf("expected nil Cors for deletion, got %q", *gotDel.Cors)
|
||||
}
|
||||
}
|
||||
|
||||
// TestIsBucketMetadataEqualCors covers the pointer-comparison helper used by
|
||||
// the CORS heal path to decide whether a peer already holds the latest config.
|
||||
func TestIsBucketMetadataEqualCors(t *testing.T) {
|
||||
a := base64.StdEncoding.EncodeToString([]byte("config-a"))
|
||||
b := base64.StdEncoding.EncodeToString([]byte("config-b"))
|
||||
|
||||
cases := []struct {
|
||||
name string
|
||||
one *string
|
||||
two *string
|
||||
want bool
|
||||
}{
|
||||
{"both nil", nil, nil, true},
|
||||
{"one nil", &a, nil, false},
|
||||
{"other nil", nil, &b, false},
|
||||
{"equal", &a, &a, true},
|
||||
{"different", &a, &b, false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := isBucketMetadataEqual(tc.one, tc.two); got != tc.want {
|
||||
t.Errorf("%s: got %v want %v", tc.name, got, tc.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -1373,6 +1373,11 @@ func getBucketLifecycleURL(endPoint, bucketName string) (ret string) {
|
||||
return makeTestTargetURL(endPoint, bucketName, "", queryValue)
|
||||
}
|
||||
|
||||
// return URL for set/get/delete cors of the bucket.
|
||||
func getBucketCorsURL(endPoint, bucketName string) string {
|
||||
return makeTestTargetURL(endPoint, bucketName, "", url.Values{"cors": []string{""}})
|
||||
}
|
||||
|
||||
// return URL for listing objects in the bucket with V1 legacy API.
|
||||
func getListObjectsV1URL(endPoint, bucketName, prefix, maxKeys, encodingType string) string {
|
||||
queryValue := url.Values{}
|
||||
@@ -2052,6 +2057,15 @@ func registerBucketLevelFunc(bucket *mux.Router, api objectAPIHandlers, apiFunct
|
||||
case "ListenNotification":
|
||||
// Register ListenNotification Handler.
|
||||
bucket.Methods(http.MethodGet).HandlerFunc(api.ListenNotificationHandler).Queries("events", "{events:.*}")
|
||||
case "PutBucketCors":
|
||||
// Register PutBucketCors handler.
|
||||
bucket.Methods(http.MethodPut).HandlerFunc(api.PutBucketCorsHandler).Queries("cors", "")
|
||||
case "GetBucketCors":
|
||||
// Register GetBucketCors handler.
|
||||
bucket.Methods(http.MethodGet).HandlerFunc(api.GetBucketCorsHandler).Queries("cors", "")
|
||||
case "DeleteBucketCors":
|
||||
// Register DeleteBucketCors handler.
|
||||
bucket.Methods(http.MethodDelete).HandlerFunc(api.DeleteBucketCorsHandler).Queries("cors", "")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -50,7 +50,7 @@ func (x *xlMetaV2VersionHeader) unmarshalV1(bts []byte) (o []byte, err error) {
|
||||
err = msgp.ArrayError{Wanted: 4, Got: zb0001}
|
||||
return o, err
|
||||
}
|
||||
bts, err = msgp.ReadExactBytes(bts, (x.VersionID)[:])
|
||||
bts, err = msgp.ReadExactBytes(bts, x.VersionID[:])
|
||||
if err != nil {
|
||||
err = msgp.WrapError(err, "VersionID")
|
||||
return o, err
|
||||
@@ -145,7 +145,7 @@ func (z *xlMetaV2VersionHeaderV2) UnmarshalMsg(bts []byte) (o []byte, err error)
|
||||
err = msgp.ArrayError{Wanted: 5, Got: zb0001}
|
||||
return o, err
|
||||
}
|
||||
bts, err = msgp.ReadExactBytes(bts, (z.VersionID)[:])
|
||||
bts, err = msgp.ReadExactBytes(bts, z.VersionID[:])
|
||||
if err != nil {
|
||||
err = msgp.WrapError(err, "VersionID")
|
||||
return o, err
|
||||
@@ -155,7 +155,7 @@ func (z *xlMetaV2VersionHeaderV2) UnmarshalMsg(bts []byte) (o []byte, err error)
|
||||
err = msgp.WrapError(err, "ModTime")
|
||||
return o, err
|
||||
}
|
||||
bts, err = msgp.ReadExactBytes(bts, (z.Signature)[:])
|
||||
bts, err = msgp.ReadExactBytes(bts, z.Signature[:])
|
||||
if err != nil {
|
||||
err = msgp.WrapError(err, "Signature")
|
||||
return o, err
|
||||
@@ -195,7 +195,7 @@ func (z *xlMetaV2VersionHeaderV2) DecodeMsg(dc *msgp.Reader) (err error) {
|
||||
err = msgp.ArrayError{Wanted: 5, Got: zb0001}
|
||||
return err
|
||||
}
|
||||
err = dc.ReadExactBytes((z.VersionID)[:])
|
||||
err = dc.ReadExactBytes(z.VersionID[:])
|
||||
if err != nil {
|
||||
err = msgp.WrapError(err, "VersionID")
|
||||
return err
|
||||
@@ -205,7 +205,7 @@ func (z *xlMetaV2VersionHeaderV2) DecodeMsg(dc *msgp.Reader) (err error) {
|
||||
err = msgp.WrapError(err, "ModTime")
|
||||
return err
|
||||
}
|
||||
err = dc.ReadExactBytes((z.Signature)[:])
|
||||
err = dc.ReadExactBytes(z.Signature[:])
|
||||
if err != nil {
|
||||
err = msgp.WrapError(err, "Signature")
|
||||
return err
|
||||
|
||||
@@ -1101,7 +1101,7 @@ func (x *xlMetaV2) loadLegacy(buf []byte) error {
|
||||
return msgp.WrapError(err, "Versions")
|
||||
}
|
||||
if cap(x.versions) >= int(zb0002) {
|
||||
x.versions = (x.versions)[:zb0002]
|
||||
x.versions = x.versions[:zb0002]
|
||||
} else {
|
||||
x.versions = make([]xlMetaV2ShallowVersion, zb0002, zb0002+1)
|
||||
}
|
||||
|
||||
@@ -840,12 +840,11 @@ Received a message: {"EventType":"s3:ObjectCreated:Put","Key":"images/myphoto.jp
|
||||
> database (string) database name (used only if `connection_string` is empty)
|
||||
> ```
|
||||
>
|
||||
> These are now deprecated, if you plan to upgrade to any releases after _RELEASE.2020-04-10T03-34-42Z_ make sure
|
||||
> to migrate to only using _connection_string_ option. To migrate, once you have upgraded all the servers use the
|
||||
> following command to update the existing notification targets.
|
||||
> These are now deprecated. SILO does not migrate an enabled target that only has these fields, so convert it to
|
||||
> _connection_string_ before starting SILO. On the old server, use the following command to update the target.
|
||||
>
|
||||
> ```
|
||||
> mc admin config set mysilo/ notify_postgres[:name] connection_string="host=hostname port=2832 username=psqluser password=psqlpass database=bucketevents"
|
||||
> mc admin config set mysilo/ notify_postgres[:name] connection_string="host=hostname port=2832 user=psqluser password=psqlpass dbname=bucketevents"
|
||||
> ```
|
||||
>
|
||||
> Please make sure this step is carried out, without this step PostgreSQL notification targets will not work,
|
||||
@@ -973,9 +972,8 @@ key | value
|
||||
> database (string) database name (used only if `dsn_string` is empty)
|
||||
> ```
|
||||
>
|
||||
> These are now deprecated, if you plan to upgrade to any releases after _RELEASE.2020-04-10T03-34-42Z_ make sure
|
||||
> to migrate to only using _dsn_string_ option. To migrate, once you have upgraded all the servers use the
|
||||
> following command to update the existing notification targets.
|
||||
> These are now deprecated. SILO does not migrate an enabled target that only has these fields, so convert it to
|
||||
> _dsn_string_ before starting SILO. On the old server, use the following command to update the target.
|
||||
>
|
||||
> ```
|
||||
> mc admin config set mysilo/ notify_mysql[:name] dsn_string="mysqluser:mysqlpass@tcp(localhost:2832)/bucketevents"
|
||||
@@ -1045,7 +1043,7 @@ Before updating the configuration, let's start with `mc admin config get` comman
|
||||
|
||||
```sh
|
||||
$ mc admin config get mysilo/ notify_mysql
|
||||
notify_mysql:myinstance enable=off format=namespace host= port= username= password= database= dsn_string= table= queue_dir= queue_limit=0
|
||||
notify_mysql:myinstance enable=off format=namespace dsn_string= table= queue_dir= queue_limit=0
|
||||
```
|
||||
|
||||
Use `mc admin config set` command to update MySQL notification configuration for the deployment with `dsn_string` parameter:
|
||||
|
||||
@@ -96,6 +96,12 @@ The access key provided for the replication *target* cluster should have these m
|
||||
|
||||
Please note that the permissions required by the admin user on the target cluster can be more fine grained to exclude permissions like "s3:ReplicateDelete", "s3:GetBucketObjectLockConfiguration" etc depending on whether delete replication rules are set up or if object locking is disabled on `destbucket`. The above policies assume that replication of objects, tags and delete marker replication are all enabled on object lock enabled buckets. A sample script to setup replication is provided [here](https://github.com/pgsty/silo/blob/main/docs/bucket/replication/setup_replication.sh)
|
||||
|
||||
The target replication credential continues to authorize replicated deletes with
|
||||
`s3:DeleteObject` plus `s3:ReplicateDelete`; it does not need
|
||||
`s3:DeleteObjectVersion`. This internal receiver contract is deliberately
|
||||
separate from ordinary S3 requests: a client deleting an explicitly named
|
||||
version, including `versionId=null`, must have `s3:DeleteObjectVersion`.
|
||||
|
||||
To set up replication from `srcbucket` on the `mysilo` cluster to `destbucket`
|
||||
on a target Silo cluster at `https://replica-endpoint:9000`, use:
|
||||
```
|
||||
@@ -200,6 +206,10 @@ To add a replication rule allowing both delete marker replication, versioned del
|
||||
|
||||
Additional permission of "s3:ReplicateDelete" action would need to be specified on the access key configured for the target cluster if Delete Marker replication or versioned delete replication is enabled.
|
||||
|
||||
An explicit deny on `s3:DeleteObjectVersion` still blocks the corresponding
|
||||
replicated version purge. An allow is not otherwise required for the target
|
||||
replication credential.
|
||||
|
||||
```
|
||||
mc replicate add mysilo/srcbucket/Tax --priority 1 --remote-bucket `remote-target` --tags "Year=2019&Company=AcmeCorp" --storage-class "STANDARD" --replicate "delete,delete-marker"
|
||||
Replication configuration applied successfully to mysilo/srcbucket.
|
||||
|
||||
@@ -88,11 +88,7 @@ echo "=== mysilo2"
|
||||
|
||||
versionId="$(./mc ls --json --versions mysilo1/testbucket/dir/ | tail -n1 | jq -r .versionId)"
|
||||
|
||||
export AWS_ACCESS_KEY_ID=minioadmin
|
||||
export AWS_SECRET_ACCESS_KEY=minioadmin
|
||||
export AWS_REGION=us-east-1
|
||||
|
||||
aws s3api --endpoint-url http://localhost:9001 delete-object --bucket testbucket --key dir/file --version-id "$versionId"
|
||||
./mc rm --version-id "$versionId" mysilo1/testbucket/dir/file
|
||||
|
||||
./mc ls -r --versions mysilo1/testbucket >/tmp/mysilo1.txt
|
||||
./mc ls -r --versions mysilo2/testbucket >/tmp/mysilo2.txt
|
||||
@@ -117,6 +113,76 @@ if [ $ret -ne 0 ]; then
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Verify the documented least-privilege target policy. Explicit version
|
||||
# deletion on the receiver is replication traffic, so the target credential
|
||||
# needs DeleteObject + ReplicateDelete but not DeleteObjectVersion.
|
||||
./mc mb mysilo1/leastpriv/ mysilo2/leastpriv/ --with-versioning
|
||||
./mc admin user add mysilo2 repluser repluser123
|
||||
cat >/tmp/xl/replpolicy.json <<'EOF'
|
||||
{
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:GetReplicationConfiguration",
|
||||
"s3:ListBucket",
|
||||
"s3:ListBucketMultipartUploads",
|
||||
"s3:GetBucketLocation",
|
||||
"s3:GetBucketVersioning"
|
||||
],
|
||||
"Resource": ["arn:aws:s3:::leastpriv"]
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": [
|
||||
"s3:GetReplicationConfiguration",
|
||||
"s3:ReplicateTags",
|
||||
"s3:AbortMultipartUpload",
|
||||
"s3:GetObject",
|
||||
"s3:GetObjectVersion",
|
||||
"s3:GetObjectVersionTagging",
|
||||
"s3:PutObject",
|
||||
"s3:DeleteObject",
|
||||
"s3:ReplicateObject",
|
||||
"s3:ReplicateDelete"
|
||||
],
|
||||
"Resource": ["arn:aws:s3:::leastpriv/*"]
|
||||
}
|
||||
]
|
||||
}
|
||||
EOF
|
||||
./mc admin policy create mysilo2 replpolicy /tmp/xl/replpolicy.json
|
||||
./mc admin policy attach mysilo2 replpolicy --user repluser
|
||||
./mc replicate add mysilo1/leastpriv --remote-bucket http://repluser:repluser123@localhost:9002/leastpriv/ --priority 1 --replicate delete,delete-marker
|
||||
|
||||
./mc cp README.md mysilo1/leastpriv/dir/file
|
||||
./mc cp README.md mysilo1/leastpriv/dir/file
|
||||
sleep 1s
|
||||
|
||||
leastPrivVersionId="$(./mc ls --json --versions mysilo1/leastpriv/dir/ | tail -n1 | jq -r .versionId)"
|
||||
./mc rm --version-id "$leastPrivVersionId" mysilo1/leastpriv/dir/file
|
||||
sleep 1s
|
||||
./mc ls -r --versions mysilo1/leastpriv >/tmp/leastpriv1.txt
|
||||
./mc ls -r --versions mysilo2/leastpriv >/tmp/leastpriv2.txt
|
||||
out=$(diff -qpruN /tmp/leastpriv1.txt /tmp/leastpriv2.txt)
|
||||
ret=$?
|
||||
if [ $ret -ne 0 ]; then
|
||||
echo "BUG: least-privilege version delete did not replicate: $out"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
./mc rm mysilo1/leastpriv/dir/file
|
||||
sleep 1s
|
||||
./mc ls -r --versions mysilo1/leastpriv >/tmp/leastpriv1.txt
|
||||
./mc ls -r --versions mysilo2/leastpriv >/tmp/leastpriv2.txt
|
||||
out=$(diff -qpruN /tmp/leastpriv1.txt /tmp/leastpriv2.txt)
|
||||
ret=$?
|
||||
if [ $ret -ne 0 ]; then
|
||||
echo "BUG: least-privilege delete marker did not replicate: $out"
|
||||
exit 1
|
||||
fi
|
||||
|
||||
# Test listing of non replicated permanent deletes
|
||||
|
||||
set -x
|
||||
@@ -129,7 +195,7 @@ versionId="$(./mc ls --json --versions mysilo1/foobucket/dir/ | jq -r .versionId
|
||||
|
||||
kill ${pid2} && wait ${pid2} || true
|
||||
|
||||
aws s3api --endpoint-url http://localhost:9001 delete-object --bucket foobucket --key dir/file --version-id "$versionId"
|
||||
./mc rm --version-id "$versionId" mysilo1/foobucket/dir/file
|
||||
|
||||
out="$(./mc ls mysilo1/foobucket/dir/)"
|
||||
if [ "$out" != "" ]; then
|
||||
|
||||
@@ -358,7 +358,7 @@ func (z *xlMetaV2VersionHeaderV2) UnmarshalMsg(bts []byte) (o []byte, e error) {
|
||||
e = msgp.ArrayError{Wanted: 5, Got: zb0001}
|
||||
return o, e
|
||||
}
|
||||
bts, e = msgp.ReadExactBytes(bts, (z.VersionID)[:])
|
||||
bts, e = msgp.ReadExactBytes(bts, z.VersionID[:])
|
||||
if e != nil {
|
||||
e = msgp.WrapError(e, "VersionID")
|
||||
return o, e
|
||||
@@ -368,7 +368,7 @@ func (z *xlMetaV2VersionHeaderV2) UnmarshalMsg(bts []byte) (o []byte, e error) {
|
||||
e = msgp.WrapError(e, "ModTime")
|
||||
return o, e
|
||||
}
|
||||
bts, e = msgp.ReadExactBytes(bts, (z.Signature)[:])
|
||||
bts, e = msgp.ReadExactBytes(bts, z.Signature[:])
|
||||
if e != nil {
|
||||
e = msgp.WrapError(e, "Signature")
|
||||
return o, e
|
||||
|
||||
@@ -745,7 +745,7 @@ func (z *xlMetaV2VersionHeaderV2) UnmarshalMsg(bts []byte, hdrVer uint) (o []byt
|
||||
err = msgp.ArrayError{Wanted: want, Got: zb0001}
|
||||
return o, err
|
||||
}
|
||||
bts, err = msgp.ReadExactBytes(bts, (z.VersionID)[:])
|
||||
bts, err = msgp.ReadExactBytes(bts, z.VersionID[:])
|
||||
if err != nil {
|
||||
err = msgp.WrapError(err, "VersionID")
|
||||
return o, err
|
||||
@@ -755,7 +755,7 @@ func (z *xlMetaV2VersionHeaderV2) UnmarshalMsg(bts []byte, hdrVer uint) (o []byt
|
||||
err = msgp.WrapError(err, "ModTime")
|
||||
return o, err
|
||||
}
|
||||
bts, err = msgp.ReadExactBytes(bts, (z.Signature)[:])
|
||||
bts, err = msgp.ReadExactBytes(bts, z.Signature[:])
|
||||
if err != nil {
|
||||
err = msgp.WrapError(err, "Signature")
|
||||
return o, err
|
||||
|
||||
@@ -4,6 +4,14 @@ This document summarizes fork-specific security fixes and closely related upgrad
|
||||
|
||||
Entries carry a CVE identifier where one exists. Where none does, they carry a fork-local `SN-<year>-<sequence>` identifier so that a finding without a CVE can still be referenced stably from release notes, commits and issues. An `SN-` identifier is **not** a CVE and is not registered in any vulnerability database; it is deliberately not written in CVE form so that scanners do not mistake it for one. Upstream `minio/minio` is archived, so for findings in inherited code there is no upstream maintainer to coordinate a CVE assignment with. `SN-2026-001` is the streaming-flush regression in `trackingResponseWriter`, which is a reliability defect rather than a security one and is tracked in the release notes rather than here.
|
||||
|
||||
## Inherited upstream advisory baseline
|
||||
|
||||
The first Silo community release was cut from upstream history that already contained the following security fix. Upstream and Silo links are both recorded even when the fork preserves the same commit object and SHA; that identity is the inheritance evidence, not a claim that Silo independently reimplemented the patch.
|
||||
|
||||
| ID | Upstream remediation | Silo inheritance | Regression evidence | Release / operator note |
|
||||
| :-- | :-- | :-- | :-- | :-- |
|
||||
| [CVE-2025-62506](https://github.com/advisories/GHSA-jjjj-jwhf-8rgr) | [minio/minio#21642](https://github.com/minio/minio/pull/21642), merged as [`c1a49490`](https://github.com/minio/minio/commit/c1a49490c78e9c3ebcad86ba0662319138ace190) | The same commit object is present as [`pgsty/silo@c1a49490`](https://github.com/pgsty/silo/commit/c1a49490c78e9c3ebcad86ba0662319138ace190) | The inherited [service-account](https://github.com/pgsty/silo/blob/c1a49490c78e9c3ebcad86ba0662319138ace190/cmd/admin-handlers-users_test.go#L211-L212) and [STS](https://github.com/pgsty/silo/blob/c1a49490c78e9c3ebcad86ba0662319138ace190/cmd/sts-handlers_test.go#L45-L46) regression groups run for root and non-root parents through `go test ./cmd` | Resets `DenyOnly` while evaluating a restricted session policy so service or STS accounts cannot mint an unrestricted child service account. Upstream first fixed this in [`RELEASE.2025-10-15T17-29-55Z`](https://github.com/minio/minio/releases/tag/RELEASE.2025-10-15T17-29-55Z); every Silo community release, beginning with [`RELEASE.2025-12-03T12-00-00Z`](https://github.com/pgsty/silo/releases/tag/RELEASE.2025-12-03T12-00-00Z), contains it. Operators migrating from an older upstream build should upgrade and audit service accounts created by restricted service or STS identities. |
|
||||
|
||||
## Advisories since `RELEASE.2026-03-21T00-00-00Z`
|
||||
|
||||
| ID | Fixed by | Affected area | Remote exploitability | Summary | Upgrade / workaround notes |
|
||||
@@ -19,6 +27,7 @@ Entries carry a CVE identifier where one exists. Where none does, they carry a f
|
||||
| `SN-2026-003` | [`silo-pkg v3.11.0`](https://github.com/pgsty/silo-pkg/releases/tag/v3.11.0) and [`2f55347f7`](https://github.com/pgsty/minio/commit/2f55347f78352aed8e08866d370c9426c73362cf) | S3/IAM bucket-policy condition values | Yes (policy-dependent) | Prevents raw request entries that spell condition-key names from shadowing or synthesizing internal condition values; confines `s3:signatureAge` to verified SigV4 presigned requests; separates query-only list fields from header-backed `x-amz-*` fields; and stops client request tags from impersonating stored existing-object tags. | The compatible query form remains for storage class and upload tagging on handlers that consume it; an explicitly present header wins, including an empty header. The historical `X-Amz-Tagging` Header mapping remains a client-supplied `RequestObjectTag` source, so use request-tag conditions only on operations that consume tags. Header-only `x-amz-*` policy keys no longer accept query substitutes. `aws:SourceIp` was left following the existing forwarding-header trust model; that model is addressed separately in the next row. See [Condition value sources and precedence](https://silo.pgsty.com/administration/identity-access-management/policy-based-access-control/#condition-value-sources). |
|
||||
| Not a vulnerability | `fe6dc4780` | Client source address (`aws:SourceIp`, audit `remotehost`, event notification `Host`) | N/A -- opt-in hardening | Adds an enforceable forwarded-header trust boundary, `MINIO_API_TRUSTED_PROXIES`. Set to a list of addresses or CIDR blocks, forwarded headers are believed only from those peers and forwarding chains are read right-to-left past listed hops -- which also stops the client-supplied left-most entry that an appending proxy (the stock nginx `$proxy_add_x_forwarded_for` recipe, or HAProxy's added second header line) leaves in place. Set to `none`, no forwarded header is believed at all. This is the guarantee `_MINIO_API_XFF_HEADER=off` never provided: it suppresses `X-Forwarded-For` alone, so `X-Real-IP` and RFC 7239 `Forwarded` remain one-line substitutions for anyone that setting was meant to stop. | **No behaviour change for any existing deployment**, so there is nothing to do on upgrade unless you want the new boundary. Not assigned a CVE: the default matches upstream, and upstream's own position (maintainer response in [discussion #17878](https://github.com/minio/minio/discussions/17878), Aug 2023) is that IP-based restrictions are impractical without reliable source-IP visibility. The gap being closed is that this was never written anywhere an operator would find it -- an `IpAddress` condition is accepted and behaves as though it works. **If you use `IpAddress` or `NotIpAddress` conditions, note that they were not enforceable before this change**, including behind a reverse proxy whose `X-Forwarded-For` recipe appends rather than overwrites. If you do not, the change affects only the accuracy of client addresses in logs. The new variable is opt-in and inert when unset; `_MINIO_API_XFF_HEADER` keeps its exact upstream semantics, and upstream's `TestXFFDisabled` is retained unmodified as the proof. An `IpAddress` condition remains unenforceable by default against a client with direct network access to the API port -- that is the condition the allowlist exists to fix, not a regression introduced here. When enabling the allowlist: it must name proxies, not the subnet they sit in, because entries are skipped while walking the chain, so a range that also covers clients lets those clients forge. Multi-node deployments must include their own node addresses, since MinIO forwards some requests between nodes and a client can force a hop through the `ListObjectsV2` continuation token; prefer the allowlist over `none` on a cluster for that reason. Loopback is always trusted as a peer so FTP and SFTP keep attributing their sessions. A malformed value stops startup, as does one that names no proxy at all (`","`) or one whose `env://` remote could not be read -- `env.Get` discards that error and yields an empty string, which would otherwise read as unset. Whitespace-only remains equivalent to unset. The policy is read after `MINIO_CONFIG_ENV_FILE` is loaded so environment-file deployments are covered; `_MINIO_API_XFF_HEADER` deliberately keeps upstream's earlier read timing, where a value written into an environment file is ignored. `MINIO_IDENTITY_LDAP_STS_TRUSTED_PROXIES` now shares the same list parser, but is behaviourally untouched: the extraction is pure code motion, verified identical to the previous implementation across every combination of 37 allowlist values and 21 peer addresses. See [Client source address trust](source-address-trust.md). |
|
||||
| `SN-2026-004` | [`silo-pkg v3.11.0`](https://github.com/pgsty/silo-pkg/releases/tag/v3.11.0) and [`97b7d2804`](https://github.com/pgsty/minio/commit/97b7d28040d109061c0a46a4c01bfc7800a97cc1) | IAM policy evaluation of bucket-level actions | Yes (policy-dependent) | Withholds twelve sensitive bucket-level writes from an object-only resource pattern. The IAM matcher appended a trailing slash for bucket-level requests (empty object name), so a resource of `arn:aws:s3:::bucket/*` matched `"bucket/"` and authorized bucket-level actions it was never meant to reach -- upstream [minio/minio#20449](https://github.com/minio/minio/issues/20449). The bucket-policy evaluation path never had the slash and was already reference-correct. | **This is an authorization tightening; read this row before upgrading if you write your own bucket-scoped policies.** Withheld from `bucket/*` on `Allow` statements only: `PutBucketPolicy`, `DeleteBucketPolicy`, `PutBucketObjectLockConfiguration`, `PutBucketVersioning`, `PutReplicationConfiguration`, `PutBucketLifecycle`, `DeleteBucket`, `ForceDeleteBucket`, `PutBucketCors`, `DeleteBucketCors`, `PutBucketQOS`, `PutInventoryConfiguration`. Membership was decided by one question -- does reaching this action give the caller something its object-scoped grant does not already give it? -- because the bug only fires when the statement already grants the bucket action, which in practice means `s3:*`, so the affected principal already holds full object CRUD. Only actions that hand out access to others, defeat a protection aimed at write-holders, act under server credentials, outlive the grant, or destroy the bucket entity qualify. **Deliberately not withheld, and asserted by test so re-adding one is a deliberate act**: `ListBucket`, `GetBucketLocation` and the read/list family, `PutBucketTagging`, `PutBucketEncryption`, `PutBucketNotification`, and `CreateBucket` -- so `mc ls`, SDK session setup and ordinary tenant self-service keep working through `bucket/*`. Breaking those is what got upstream's own full fix reverted. **What to change**: add the bare bucket ARN (`arn:aws:s3:::bucket`) alongside `arn:aws:s3:::bucket/*` in any statement that legitimately grants one of the twelve. Built-in canned policies are unaffected (all use `Resource: "*"`). `Deny` statements are untouched, so no bucket lock is ever weakened, and `NotResource` exclusions keep their full reach. The hardening is monotone by construction rather than by argument: the protected path requires **both** the bare and the historical `"bucket/"` form to match, an intersection with the historical decision -- without that, a fixed-width wildcard such as `mybucke?` would match `"mybucket"` while never having matched `"mybucket/"`, and the hardening would have granted a write the buggy matcher refused. `MINIO_API_LEGACY_BUCKET_RESOURCE_MATCH=on` restores the historical behaviour in full; it is read once at startup. Still deferred to a migration-gated release: the read/list family, a startup audit naming affected policies, and a self-explaining denial log. |
|
||||
| `SN-2026-005` | [`silo-pkg v3.12.0`](https://github.com/pgsty/silo-pkg/releases/tag/v3.12.0) and [`eee05a17c`](https://github.com/pgsty/silo/commit/eee05a17c34a07cebb27220d12697be74c8bd617) | IAM named-policy and service-account policy writes | No direct remote exploit; policy-dependent | Rejects S3, S3 Tables, and KMS ARN namespace prefixes that name no resource, including their historical `*arn:...` serialization, in both `Resource` and `NotResource`. A resource-matching `Deny` using such a prefix could silently fail to deny, while an `Allow` with the prefix in `NotResource` could match far more broadly than intended. The guard applies when creating named policies and when creating or updating service-account session policies. | **This is an authorization tightening for new and updated policies.** Existing policies keep loading, matching, importing, and replicating with unchanged runtime behavior, but a policy containing one of these prefixes cannot be submitted unchanged; replace it with the intended concrete resource, or use an explicit wildcard such as `arn:aws:s3:::*` only when all resources are intended. Enabling the strict path also rejects an admin statement that combines `Resource` with `NotResource`, and rejects non-S3 resources on bucket-scoped admin actions. Here “bare ARN prefix” means a namespace with no resource after it (`arn:aws:s3:::`); it is distinct from the valid “bare bucket ARN” in `SN-2026-004` (`arn:aws:s3:::bucket`). IAM import, site-replication receive paths, stored-policy loading, and STS inline policies remain on the permissive compatibility path in this release. |
|
||||
|
||||
## Dependency security updates
|
||||
|
||||
|
||||
@@ -0,0 +1,584 @@
|
||||
# Per-Bucket CORS Site-Replication Convergence Design
|
||||
|
||||
## Status
|
||||
|
||||
- Issue: [pgsty/silo#75](https://github.com/pgsty/silo/issues/75)
|
||||
- Baseline: `e4e3007da6d7d1198a6a050e34f84566d40a9654`
|
||||
- Working branch: `codex/issue-75-cors-hardening`
|
||||
- Decision: CORS-specific deterministic last-writer-wins register, described below
|
||||
- Implementation state: B2 is commit `724f8703d`; the final B2+B3 integration is signed commit `0eebc928f` on the PR #80 branch and has passed combined local acceptance
|
||||
- Release state: PR #80 remains open; nothing is merged, tagged, packaged, published as an image, or deployed
|
||||
- Final design/implementation review: the B2 implementation was GO; the combined B2+B3 Opus 5 Max review found one test-build conflict and one legacy-metadata load risk, both corrected before combined testing
|
||||
|
||||
This document defines the replication state, ordering, persistence, status,
|
||||
healing, concurrency, compatibility, and test contract for per-bucket CORS.
|
||||
It is an implementation design record, not public upgrade or rollback guidance.
|
||||
Public operator documentation belongs in the separate `silo.pgsty.com`
|
||||
repository.
|
||||
|
||||
## Scope
|
||||
|
||||
This design covers the current-version CORS path:
|
||||
|
||||
```text
|
||||
PutBucketCors / DeleteBucketCors
|
||||
-> persist local CORS state
|
||||
-> BucketMetaHook
|
||||
-> madmin SRBucketMeta transport
|
||||
-> SRPeerReplicateBucketItem dispatch
|
||||
-> PeerBucketCorsConfigHandler
|
||||
-> SiteReplicationMetaInfo
|
||||
-> siteReplicationStatus
|
||||
-> latestCORSConfig
|
||||
-> healCORSMetadata
|
||||
```
|
||||
|
||||
It also covers retry, duplicate delivery, reordering, equal timestamps,
|
||||
initial site sync, missed DELETE recovery, cache reload, process restart, and
|
||||
concurrent CORS mutations on different nodes of one cluster.
|
||||
|
||||
The following are deliberately out of scope:
|
||||
|
||||
- redesigning the replication semantics of policy, tags, SSE, quota,
|
||||
versioning, or Object Lock;
|
||||
- eliminating lost updates between different bucket-metadata types that all
|
||||
rewrite `.metadata.bin`; this inherited problem is tracked by
|
||||
[pgsty/silo#77](https://github.com/pgsty/silo/issues/77);
|
||||
- mixed-version support that permits CORS writes before every site runs a
|
||||
CORS-aware binary;
|
||||
- public downgrade, rollback, and global-fallback documentation;
|
||||
- Console UI for bucket CORS.
|
||||
|
||||
### Adjacent issue-75 changes in the same candidate
|
||||
|
||||
The final issue-75 candidate also contains CORS work outside the LWW register
|
||||
itself:
|
||||
|
||||
- a strict, namespace-tolerant XML wire parser that rejects trailing roots,
|
||||
unknown/nested elements, duplicate singleton fields, invalid integer shape,
|
||||
and non-whitespace character data;
|
||||
- Unicode code-point ID counting, exact uppercase S3 methods, non-empty header
|
||||
elements, and int32-compatible MaxAge validation;
|
||||
- a single-`*` matcher and response-selection changes needed to distinguish a
|
||||
literal `*` origin from a patterned or explicit `null` match;
|
||||
- fail-closed metadata-error handling in the HTTP middleware;
|
||||
- complete allowed-method, explicit MaxAge=0, expose-header, credentials, and
|
||||
`Vary` preflight behavior;
|
||||
- checksum mismatch classification as `BadDigest`; and
|
||||
- parser, signed-handler, browser-response, and protocol adversarial tests.
|
||||
|
||||
Those changes share the same CORS release gate and are present in the reviewed
|
||||
diff, but they are not part of the replication conflict key or join algorithm.
|
||||
This document describes them only where they constrain replication validation
|
||||
or the final verification boundary.
|
||||
|
||||
## Confirmed Failures in the Pre-Fix Candidate
|
||||
|
||||
The pre-fix issue-75 candidate had four independently reproduced convergence
|
||||
defects:
|
||||
|
||||
1. Heal compared only payloads. If two sites stored identical payload bytes
|
||||
with different source timestamps, heal skipped the older site. The sites
|
||||
retained different ordering barriers and could disagree on a later delayed
|
||||
event.
|
||||
2. `isBucketMetadataEqual` used `strings.EqualFold` for base64. For example,
|
||||
`QQ==` and `qQ==` decode to different bytes but compared equal.
|
||||
3. Status derived `CorsCfgMismatch` from live payload count and payload set.
|
||||
It did not include source timestamp or tombstone state, so it could report
|
||||
divergent sites as converged and suppress healing.
|
||||
4. Equal-timestamp conflicting events had no stable tie-breaker. Peer apply
|
||||
accepted whichever event arrived last, while heal selected whichever map
|
||||
entry happened to be visited first.
|
||||
|
||||
Two additional correctness requirements followed from the state model:
|
||||
|
||||
- the read, compare, and save transition must be atomic across nodes in one
|
||||
cluster; and
|
||||
- a successful local PUT or DELETE must advance beyond an already stored
|
||||
future source timestamp instead of moving the local barrier backwards.
|
||||
|
||||
## Constraints
|
||||
|
||||
The minimum fix must satisfy these constraints:
|
||||
|
||||
- preserve `madmin.SRBucketMeta` and `madmin.SRBucketInfo` wire schemas;
|
||||
- preserve the exact source `UpdatedAt` on peer apply and heal;
|
||||
- distinguish a never-configured bucket from a persisted deletion;
|
||||
- converge without relying on event arrival order, map iteration order, or a
|
||||
particular site being the healer;
|
||||
- serialize CORS-versus-CORS transitions cluster-wide without introducing a
|
||||
broad bucket-metadata redesign;
|
||||
- reject malformed replication payloads before persistence;
|
||||
- remain idempotent under retry and initial-sync replay;
|
||||
- keep the replication state-machine change limited to CORS except for the
|
||||
directly shared base64 equality bug; do not infer that the same dirty
|
||||
candidate contains no adjacent CORS protocol or middleware changes.
|
||||
|
||||
## State Model
|
||||
|
||||
For one bucket lineage, the persisted CORS state is:
|
||||
|
||||
```text
|
||||
State = (Payload, SourceUpdatedAt)
|
||||
```
|
||||
|
||||
`BucketMetadata.Created` is not part of the conflict key. It is the lineage
|
||||
floor used to reject an event from an older incarnation of the bucket.
|
||||
|
||||
### State kinds
|
||||
|
||||
| Kind | Payload | `CorsConfigUpdatedAt` | Meaning |
|
||||
| --- | --- | --- | --- |
|
||||
| Baseline | nil | zero | CORS has never been configured for this bucket lineage |
|
||||
| Live | non-empty XML bytes | non-zero | A live per-bucket CORS configuration |
|
||||
| Tombstone | nil | non-zero | CORS was explicitly deleted at the source timestamp |
|
||||
|
||||
The baseline uses a zero timestamp deliberately. Defaulting a missing CORS
|
||||
timestamp to `CreatedAt` would make classification depend on two values that
|
||||
can be obtained from different cache/disk snapshots. It would also make a
|
||||
never-configured state indistinguishable from a deletion at bucket creation.
|
||||
|
||||
Per-bucket CORS and `CorsConfigUpdatedAt` were introduced together, so there
|
||||
is no released legacy live-CORS state that requires synthesizing a timestamp.
|
||||
|
||||
### Wire canonicalization
|
||||
|
||||
A non-nil wire payload must satisfy all of the following:
|
||||
|
||||
1. strict standard base64 decoding succeeds;
|
||||
2. re-encoding the decoded bytes produces exactly the received string;
|
||||
3. the decoded payload is non-empty;
|
||||
4. CORS XML parsing succeeds; and
|
||||
5. `cors.Config.Validate()` succeeds.
|
||||
|
||||
The canonical re-encode check rejects ignored newlines and alternate textual
|
||||
representations. Equality is therefore equality of decoded bytes, with exact
|
||||
base64 string equality remaining safe for the shared metadata helper.
|
||||
|
||||
An invalid wire value is not a candidate winner and is never propagated.
|
||||
Peer apply rejects it before any metadata write.
|
||||
|
||||
A bucket may nevertheless contain a CORS document written by a pre-release,
|
||||
more lenient build. Loading such metadata keeps policy, lifecycle, versioning,
|
||||
and the other bucket fields available, but stashes the CORS parse/validation
|
||||
error and exposes no active CORS config. CORS GET and middleware lookup return
|
||||
that error, so browser handling fails closed. A valid PUT or DELETE can repair
|
||||
the record; any attempt to save a newly invalid CORS document remains rejected.
|
||||
|
||||
## Deterministic Ordering
|
||||
|
||||
States use the following total order:
|
||||
|
||||
```text
|
||||
1. SourceUpdatedAt
|
||||
2. Kind: baseline < live < tombstone
|
||||
3. For live/live ties: lexicographic decoded payload bytes
|
||||
```
|
||||
|
||||
The greater state wins.
|
||||
|
||||
Consequences:
|
||||
|
||||
- a newer source event wins regardless of arrival order;
|
||||
- the same payload with a newer timestamp is a greater state and advances the
|
||||
ordering barrier;
|
||||
- a DELETE wins an equal-timestamp PUT/DELETE conflict;
|
||||
- two equal-timestamp live payloads choose the same bytewise winner at every
|
||||
site;
|
||||
- an exact duplicate is equal and therefore a no-op;
|
||||
- retry, reordering, and duplicate delivery cannot move local state backward.
|
||||
|
||||
The live-payload tie-breaker is not intended to identify the human's temporal
|
||||
intent. It supplies the deterministic result required when the timestamp has
|
||||
already failed to distinguish two writes.
|
||||
|
||||
## Why No Source-Site Tie-Breaker
|
||||
|
||||
The rejected source-site alternative ordered states by timestamp plus origin
|
||||
deployment ID. It would require a new origin field in madmin-go transport and
|
||||
a persisted origin field in `BucketMetadata`. That adds a dependency release,
|
||||
wire compatibility work, and an on-disk schema change without improving the
|
||||
convergence guarantee over the content-based total order.
|
||||
|
||||
If a future product requirement needs provenance-aware conflict explanation,
|
||||
the source-site design can be introduced as a versioned protocol. It is not
|
||||
required to make the current register converge.
|
||||
|
||||
## Bucket Lineage and `CreatedAt`
|
||||
|
||||
`CreatedAt` protects a recreated bucket from delayed metadata events belonging
|
||||
to the prior bucket incarnation:
|
||||
|
||||
```text
|
||||
if incoming.SourceUpdatedAt < local.CreatedAt:
|
||||
ignore and log once per bucket
|
||||
```
|
||||
|
||||
The floor is retained because removing it could install an old CORS grant on a
|
||||
new bucket with the same name. It is intentionally not used to classify the
|
||||
baseline.
|
||||
|
||||
For current-version site replication, local events are generated strictly
|
||||
after `max(CreatedAt, current CORS barrier)`, and bucket creation timestamps are
|
||||
propagated before initial metadata sync. A floor rejection therefore indicates
|
||||
a stale lineage event, clock/history corruption, or a mixed/unsupported setup.
|
||||
The rejection is observable through a bucket-scoped log-once message and the
|
||||
remaining status mismatch.
|
||||
|
||||
## Local Transition
|
||||
|
||||
PUT and DELETE use the same CORS-specific transition helper.
|
||||
|
||||
Under the bucket CORS namespace lock:
|
||||
|
||||
1. load the current `.metadata.bin` through the migration-aware parsed loader;
|
||||
2. validate the new live payload, if any;
|
||||
3. choose:
|
||||
|
||||
```text
|
||||
UpdatedAt = max(UTCNow, CreatedAt + epsilon, CurrentBarrier + epsilon)
|
||||
```
|
||||
|
||||
4. store either the live bytes or a nil tombstone with that timestamp;
|
||||
5. save and refresh the parsed cache; and
|
||||
6. release the lock before invoking `BucketMetaHook`.
|
||||
|
||||
This preserves HTTP semantics while ensuring a local administrative action is
|
||||
strictly greater than the state it observed, including a future-dated peer
|
||||
barrier caused by clock skew. The peer path deliberately uses a raw metadata
|
||||
read instead: it must preserve the exact zero baseline and reject missing
|
||||
metadata rather than implicitly creating a peer bucket record.
|
||||
|
||||
## Peer and Legacy-Bulk Transition
|
||||
|
||||
Typed CORS dispatch decodes and validates the payload, then performs this join
|
||||
under the same lock:
|
||||
|
||||
```text
|
||||
if incoming timestamp is zero:
|
||||
reject
|
||||
if incoming timestamp is before CreatedAt:
|
||||
ignore and log
|
||||
if incoming state <= local state:
|
||||
no-op
|
||||
otherwise:
|
||||
persist incoming payload and exact source timestamp
|
||||
```
|
||||
|
||||
The admin handler's legacy/default bulk metadata path can also carry a non-nil
|
||||
CORS field. It therefore takes the same CORS lock, applies strict decoding and
|
||||
validation, and uses the same state comparison before saving. A nil CORS field
|
||||
in that untyped legacy shape means "not included" and cannot represent a
|
||||
tombstone; current producers use the typed CORS event for deletion.
|
||||
|
||||
## Concurrency and Locking
|
||||
|
||||
The transition lock is:
|
||||
|
||||
```text
|
||||
.minio.sys / buckets/<bucket>/cors-config.lock
|
||||
```
|
||||
|
||||
It is a virtual distributed namespace lock. The name deliberately differs from
|
||||
the real `buckets/<bucket>/.metadata.bin` object because the metadata save path
|
||||
locks that object internally and namespace locks are not re-entrant.
|
||||
|
||||
The lock serializes every intentional current-version local, typed-peer,
|
||||
legacy-bulk, and local-heal CORS transition across nodes of one cluster. It
|
||||
cannot prevent an unrelated whole-record writer from restoring stale CORS
|
||||
columns. Residual paths include another metadata type's `Update`/`Delete`, a
|
||||
legacy bulk item whose nil CORS field means "not included",
|
||||
`ImportBucketMetadata`, and bucket-make metadata rewriting. Their inherited
|
||||
whole-record behavior is the separate architectural problem under issue #77.
|
||||
|
||||
No cross-site admin call or `BucketMetaHook` dispatch is made while holding the
|
||||
CORS lock. The metadata save can perform blocking intra-cluster notification
|
||||
fan-out before the lock is released. Local handlers release the lock before
|
||||
cross-site dispatch; reordered network delivery is handled by the total-order
|
||||
join.
|
||||
|
||||
## Dispatch and Retry
|
||||
|
||||
PUT sends a typed `SRBucketMetaTypeCorsConfig` event with canonical base64 XML
|
||||
and the local source timestamp. DELETE sends the same type with `Cors == nil`
|
||||
and the tombstone timestamp.
|
||||
|
||||
`BucketMetaHook` may deliver concurrently to sites, fail on a subset, or be
|
||||
retried by an external operation. The receiver transition is idempotent, so the
|
||||
transport does not need to impose a global event order.
|
||||
|
||||
Current-version admin dispatch routes the typed event directly to
|
||||
`PeerBucketCorsConfigHandler`. The legacy/default path is hardened only to
|
||||
prevent a non-nil CORS field from bypassing the join; it is not a tombstone
|
||||
compatibility protocol.
|
||||
|
||||
## Status Projection
|
||||
|
||||
`SiteReplicationMetaInfo` always exports `CorsConfigUpdatedAt`, including zero
|
||||
baseline and nil tombstone states. It exports `CorsConfig` only for a live
|
||||
payload.
|
||||
|
||||
Status considers sites converged if and only if every site has the same full
|
||||
CORS state:
|
||||
|
||||
```text
|
||||
(kind, decoded payload bytes, SourceUpdatedAt)
|
||||
```
|
||||
|
||||
Live payload counts remain useful for per-site summary totals, but they do not
|
||||
determine `CorsCfgMismatch`.
|
||||
|
||||
Examples:
|
||||
|
||||
| Site A | Site B | Mismatch |
|
||||
| --- | --- | --- |
|
||||
| baseline | baseline | no |
|
||||
| same live bytes at same timestamp | same live bytes at same timestamp | no |
|
||||
| same live bytes at different timestamps | same live bytes at different timestamps | yes |
|
||||
| same tombstone timestamp | same tombstone timestamp | no |
|
||||
| tombstones at different timestamps | tombstones at different timestamps | yes |
|
||||
| live | tombstone | yes |
|
||||
| invalid wire state | any state | yes |
|
||||
|
||||
## Winner Selection and Heal
|
||||
|
||||
Heal computes the maximum non-baseline valid state using the total order.
|
||||
Selection is independent of Go map iteration. Deployment ID is used only as a
|
||||
stable log-source choice when two sites already expose exactly equal states.
|
||||
|
||||
For each different site:
|
||||
|
||||
- the local site delegates to the normal peer CORS transition, preserving the
|
||||
source timestamp and lock discipline;
|
||||
- a remote site receives a typed `SRBucketMetaTypeCorsConfig` event with the
|
||||
winner's canonical payload or nil tombstone and exact timestamp.
|
||||
|
||||
Payload equality alone is insufficient. A site with identical bytes at an
|
||||
older timestamp is healed so it acquires the same future ordering barrier.
|
||||
|
||||
If every reported state is baseline, there is no event to propagate. If every
|
||||
reported state is invalid, status remains mismatched and heal does not select
|
||||
corrupt input as a source.
|
||||
|
||||
## Initial Sync
|
||||
|
||||
Initial sync emits:
|
||||
|
||||
- a live event when `CorsConfigUpdatedAt` is non-zero and payload is live;
|
||||
- a tombstone event when `CorsConfigUpdatedAt` is non-zero and payload is nil;
|
||||
- no event for the zero baseline.
|
||||
|
||||
Replaying initial sync is idempotent. A missed DELETE is recoverable because
|
||||
the tombstone is part of the snapshot rather than being inferred from the
|
||||
absence of a live payload.
|
||||
|
||||
All sites must run the CORS-aware implementation before enabling or mutating
|
||||
per-bucket CORS. An older receiver can route an unknown typed event through a
|
||||
legacy path that cannot represent deletion and does not provide this ordering
|
||||
contract.
|
||||
|
||||
## Persistence and Restart
|
||||
|
||||
`CorsConfigXML` and `CorsConfigUpdatedAt` are persisted together in
|
||||
`BucketMetadata` msgpack. Zero time round-trips as zero; CORS is deliberately
|
||||
not defaulted to `CreatedAt` during load.
|
||||
|
||||
`BucketMetadata.Save` parses the live CORS XML before writing and before the
|
||||
metadata system replaces the local cache. Therefore a rejected payload cannot
|
||||
poison disk or cache, and a successful peer/heal transition immediately serves
|
||||
the newly persisted parsed configuration.
|
||||
|
||||
After cache removal or process restart:
|
||||
|
||||
- a live state restores the same parsed rules and source timestamp;
|
||||
- a tombstone restores nil payload plus its non-zero timestamp;
|
||||
- a baseline remains nil plus zero timestamp.
|
||||
- a legacy-invalid raw document leaves the non-CORS bucket metadata readable,
|
||||
disables per-bucket CORS fail-closed, and remains repairable through a valid
|
||||
CORS PUT or DELETE.
|
||||
|
||||
## Error Handling
|
||||
|
||||
| Error | Behavior |
|
||||
| --- | --- |
|
||||
| zero source timestamp on a peer live/delete event | reject the event |
|
||||
| invalid/non-canonical base64 | reject before locking or saving |
|
||||
| empty non-nil payload | reject |
|
||||
| malformed XML | reject before saving |
|
||||
| semantically invalid CORS rules | reject before saving |
|
||||
| legacy-invalid CORS already on disk | load other metadata, return a CORS-specific error, and permit CORS replacement or deletion |
|
||||
| event before bucket `CreatedAt` | ignore and log once per bucket |
|
||||
| missing bucket metadata | return an error; do not create metadata implicitly |
|
||||
| exact duplicate or lower state | successful no-op |
|
||||
| remote heal failure | log the peer error; future heal cycles retry |
|
||||
|
||||
## Alternatives Considered
|
||||
|
||||
### Timestamp only
|
||||
|
||||
Rejected. Ignoring or accepting every equal-timestamp conflict leaves an
|
||||
already divergent pair without a deterministic repair rule.
|
||||
|
||||
### Timestamp plus source deployment ID
|
||||
|
||||
Rejected for the current protocol. It is convergent, but requires madmin-go,
|
||||
wire, and persisted-schema changes without improving convergence over the
|
||||
selected total order.
|
||||
|
||||
### Payload-only status and heal
|
||||
|
||||
Rejected. It cannot distinguish ordering barriers and suppresses the exact
|
||||
heal needed to make later event acceptance consistent.
|
||||
|
||||
### Default baseline timestamp to bucket creation
|
||||
|
||||
Rejected. It conflates baseline classification with a mutable value that may
|
||||
come from a different snapshot and can turn a never-configured site into a
|
||||
false tombstone source.
|
||||
|
||||
### Reuse `.metadata.bin` as the transition lock
|
||||
|
||||
Rejected. The save path takes the same namespace lock internally; reusing it
|
||||
would self-deadlock.
|
||||
|
||||
### Redesign every bucket metadata type together
|
||||
|
||||
Rejected for issue #75. Neighboring metadata types have related inherited
|
||||
patterns but different delete, validation, and compatibility semantics. They
|
||||
require focused reproductions under issue #77.
|
||||
|
||||
## Invariants
|
||||
|
||||
The implementation is acceptable only while all of these invariants hold:
|
||||
|
||||
1. Zero timestamp plus nil payload is the only baseline representation.
|
||||
2. Nil payload plus non-zero timestamp is a durable tombstone.
|
||||
3. A live payload has canonical base64 on the wire, valid CORS XML, and a
|
||||
non-zero source timestamp.
|
||||
4. Every intentional current-version CORS state transition is serialized by
|
||||
the CORS namespace lock from disk read through state comparison and save;
|
||||
unrelated whole-record overwrite risk remains explicitly under issue #77.
|
||||
5. Peer apply and heal never replace local state with a lower or equal state.
|
||||
6. Local PUT and DELETE create a state strictly greater than the state observed
|
||||
under the lock.
|
||||
7. A peer event before local bucket creation cannot modify the new bucket
|
||||
lineage.
|
||||
8. Status reports convergence only for identical full states.
|
||||
9. Heal selects the same maximum regardless of arrival order, site, or map
|
||||
iteration order.
|
||||
10. Same-payload/newer-timestamp heal advances the older barrier.
|
||||
11. Initial sync and retry preserve tombstones and source timestamps.
|
||||
12. Disk reload and cache reload preserve state kind, payload, and timestamp.
|
||||
13. A legacy-invalid CORS document cannot activate global fallback, hide other
|
||||
bucket metadata, or prevent a valid CORS PUT/DELETE repair.
|
||||
|
||||
## Test Contract
|
||||
|
||||
The required test matrix is:
|
||||
|
||||
| Area | Required evidence |
|
||||
| --- | --- |
|
||||
| Wire | canonical base64 accepted; case-different decoded bytes differ; malformed and non-canonical base64 rejected |
|
||||
| Validation | invalid XML and semantically invalid origin/method/rule rejected without mutation |
|
||||
| Strict wire | standard S3 namespace accepted; trailing root, unknown/nested elements, duplicate singleton fields, lowercase methods, byte-counted Unicode IDs, and invalid MaxAge rejected |
|
||||
| Ordering | older event ignored; newer event applied; duplicate no-op; equal live/live order-independent; equal PUT/DELETE chooses tombstone |
|
||||
| Barrier | same payload with newer timestamp is persisted and healed |
|
||||
| Tombstone | delayed PUT cannot resurrect; missed DELETE wins heal; repeated DELETE is idempotent |
|
||||
| Status | baseline, live, tombstone, payload mismatch, and timestamp-only mismatch classified correctly |
|
||||
| Winner | three-site equal-timestamp selection remains deterministic across repeated map iteration |
|
||||
| Concurrency | concurrent peer and legacy-bulk events converge to the total-order maximum |
|
||||
| Local concurrency | concurrent local PUT/DELETE timestamps are unique and final state matches the last serialized transition |
|
||||
| Initial sync | baseline omitted; live and tombstone emitted with exact source timestamp |
|
||||
| Lineage | pre-creation event ignored; post-creation event applied |
|
||||
| Restart | cache removal/disk reload preserves tombstone or live state and status timestamp |
|
||||
| Legacy repair | a lenient historical document loads fail-closed without hiding other metadata and can be deleted or replaced |
|
||||
| Full seam | signed admin dispatch -> peer apply -> real status collection -> local heal -> cache reload -> remote heal dispatch |
|
||||
|
||||
## Local Verification Record
|
||||
|
||||
The committed B2 implementation passed:
|
||||
|
||||
- the supplied adversarial base64 and same-payload/newer-timestamp tests;
|
||||
- focused CORS normal tests;
|
||||
- focused CORS race tests;
|
||||
- `go test ./internal/bucket/cors` and its race run;
|
||||
- `go test ./cmd -count=1`;
|
||||
- `go vet ./...`;
|
||||
- `go build ./...`;
|
||||
- repository-configured golangci-lint v2.13.1 with zero issues;
|
||||
- gofmt and `git diff --check`;
|
||||
- a signed admin dispatch -> apply -> status -> heal -> cache reload test.
|
||||
|
||||
After integrating B3 and resolving overlap, the frozen combination passed:
|
||||
|
||||
- focused strict-parser, validation, middleware, replication, namespace,
|
||||
legacy-repair, and race tests;
|
||||
- CI-tagged `go test ./...`, full vet/build, module verification, pinned lint,
|
||||
and rebrand/compatibility checks;
|
||||
- a real local two-site deployment with two nodes per site, including
|
||||
bidirectional replacement, a site missing DELETE while offline, restart
|
||||
heal, and a second restart preserving the tombstone; and
|
||||
- raw SigV4 wire probes that reject a lowercase method and trailing XML root,
|
||||
accept a 255-code-point Unicode ID, and replicate the accepted config.
|
||||
|
||||
The public EN/ZH design records pass a warning-fatal Hugo build, rendered link
|
||||
checking, and local browser QA. These results are acceptance evidence, not a
|
||||
release, deployment, tag, or production claim.
|
||||
|
||||
The repository `make lint` bootstrap could not download its private copy of
|
||||
golangci-lint because the network returned HTTP status 000. The same exact
|
||||
v2.13.1 binary already installed locally was used with the Makefile's build
|
||||
tags, timeout, and configuration and reported zero issues.
|
||||
|
||||
## Independent Review Record
|
||||
|
||||
Four read-only local Claude Code reviews used canonical model
|
||||
`claude-opus-5` at `max` effort.
|
||||
|
||||
The first review rejected the pre-fix candidate and identified the unsafe
|
||||
CreatedAt-based baseline, missing deterministic tie-break, missing atomic join,
|
||||
non-monotonic local barrier, timestamp-blind status, and initial-sync tombstone
|
||||
gap. The selected C-prime model incorporated the valid findings while rejecting
|
||||
the suggestion to rewrite normal source timestamps.
|
||||
|
||||
The second review found no P0. Its `GO WITH FIXES` findings were peer semantic
|
||||
validation, the legacy/default admin mutation path bypassing the CORS lock and
|
||||
join, CreatedAt-floor observability, and missing tests for invalid XML, lineage,
|
||||
and concurrent local transitions. Those required changes and tests are now in
|
||||
the working tree.
|
||||
|
||||
The final review examined this design and the exact dirty diff, independently
|
||||
reran build, vet, lint, normal tests, and race tests, and found no P0 or P1.
|
||||
Its verdict was `GO WITH FIXES`: the implementation was explicitly judged GO,
|
||||
while five design-document statements required correction. It also suggested
|
||||
an optional status hardening so semantically invalid canonical payloads are
|
||||
not selected and retransmitted. The hardening and all mandatory documentation
|
||||
corrections are incorporated in the current tree. The final selected solution
|
||||
is therefore the C-prime register and invariants recorded in this document.
|
||||
|
||||
The fourth review examined the resolved B2+B3 combination. It confirmed that
|
||||
the C-prime register, strict wire parser, MaxAge presence, wildcard credentials,
|
||||
Origin-null marker, rejected-preflight `Vary`, checksum classification, and
|
||||
peer validation can coexist. It found a conflict-resolution test helper typo
|
||||
and the risk that strict parsing could make all bucket metadata unavailable for
|
||||
a document accepted by a lenient development build. The helper was corrected;
|
||||
metadata loading now stashes a CORS-specific error, fails browser behavior
|
||||
closed, rejects new invalid saves, and allows a valid CORS PUT/DELETE repair.
|
||||
|
||||
## Release Gates
|
||||
|
||||
An implementation-level GO means only that the local CORS state machine and
|
||||
tests satisfy this document. It does not authorize a release.
|
||||
|
||||
Before closing issue #75 or publishing a server artifact:
|
||||
|
||||
1. commit the exact reviewed implementation and design with DCO sign-off;
|
||||
2. push a focused branch and run remote PR CI;
|
||||
3. merge and confirm main CI on the merge commit;
|
||||
4. finish public EN/ZH upgrade, fallback, and downgrade documentation in
|
||||
`silo.pgsty.com`;
|
||||
5. run a real two-site process test for PUT, DELETE, simultaneous conflict,
|
||||
offline peer restart, status, and heal;
|
||||
6. verify no release tag or image contains an intermediate candidate; and
|
||||
7. treat package, image, SBOM, signature, canary, and production verification
|
||||
as separate gates.
|
||||
@@ -1,19 +1,24 @@
|
||||
module github.com/minio/minio
|
||||
|
||||
go 1.26.5
|
||||
go 1.27.0
|
||||
|
||||
// Use Pigsty's SILO Console v2.1.1 release while preserving upstream import paths.
|
||||
// The pseudo-version pins v2.1.1's commit because the compatible module path has no /v2 suffix.
|
||||
replace github.com/minio/console => github.com/pgsty/silo-console v0.0.0-20260806061103-72fc0a5ea52a
|
||||
// Use PGSTY's maintained Silo Go SDK while preserving upstream import paths.
|
||||
// Keep the required version on a real upstream tag because replace directives
|
||||
// are ignored when this module is consumed as a dependency.
|
||||
replace github.com/minio/minio-go/v7 => github.com/pgsty/silo-go/v7 v7.3.1
|
||||
|
||||
// Use Pigsty's SILO Console v2.2.1 release while preserving upstream import paths.
|
||||
// The pseudo-version pins v2.2.1's commit because the compatible module path has no /v2 suffix.
|
||||
replace github.com/minio/console => github.com/pgsty/silo-console v0.0.0-20260829111139-e07ef01ab8bf
|
||||
|
||||
// Use Pigsty's maintained mc fork for Console's embedded client code.
|
||||
replace github.com/minio/mc => github.com/pgsty/mc v0.0.0-20260801042411-ad10a2a10b76
|
||||
replace github.com/minio/mc => github.com/pgsty/mc v0.0.0-20260829103737-5ed037ef4ec1
|
||||
|
||||
// Use Pigsty's maintained SILO package fork while preserving upstream import paths.
|
||||
// This retains the LDAP TLS fix tracked in https://github.com/pgsty/silo/issues/15.
|
||||
// v3.11.0 follows upstream minio/pkg's 3.11 line and carries the
|
||||
// minio/minio#20449 bucket-write boundary hardening.
|
||||
replace github.com/minio/pkg/v3 => github.com/pgsty/silo-pkg/v3 v3.11.0
|
||||
// v3.12.2 retains the minio/minio#20449 bucket-write boundary hardening,
|
||||
// rejects bare ARN prefixes on strict policy-write paths, and selects Silo Go v7.3.1.
|
||||
replace github.com/minio/pkg/v3 => github.com/pgsty/silo-pkg/v3 v3.12.3-0.20260829103855-748c94bf8ab7
|
||||
|
||||
// v22.7.0 does not compile on NetBSD because its unix implementation uses
|
||||
// CLOCK_MONOTONIC, which is unavailable there. Keep the last portable release
|
||||
@@ -37,7 +42,7 @@ require (
|
||||
github.com/beevik/ntp v1.5.0
|
||||
github.com/buger/jsonparser v1.1.2
|
||||
github.com/cespare/xxhash/v2 v2.3.0
|
||||
github.com/cheggaaa/pb v1.0.29
|
||||
github.com/cheggaaa/pb v1.0.30
|
||||
github.com/coreos/go-oidc/v3 v3.17.0
|
||||
github.com/coreos/go-systemd/v22 v22.7.0
|
||||
github.com/cosnicolaou/pbzip2 v1.0.6
|
||||
@@ -57,15 +62,15 @@ require (
|
||||
github.com/google/uuid v1.6.0
|
||||
github.com/inconshreveable/mousetrap v1.1.0
|
||||
github.com/json-iterator/go v1.1.12
|
||||
github.com/klauspost/compress v1.18.7
|
||||
github.com/klauspost/cpuid/v2 v2.3.0
|
||||
github.com/klauspost/compress v1.19.2
|
||||
github.com/klauspost/cpuid/v2 v2.4.0
|
||||
github.com/klauspost/filepathx v1.1.1
|
||||
github.com/klauspost/pgzip v1.2.6
|
||||
github.com/klauspost/readahead v1.4.0
|
||||
github.com/klauspost/reedsolomon v1.13.3
|
||||
github.com/lib/pq v1.10.9
|
||||
github.com/lithammer/shortuuid/v4 v4.2.0
|
||||
github.com/miekg/dns v1.1.72
|
||||
github.com/miekg/dns v1.1.73
|
||||
github.com/minio/cli v1.24.2
|
||||
github.com/minio/console v1.7.6
|
||||
github.com/minio/csvparser v1.0.0
|
||||
@@ -75,7 +80,7 @@ require (
|
||||
github.com/minio/kms-go/kes v0.3.1
|
||||
github.com/minio/kms-go/kms v0.6.0
|
||||
github.com/minio/madmin-go/v3 v3.0.110
|
||||
github.com/minio/minio-go/v7 v7.0.99
|
||||
github.com/minio/minio-go/v7 v7.3.0
|
||||
github.com/minio/mux v1.9.2
|
||||
github.com/minio/pkg/v3 v3.6.1
|
||||
github.com/minio/selfupdate v0.6.0
|
||||
@@ -90,9 +95,9 @@ require (
|
||||
github.com/ncw/directio v1.0.5
|
||||
github.com/nsqio/go-nsq v1.1.0
|
||||
github.com/philhofer/fwd v1.2.0
|
||||
github.com/pierrec/lz4/v4 v4.1.26
|
||||
github.com/pierrec/lz4/v4 v4.1.29
|
||||
github.com/pkg/errors v0.9.1
|
||||
github.com/pkg/sftp v1.13.10
|
||||
github.com/pkg/sftp v1.13.11
|
||||
github.com/pkg/xattr v0.4.12
|
||||
github.com/prometheus/client_golang v1.23.2
|
||||
github.com/prometheus/client_model v0.6.2
|
||||
@@ -108,13 +113,13 @@ require (
|
||||
github.com/valyala/bytebufferpool v1.0.0
|
||||
github.com/xdg/scram v1.0.5
|
||||
github.com/zeebo/xxh3 v1.1.0
|
||||
go.etcd.io/etcd/api/v3 v3.6.9
|
||||
go.etcd.io/etcd/client/v3 v3.6.9
|
||||
go.etcd.io/etcd/api/v3 v3.7.1
|
||||
go.etcd.io/etcd/client/v3 v3.7.1
|
||||
go.uber.org/atomic v1.11.0
|
||||
go.uber.org/zap v1.28.0
|
||||
go.yaml.in/yaml/v3 v3.0.5
|
||||
goftp.io/server/v2 v2.0.2
|
||||
golang.org/x/crypto v0.54.0
|
||||
goftp.io/server/v2 v2.0.3
|
||||
golang.org/x/crypto v0.55.0
|
||||
golang.org/x/oauth2 v0.36.0
|
||||
golang.org/x/sync v0.22.0
|
||||
golang.org/x/sys v0.47.0
|
||||
@@ -152,7 +157,7 @@ require (
|
||||
github.com/charmbracelet/colorprofile v0.4.3 // indirect
|
||||
github.com/charmbracelet/harmonica v0.2.0 // indirect
|
||||
github.com/charmbracelet/lipgloss v1.1.0 // indirect
|
||||
github.com/charmbracelet/x/ansi v0.11.6 // indirect
|
||||
github.com/charmbracelet/x/ansi v0.11.7 // indirect
|
||||
github.com/charmbracelet/x/cellbuf v0.0.15 // indirect
|
||||
github.com/charmbracelet/x/term v0.2.2 // indirect
|
||||
github.com/clipperhouse/displaywidth v0.11.0 // indirect
|
||||
@@ -171,7 +176,6 @@ require (
|
||||
github.com/fatih/structs v1.1.0 // indirect
|
||||
github.com/felixge/httpsnoop v1.0.4 // indirect
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8 // indirect
|
||||
github.com/go-ini/ini v1.67.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
|
||||
@@ -210,7 +214,6 @@ require (
|
||||
github.com/google/shlex v0.0.0-20191202100458-e7afc7fbc510 // indirect
|
||||
github.com/googleapis/enterprise-certificate-proxy v0.3.15 // indirect
|
||||
github.com/googleapis/gax-go/v2 v2.22.0 // indirect
|
||||
github.com/gorilla/mux v1.8.1 // indirect
|
||||
github.com/gorilla/websocket v1.5.4-0.20250319132907-e064f32e3674 // indirect
|
||||
github.com/grafana/regexp v0.0.0-20250905093917-f7b3be9d1853 // indirect
|
||||
github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect
|
||||
@@ -230,20 +233,19 @@ require (
|
||||
github.com/kr/fs v0.1.0 // indirect
|
||||
github.com/kylelemons/godebug v1.1.0 // indirect
|
||||
github.com/lestrrat-go/blackmagic v1.0.4 // indirect
|
||||
github.com/lestrrat-go/dsig v1.0.0 // indirect
|
||||
github.com/lestrrat-go/dsig v1.3.0 // indirect
|
||||
github.com/lestrrat-go/dsig-secp256k1 v1.0.0 // indirect
|
||||
github.com/lestrrat-go/httpcc v1.0.1 // indirect
|
||||
github.com/lestrrat-go/httprc/v3 v3.0.1 // indirect
|
||||
github.com/lestrrat-go/jwx/v3 v3.0.12 // indirect
|
||||
github.com/lestrrat-go/option v1.0.1 // indirect
|
||||
github.com/lestrrat-go/httprc/v3 v3.0.6 // indirect
|
||||
github.com/lestrrat-go/jwx/v3 v3.0.13 // indirect
|
||||
github.com/lestrrat-go/option/v2 v2.0.0 // indirect
|
||||
github.com/lucasb-eyer/go-colorful v1.3.0 // indirect
|
||||
github.com/lucasb-eyer/go-colorful v1.4.0 // indirect
|
||||
github.com/lufia/plan9stats v0.0.0-20260216142805-b3301c5f2a88 // indirect
|
||||
github.com/mattn/go-colorable v0.1.15 // indirect
|
||||
github.com/mattn/go-ieproxy v0.0.12 // indirect
|
||||
github.com/mattn/go-isatty v0.0.24 // indirect
|
||||
github.com/mattn/go-localereader v0.0.1 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.21 // indirect
|
||||
github.com/mattn/go-runewidth v0.0.23 // indirect
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.4 // indirect
|
||||
github.com/minio/colorjson v1.0.8 // indirect
|
||||
github.com/minio/crc64nvme v1.1.1 // indirect
|
||||
@@ -283,12 +285,12 @@ require (
|
||||
github.com/tklauser/go-sysconf v0.3.16 // indirect
|
||||
github.com/tklauser/numcpus v0.11.0 // indirect
|
||||
github.com/unrolled/secure v1.17.0 // indirect
|
||||
github.com/valyala/fastjson v1.6.4 // indirect
|
||||
github.com/valyala/fastjson v1.6.10 // indirect
|
||||
github.com/vbauerster/mpb/v8 v8.12.0 // indirect
|
||||
github.com/xdg/stringprep v1.0.3 // indirect
|
||||
github.com/xo/terminfo v0.0.0-20220910002029-abceb7e1c41e // indirect
|
||||
github.com/yusufpapurcu/wmi v1.2.4 // indirect
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.6.9 // indirect
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.7.1 // indirect
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
|
||||
go.opentelemetry.io/contrib/detectors/gcp v1.43.0 // indirect
|
||||
go.opentelemetry.io/contrib/instrumentation/google.golang.org/grpc/otelgrpc v0.67.0 // indirect
|
||||
@@ -300,13 +302,14 @@ require (
|
||||
go.opentelemetry.io/otel/trace v1.44.0 // indirect
|
||||
go.uber.org/multierr v1.11.0 // indirect
|
||||
go.yaml.in/yaml/v2 v2.4.4 // indirect
|
||||
golang.org/x/mod v0.37.0 // indirect
|
||||
golang.org/x/net v0.57.0 // indirect
|
||||
golang.org/x/text v0.40.0 // indirect
|
||||
golang.org/x/tools v0.47.0 // indirect
|
||||
golang.org/x/mod v0.40.0 // indirect
|
||||
golang.org/x/net v0.58.0 // indirect
|
||||
golang.org/x/text v0.41.0 // indirect
|
||||
golang.org/x/tools v0.49.0 // indirect
|
||||
google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 // indirect
|
||||
google.golang.org/genproto/googleapis/api v0.0.0-20260526163538-3dc84a4a5aaa // indirect
|
||||
google.golang.org/genproto/googleapis/rpc v0.0.0-20260526163538-3dc84a4a5aaa // indirect
|
||||
google.golang.org/grpc v1.82.1 // indirect
|
||||
google.golang.org/protobuf v1.36.11 // indirect
|
||||
gopkg.in/ini.v1 v1.67.3 // indirect
|
||||
)
|
||||
|
||||
@@ -101,16 +101,16 @@ github.com/charmbracelet/harmonica v0.2.0 h1:8NxJWRWg/bzKqqEaaeFNipOu77YR5t8aSwG
|
||||
github.com/charmbracelet/harmonica v0.2.0/go.mod h1:KSri/1RMQOZLbw7AHqgcBycp8pgJnQMYYT8QZRqZ1Ao=
|
||||
github.com/charmbracelet/lipgloss v1.1.0 h1:vYXsiLHVkK7fp74RkV7b2kq9+zDLoEU4MZoFqR/noCY=
|
||||
github.com/charmbracelet/lipgloss v1.1.0/go.mod h1:/6Q8FR2o+kj8rz4Dq0zQc3vYf7X+B0binUUBwA0aL30=
|
||||
github.com/charmbracelet/x/ansi v0.11.6 h1:GhV21SiDz/45W9AnV2R61xZMRri5NlLnl6CVF7ihZW8=
|
||||
github.com/charmbracelet/x/ansi v0.11.6/go.mod h1:2JNYLgQUsyqaiLovhU2Rv/pb8r6ydXKS3NIttu3VGZQ=
|
||||
github.com/charmbracelet/x/ansi v0.11.7 h1:kzv1kJvjg2S3r9KHo8hDdHFQLEqn4RBCb39dAYC84jI=
|
||||
github.com/charmbracelet/x/ansi v0.11.7/go.mod h1:9qGpnAVYz+8ACONkZBUWPtL7lulP9No6p1epAihUZwQ=
|
||||
github.com/charmbracelet/x/cellbuf v0.0.15 h1:ur3pZy0o6z/R7EylET877CBxaiE1Sp1GMxoFPAIztPI=
|
||||
github.com/charmbracelet/x/cellbuf v0.0.15/go.mod h1:J1YVbR7MUuEGIFPCaaZ96KDl5NoS0DAWkskup+mOY+Q=
|
||||
github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91 h1:payRxjMjKgx2PaCWLZ4p3ro9y97+TVLZNaRZgJwSVDQ=
|
||||
github.com/charmbracelet/x/exp/golden v0.0.0-20241011142426-46044092ad91/go.mod h1:wDlXFlCrmJ8J+swcL/MnGUuYnqgQdW9rhSD61oNMb6U=
|
||||
github.com/charmbracelet/x/term v0.2.2 h1:xVRT/S2ZcKdhhOuSP4t5cLi5o+JxklsoEObBSgfgZRk=
|
||||
github.com/charmbracelet/x/term v0.2.2/go.mod h1:kF8CY5RddLWrsgVwpw4kAa6TESp6EB5y3uxGLeCqzAI=
|
||||
github.com/cheggaaa/pb v1.0.29 h1:FckUN5ngEk2LpvuG0fw1GEFx6LtyY2pWI/Z2QgCnEYo=
|
||||
github.com/cheggaaa/pb v1.0.29/go.mod h1:W40334L7FMC5JKWldsTWbdGjLo0RxUKK73K+TuPxX30=
|
||||
github.com/cheggaaa/pb v1.0.30 h1:NylhgqJfXx3JVBGx6ywsXuhpz8caSMPmLArXyAv1bwU=
|
||||
github.com/cheggaaa/pb v1.0.30/go.mod h1:YgTBwa6PqwwDB/2UKdLuuFRNTwEkcCPsA5AmWivrBAg=
|
||||
github.com/chromedp/cdproto v0.0.0-20230802225258-3cf4e6d46a89/go.mod h1:GKljq0VrfU4D5yc+2qA6OVr8pmO/MBbPEWqWQ/oqGEs=
|
||||
github.com/chromedp/chromedp v0.9.2/go.mod h1:LkSXJKONWTCHAfQasKFUZI+mxqS4tZqhmtGzzhLsnLs=
|
||||
github.com/chromedp/sysutil v1.0.0/go.mod h1:kgWmDdq8fTzXYcKIBqIYvRRTnYb9aNS9moAV0xufSww=
|
||||
@@ -186,8 +186,6 @@ github.com/fraugster/parquet-go v0.12.0/go.mod h1:dGzUxdNqXsAijatByVgbAWVPlFirnh
|
||||
github.com/fsnotify/fsnotify v1.4.7/go.mod h1:jwhsz4b93w/PPRr/qN1Yymfu8t87LnFCMoQvtojpjFo=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8 h1:H9AZkK22UOmfX8J84ubyaZxKJZ3FMHVwn8swoMML7iQ=
|
||||
github.com/go-asn1-ber/asn1-ber v1.5.8/go.mod h1:hEBeB/ic+5LoWskz+yKT7vGhhPYkProFKoKdwZRWMe0=
|
||||
github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=
|
||||
github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4 h1:moDMcTHmvE6Groj34emNPLs/qtYXRVcd6S7NHbHz3kA=
|
||||
github.com/go-jose/go-jose/v4 v4.1.4/go.mod h1:x4oUasVrzR7071A4TnHLGSPpNOm2a21K9Kf04k1rs08=
|
||||
github.com/go-ldap/ldap/v3 v3.4.14 h1:D6PYdEgsaVzsXyr6w/yDC06Ria4uUhWm+Rb+er8lfAs=
|
||||
@@ -376,11 +374,11 @@ github.com/keybase/go-keychain v0.0.1/go.mod h1:PdEILRW3i9D8JcdM+FmY6RwkHGnhHxXw
|
||||
github.com/kisielk/errcheck v1.5.0/go.mod h1:pFxgyoBC7bSaBwPgfKdkLd5X25qrDl4LWUI2bnpBCr8=
|
||||
github.com/kisielk/gotool v1.0.0/go.mod h1:XhKaO+MFFWcvkIS/tQcRk01m1F5IRFswLeQ+oQHNcck=
|
||||
github.com/klauspost/compress v1.14.4/go.mod h1:/3/Vjq9QcHkK5uEr5lBEmyoZ1iFhe47etQ6QUkpK6sk=
|
||||
github.com/klauspost/compress v1.18.7 h1:aUyZsS4kH3QTKurYhAOwAHxllVPnOthb3vPfnF1Ehjw=
|
||||
github.com/klauspost/compress v1.18.7/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/compress v1.19.2 h1:hMRETovs/pu/dVWN7zIT1PGG8t509MwT6bO7XSi26R8=
|
||||
github.com/klauspost/compress v1.19.2/go.mod h1:cwPg85FWrGar70rWktvGQj8/hthj3wpl0PGDogxkrSQ=
|
||||
github.com/klauspost/cpuid/v2 v2.0.1/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0 h1:S4CRMLnYUhGeDFDqkGriYKdfoFlDnMtqTiI/sFzhA9Y=
|
||||
github.com/klauspost/cpuid/v2 v2.3.0/go.mod h1:hqwkgyIinND0mEev00jJYCxPNVRVXFQeu1XKlok6oO0=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw=
|
||||
github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU=
|
||||
github.com/klauspost/crc32 v1.3.0 h1:sSmTt3gUt81RP655XGZPElI0PelVTZ6YwCRnPSupoFM=
|
||||
github.com/klauspost/crc32 v1.3.0/go.mod h1:D7kQaZhnkX/Y0tstFGf8VUzv2UofNGqCjnC3zdHB0Hw=
|
||||
github.com/klauspost/filepathx v1.1.1 h1:201zvAsL1PhZvmXTP+QLer3AavWrO3U1NILWpniHK4w=
|
||||
@@ -405,18 +403,16 @@ github.com/kylelemons/godebug v1.1.0/go.mod h1:9/0rRGxNHcop5bhtWyNeEfOS8JIWk580+
|
||||
github.com/ledongthuc/pdf v0.0.0-20220302134840-0c2507a12d80/go.mod h1:imJHygn/1yfhB7XSJJKlFZKl/J+dCPAknuiaGOshXAs=
|
||||
github.com/lestrrat-go/blackmagic v1.0.4 h1:IwQibdnf8l2KoO+qC3uT4OaTWsW7tuRQXy9TRN9QanA=
|
||||
github.com/lestrrat-go/blackmagic v1.0.4/go.mod h1:6AWFyKNNj0zEXQYfTMPfZrAXUWUfTIZ5ECEUEJaijtw=
|
||||
github.com/lestrrat-go/dsig v1.0.0 h1:OE09s2r9Z81kxzJYRn07TFM9XA4akrUdoMwr0L8xj38=
|
||||
github.com/lestrrat-go/dsig v1.0.0/go.mod h1:dEgoOYYEJvW6XGbLasr8TFcAxoWrKlbQvmJgCR0qkDo=
|
||||
github.com/lestrrat-go/dsig v1.3.0 h1:phjMOCXvYzhuIgn7Voe2rex8z166vGfxRxmqM25P9/Q=
|
||||
github.com/lestrrat-go/dsig v1.3.0/go.mod h1:RD2eOaidyPvpc7IJQoO3Qq52RWdy8ZcJs8lrOnoa1Kc=
|
||||
github.com/lestrrat-go/dsig-secp256k1 v1.0.0 h1:JpDe4Aybfl0soBvoVwjqDbp+9S1Y2OM7gcrVVMFPOzY=
|
||||
github.com/lestrrat-go/dsig-secp256k1 v1.0.0/go.mod h1:CxUgAhssb8FToqbL8NjSPoGQlnO4w3LG1P0qPWQm/NU=
|
||||
github.com/lestrrat-go/httpcc v1.0.1 h1:ydWCStUeJLkpYyjLDHihupbn2tYmZ7m22BGkcvZZrIE=
|
||||
github.com/lestrrat-go/httpcc v1.0.1/go.mod h1:qiltp3Mt56+55GPVCbTdM9MlqhvzyuL6W/NMDA8vA5E=
|
||||
github.com/lestrrat-go/httprc/v3 v3.0.1 h1:3n7Es68YYGZb2Jf+k//llA4FTZMl3yCwIjFIk4ubevI=
|
||||
github.com/lestrrat-go/httprc/v3 v3.0.1/go.mod h1:2uAvmbXE4Xq8kAUjVrZOq1tZVYYYs5iP62Cmtru00xk=
|
||||
github.com/lestrrat-go/jwx/v3 v3.0.12 h1:p25r68Y4KrbBdYjIsQweYxq794CtGCzcrc5dGzJIRjg=
|
||||
github.com/lestrrat-go/jwx/v3 v3.0.12/go.mod h1:HiUSaNmMLXgZ08OmGBaPVvoZQgJVOQphSrGr5zMamS8=
|
||||
github.com/lestrrat-go/option v1.0.1 h1:oAzP2fvZGQKWkvHa1/SAcFolBEca1oN+mQ7eooNBEYU=
|
||||
github.com/lestrrat-go/option v1.0.1/go.mod h1:5ZHFbivi4xwXxhxY9XHDe2FHo6/Z7WWmtT7T5nBBp3I=
|
||||
github.com/lestrrat-go/httprc/v3 v3.0.6 h1:4FpLQ18KK/ypPbVU3NLWJNRvH3kcYiqKqWfKGqNWxxI=
|
||||
github.com/lestrrat-go/httprc/v3 v3.0.6/go.mod h1:mSMtkZW92Z98M5YoNNztbRGxbXHql7tSitCvaxvo9l0=
|
||||
github.com/lestrrat-go/jwx/v3 v3.0.13 h1:AdHKiPIYeCSnOJtvdpipPg/0SuFh9rdkN+HF3O0VdSk=
|
||||
github.com/lestrrat-go/jwx/v3 v3.0.13/go.mod h1:2m0PV1A9tM4b/jVLMx8rh6rBl7F6WGb3EG2hufN9OQU=
|
||||
github.com/lestrrat-go/option/v2 v2.0.0 h1:XxrcaJESE1fokHy3FpaQ/cXW8ZsIdWcdFzzLOcID3Ss=
|
||||
github.com/lestrrat-go/option/v2 v2.0.0/go.mod h1:oSySsmzMoR0iRzCDCaUfsCzxQHUEuhOViQObyy7S6Vg=
|
||||
github.com/lib/pq v1.10.4/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
@@ -424,8 +420,8 @@ github.com/lib/pq v1.10.9 h1:YXG7RB+JIjhP29X+OtkiDnYaXQwpS4JEWq7dtCCRUEw=
|
||||
github.com/lib/pq v1.10.9/go.mod h1:AlVN5x4E4T544tWzH6hKfbfQvm3HdbOxrmggDNAPY9o=
|
||||
github.com/lithammer/shortuuid/v4 v4.2.0 h1:LMFOzVB3996a7b8aBuEXxqOBflbfPQAiVzkIcHO0h8c=
|
||||
github.com/lithammer/shortuuid/v4 v4.2.0/go.mod h1:D5noHZ2oFw/YaKCfGy0YxyE7M0wMbezmMjPdhyEFe6Y=
|
||||
github.com/lucasb-eyer/go-colorful v1.3.0 h1:2/yBRLdWBZKrf7gB40FoiKfAWYQ0lqNcbuQwVHXptag=
|
||||
github.com/lucasb-eyer/go-colorful v1.3.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||
github.com/lucasb-eyer/go-colorful v1.4.0 h1:UtrWVfLdarDgc44HcS7pYloGHJUjHV/4FwW4TvVgFr4=
|
||||
github.com/lucasb-eyer/go-colorful v1.4.0/go.mod h1:R4dSotOR9KMtayYi1e77YzuveK+i7ruzyGqttikkLy0=
|
||||
github.com/lufia/plan9stats v0.0.0-20260216142805-b3301c5f2a88 h1:PTw+yKnXcOFCR6+8hHTyWBeQ/P4Nb7dd4/0ohEcWQuM=
|
||||
github.com/lufia/plan9stats v0.0.0-20260216142805-b3301c5f2a88/go.mod h1:autxFIvghDt3jPTLoqZ9OZ7s9qTGNAWmYCjVFWPX/zg=
|
||||
github.com/magiconair/properties v1.8.0/go.mod h1:PppfXfuXeibc/6YijjN8zIbojt8czPbwD3XqdrwzmxQ=
|
||||
@@ -446,13 +442,13 @@ github.com/mattn/go-runewidth v0.0.4/go.mod h1:LwmH8dsx7+W8Uxz3IHJYH5QSwggIsqBzp
|
||||
github.com/mattn/go-runewidth v0.0.9/go.mod h1:H031xJmbD/WCDINGzjvQ9THkh0rPKHF+m2gUSrubnMI=
|
||||
github.com/mattn/go-runewidth v0.0.10/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
|
||||
github.com/mattn/go-runewidth v0.0.12/go.mod h1:RAqKPSqVFrSLVXbA8x7dzmKdmGzieGRCM46jaSJTDAk=
|
||||
github.com/mattn/go-runewidth v0.0.21 h1:jJKAZiQH+2mIinzCJIaIG9Be1+0NR+5sz/lYEEjdM8w=
|
||||
github.com/mattn/go-runewidth v0.0.21/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
|
||||
github.com/mattn/go-runewidth v0.0.23 h1:7ykA0T0jkPpzSvMS5i9uoNn2Xy3R383f9HDx3RybWcw=
|
||||
github.com/mattn/go-runewidth v0.0.23/go.mod h1:XBkDxAl56ILZc9knddidhrOlY5R/pDhgLpndooCuJAs=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.1/go.mod h1:D8He9yQNgCq6Z5Ld7szi9bcBfOoFv/3dc6xSMkL2PC0=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.4 h1:mmDVorXM7PCGKw94cs5zkfA9PSy5pEvNWRP0ET0TIVo=
|
||||
github.com/matttproud/golang_protobuf_extensions v1.0.4/go.mod h1:BSXmuO+STAnVfrANrmjBb36TMTDstsz7MSK+HVaYKv4=
|
||||
github.com/miekg/dns v1.1.72 h1:vhmr+TF2A3tuoGNkLDFK9zi36F2LS+hKTRW0Uf8kbzI=
|
||||
github.com/miekg/dns v1.1.72/go.mod h1:+EuEPhdHOsfk6Wk5TT2CzssZdqkmFhf8r+aVyDEToIs=
|
||||
github.com/miekg/dns v1.1.73 h1:uhT8nJxmTrPJYClxVxTCX+CVn6qnzSiybRk72Z6DgrE=
|
||||
github.com/miekg/dns v1.1.73/go.mod h1:RW2Obtfd5NZHvOFe3zYG0W8koWOQtAzyHaLo8vASBuQ=
|
||||
github.com/minio/cli v1.24.2 h1:J+fCUh9mhPLjN3Lj/YhklXvxj8mnyE/D6FpFduXJ2jg=
|
||||
github.com/minio/cli v1.24.2/go.mod h1:bYxnK0uS629N3Bq+AOZZ+6lwF77Sodk4+UL9vNuXhOY=
|
||||
github.com/minio/colorjson v1.0.8 h1:AS6gEQ1dTRYHmC4xuoodPDRILHP/9Wz5wYUGDQfPLpg=
|
||||
@@ -478,8 +474,6 @@ github.com/minio/madmin-go/v3 v3.0.110 h1:FIYekj7YPc430ffpXFWiUtyut3qBt/unIAcDzJ
|
||||
github.com/minio/madmin-go/v3 v3.0.110/go.mod h1:WOe2kYmYl1OIlY2DSRHVQ8j1v4OItARQ6jGyQqcCud8=
|
||||
github.com/minio/md5-simd v1.1.2 h1:Gdi1DZK69+ZVMoNHRXJyNcxrMA4dSxoYHZSQbirFg34=
|
||||
github.com/minio/md5-simd v1.1.2/go.mod h1:MzdKDxYpY2BT9XQFocsiZf/NKVtR7nkE4RoEpN+20RM=
|
||||
github.com/minio/minio-go/v7 v7.0.99 h1:2vH/byrwUkIpFQFOilvTfaUpvAX3fEFhEzO+DR3DlCE=
|
||||
github.com/minio/minio-go/v7 v7.0.99/go.mod h1:EtGNKtlX20iL2yaYnxEigaIvj0G0GwSDnifnG8ClIdw=
|
||||
github.com/minio/mux v1.9.2 h1:dQchne49BUBgOlxIHjx5wVe1gl5VXF2sxd4YCXkikTw=
|
||||
github.com/minio/mux v1.9.2/go.mod h1:OuHAsZsux+e562bcO2P3Zv/P0LMo6fPQ310SmoyG7mQ=
|
||||
github.com/minio/selfupdate v0.6.0 h1:i76PgT0K5xO9+hjzKcacQtO7+MjJ4JKA8Ak8XQ9DDwU=
|
||||
@@ -547,23 +541,25 @@ github.com/orisano/pixelmatch v0.0.0-20220722002657-fb0b55479cde/go.mod h1:nZgzb
|
||||
github.com/pascaldekloe/goe v0.1.0/go.mod h1:lzWF7FIEvWOWxwDKqyGYQf6ZUaNfKdP144TG7ZOy1lc=
|
||||
github.com/pborman/getopt v0.0.0-20170112200414-7148bc3a4c30/go.mod h1:85jBQOZwpVEaDAr341tbn15RS4fCAsIst0qp7i8ex1o=
|
||||
github.com/pelletier/go-toml v1.2.0/go.mod h1:5z9KED0ma1S8pY6P1sdut58dfprrGBbd/94hg7ilaic=
|
||||
github.com/pgsty/mc v0.0.0-20260801042411-ad10a2a10b76 h1:UIlUuz0LQKw4QlAljhv7nPDDFC1+n+e0iED7rWZrgZ8=
|
||||
github.com/pgsty/mc v0.0.0-20260801042411-ad10a2a10b76/go.mod h1:cTbS+9jGR4Qs7xTf5DEhmCTbzcDWrKMs8ZmTUnCU49E=
|
||||
github.com/pgsty/silo-console v0.0.0-20260806061103-72fc0a5ea52a h1:JfEQJkBdTwCXSrCv8P0R5tMpzxxhSdUTvg54mHwzxpA=
|
||||
github.com/pgsty/silo-console v0.0.0-20260806061103-72fc0a5ea52a/go.mod h1:7J8wCQsNT5S7GqCHnQqgj0T7Nagp1fklJhfBJI+v0XI=
|
||||
github.com/pgsty/silo-pkg/v3 v3.11.0 h1:wjN5d+tWD8Twq+e7k/KBBVhnWXC8xTIlfTcnGIKkmjc=
|
||||
github.com/pgsty/silo-pkg/v3 v3.11.0/go.mod h1:E2AB4oOgfDeb9In1KDBTrn9wzfvr0WzoPkbXW7wbwBQ=
|
||||
github.com/pgsty/mc v0.0.0-20260829103737-5ed037ef4ec1 h1:CotSAPr11rZy3VK46j5rJQYQ2LHT2mjrd9vf0Ak12bA=
|
||||
github.com/pgsty/mc v0.0.0-20260829103737-5ed037ef4ec1/go.mod h1:pwkfUxTikOkKc+yvEWqFg7CAPZDj5Yl0YHFcZoPKmU8=
|
||||
github.com/pgsty/silo-console v0.0.0-20260829111139-e07ef01ab8bf h1:BwUlE3Qr5+/JWkdNYnpSFin7RW1Uiaf7ddGlR87Y9YQ=
|
||||
github.com/pgsty/silo-console v0.0.0-20260829111139-e07ef01ab8bf/go.mod h1:Zqpx0h9NB5WzXI+OE/VVFcrXD6fKtSqqfCurmtxyKPo=
|
||||
github.com/pgsty/silo-go/v7 v7.3.1 h1:CchXB5hdv1KGUCGBzR5Tz8hSE+3P9sGJFPY+ku8tC04=
|
||||
github.com/pgsty/silo-go/v7 v7.3.1/go.mod h1:3uUcXVLE1xLBTy+A/js/hHKkvcYQ/zMbj8rbtNQavxE=
|
||||
github.com/pgsty/silo-pkg/v3 v3.12.3-0.20260829103855-748c94bf8ab7 h1:YSCnSqNjU2ddU84dA8ybJXOoWYx8VDu2qAzXMVweisc=
|
||||
github.com/pgsty/silo-pkg/v3 v3.12.3-0.20260829103855-748c94bf8ab7/go.mod h1:hSvfIz9FWTvEZqTsGEWQ8P/gD81pDee9W4j5oIvHZMY=
|
||||
github.com/philhofer/fwd v1.2.0 h1:e6DnBTl7vGY+Gz322/ASL4Gyp1FspeMvx1RNDoToZuM=
|
||||
github.com/philhofer/fwd v1.2.0/go.mod h1:RqIHx9QI14HlwKwm98g9Re5prTQ6LdeRQn+gXJFxsJM=
|
||||
github.com/pierrec/lz4/v4 v4.1.26 h1:GrpZw1gZttORinvzBdXPUXATeqlJjqUG/D87TKMnhjY=
|
||||
github.com/pierrec/lz4/v4 v4.1.26/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
|
||||
github.com/pierrec/lz4/v4 v4.1.29 h1:CDQY6qZOLI4DW0Nx6R1vRrifrCeQHnNXkMb0hZWXFjg=
|
||||
github.com/pierrec/lz4/v4 v4.1.29/go.mod h1:EoQMVJgeeEOMsCqCzqFm2O0cJvljX2nGZjcRIPL34O4=
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c h1:+mdjkGKdHQG3305AYmdv1U2eRNDiU2ErMBj1gwrq8eQ=
|
||||
github.com/pkg/browser v0.0.0-20240102092130-5ac0b6a4141c/go.mod h1:7rwL4CYBLnjLxUqIJNnCWiEdr3bn6IUYi15bNlnbCCU=
|
||||
github.com/pkg/errors v0.8.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/errors v0.9.1 h1:FEBLx1zS214owpjy7qsBeixbURkuhQAwrK5UwLGTwt4=
|
||||
github.com/pkg/errors v0.9.1/go.mod h1:bwawxfHBFNV+L2hUp1rHADufV3IMtnDRdf1r5NINEl0=
|
||||
github.com/pkg/sftp v1.13.10 h1:+5FbKNTe5Z9aspU88DPIKJ9z2KZoaGCu6Sr6kKR/5mU=
|
||||
github.com/pkg/sftp v1.13.10/go.mod h1:bJ1a7uDhrX/4OII+agvy28lzRvQrmIQuaHrcI1HbeGA=
|
||||
github.com/pkg/sftp v1.13.11 h1:0N92SLTB8JqASJB14ZLHHzFnBV8mG9zw4K7jghEFWuE=
|
||||
github.com/pkg/sftp v1.13.11/go.mod h1:uNkH9roSXglNJqM+glJJi+TQXQUm0fXFWqCFmT8hsN0=
|
||||
github.com/pkg/xattr v0.4.12 h1:rRTkSyFNTRElv6pkA3zpjHpQ90p/OdHQC1GmGh1aTjM=
|
||||
github.com/pkg/xattr v0.4.12/go.mod h1:di8WF84zAKk8jzR1UBTEWh9AUlIZZ7M/JNt8e9B6ktU=
|
||||
github.com/planetscale/vtprotobuf v0.6.1-0.20240319094008-0393e58bdf10 h1:GFCKgmp0tecUJ0sJuv4pzYCqS9+RGSn52M3FUwPs+uo=
|
||||
@@ -604,8 +600,8 @@ github.com/rivo/uniseg v0.4.7 h1:WUdvkW8uEhrYfLC4ZzdpI2ztxP1I582+49Oc5Mq64VQ=
|
||||
github.com/rivo/uniseg v0.4.7/go.mod h1:FN3SvrM+Zdj16jyLfmOkMNblXMcoc8DfTHruCPUcx88=
|
||||
github.com/rjeczalik/notify v0.9.3 h1:6rJAzHTGKXGj76sbRgDiDcYj/HniypXmSJo1SWakZeY=
|
||||
github.com/rjeczalik/notify v0.9.3/go.mod h1:gF3zSOrafR9DQEWSE8TjfI9NkooDxbyT4UgRGKZA0lc=
|
||||
github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ=
|
||||
github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc=
|
||||
github.com/rogpeppe/go-internal v1.15.0 h1:D0RCU5rMAp+SpgkiNdrjfJ+LX4J1M32V2NeCY7EJ6hc=
|
||||
github.com/rogpeppe/go-internal v1.15.0/go.mod h1:DrUVZyrJU+txYW5/1kwtXQSMFio52ZOxX7yM1VHvnxs=
|
||||
github.com/rs/cors v1.11.1 h1:eU3gRzXLRK57F5rKMGMZURNdIG4EoAmX8k94r9wXWHA=
|
||||
github.com/rs/cors v1.11.1/go.mod h1:XyqrcTp5zjWr1wsJ8PIRZssZ8b/WMcMf71DJnit4EMU=
|
||||
github.com/rs/xid v1.6.0 h1:fV591PaemRlL6JfRxGDEPl69wICngIQ3shQtzfy2gxU=
|
||||
@@ -636,14 +632,15 @@ github.com/spiffe/go-spiffe/v2 v2.6.0/go.mod h1:gm2SeUoMZEtpnzPNs2Csc0D/gX33k1xI
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.2.2/go.mod h1:a8OnRcib4nhh0OaRAV+Yts87kKdq0PP7pXfy6kDkUVs=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.4.0/go.mod h1:j7eGeouHqKxXV5pUuKE4zz7dFj8WfuZ+81PSLYec5m4=
|
||||
github.com/stretchr/testify v1.6.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.11.1 h1:7s2iGBzp5EwR7/aIZr8ao5+dra3wiQyKjjFuvgVKu7U=
|
||||
github.com/stretchr/testify v1.11.1/go.mod h1:wZwfW3scLgRK+23gO65QZefKpKQRnfz6sD981Nm4B6U=
|
||||
github.com/tidwall/gjson v1.18.0 h1:FIDeeyB800efLX89e5a8Y0BNH+LOngJyGrIWxG2FKQY=
|
||||
@@ -666,8 +663,8 @@ github.com/unrolled/secure v1.17.0 h1:Io7ifFgo99Bnh0J7+Q+qcMzWM6kaDPCA5FroFZEdbW
|
||||
github.com/unrolled/secure v1.17.0/go.mod h1:BmF5hyM6tXczk3MpQkFf1hpKSRqCyhqcbiQtiAF7+40=
|
||||
github.com/valyala/bytebufferpool v1.0.0 h1:GqA5TC/0021Y/b9FG4Oi9Mr3q7XYx6KllzawFIhcdPw=
|
||||
github.com/valyala/bytebufferpool v1.0.0/go.mod h1:6bBcMArwyJ5K/AmCkWv1jt77kVWyCJ6HpOuEn7z0Csc=
|
||||
github.com/valyala/fastjson v1.6.4 h1:uAUNq9Z6ymTgGhcm0UynUAB6tlbakBrz6CQFax3BXVQ=
|
||||
github.com/valyala/fastjson v1.6.4/go.mod h1:CLCAqky6SMuOcxStkYQvblddUtoRxhYMGLrsQns1aXY=
|
||||
github.com/valyala/fastjson v1.6.10 h1:/yjJg8jaVQdYR3arGxPE2X5z89xrlhS0eGXdv+ADTh4=
|
||||
github.com/valyala/fastjson v1.6.10/go.mod h1:e6FubmQouUNP73jtMLmcbxS6ydWIpOfhz34TSfO3JaE=
|
||||
github.com/vbauerster/mpb/v8 v8.12.0 h1:+gneY3ifzc88tKDzOtfG8k8gfngCx615S2ZmFM4liWg=
|
||||
github.com/vbauerster/mpb/v8 v8.12.0/go.mod h1:V02YIuMVo301Y1VE9VtZlD8s84OMsk+EKN6mwvf/588=
|
||||
github.com/xdg/scram v1.0.5 h1:TuS0RFmt5Is5qm9Tm2SoD89OPqe4IRiFtyFY4iwWXsw=
|
||||
@@ -688,12 +685,12 @@ github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs=
|
||||
github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s=
|
||||
go.etcd.io/bbolt v1.3.6 h1:/ecaJf0sk1l4l6V4awd65v2C3ILy7MSj+s/x1ADCIMU=
|
||||
go.etcd.io/bbolt v1.3.6/go.mod h1:qXsaaIqmgQH0T+OPdb99Bf+PKfBBQVAdyD6TY9G8XM4=
|
||||
go.etcd.io/etcd/api/v3 v3.6.9 h1:UA7iKfEW1AzgihcBSGXci2kDGQiokSq41F9HMCI/RTI=
|
||||
go.etcd.io/etcd/api/v3 v3.6.9/go.mod h1:csEk/qTfxKL36NqJdU15Tgtl65A8dyEY2BYo7PRsIwk=
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.6.9 h1:T8nuk8Lz64C+Hzb0coBFLMSlVSQZBpAtFk46swdM1DA=
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.6.9/go.mod h1:WEy3PpwbbEBVRdh1NVJYsuUe/8eyI21PNJRazeD8z/Y=
|
||||
go.etcd.io/etcd/client/v3 v3.6.9 h1:3X555hQXmhRr27O37wls53g68CpUiPOiHXrZfz2Al+o=
|
||||
go.etcd.io/etcd/client/v3 v3.6.9/go.mod h1:KO7H1HLYh1qaljuVZJQwBFk1lRce6pJzt+C81GEnrlM=
|
||||
go.etcd.io/etcd/api/v3 v3.7.1 h1:KJG0/DcWGfe3Y1otDf/fsBf0TSSgpxZ5RO/L8SFt73E=
|
||||
go.etcd.io/etcd/api/v3 v3.7.1/go.mod h1:8bXIpCMeV7E3/XL0Ix123ATn3dB+0V7d9zklHbB0m78=
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.7.1 h1:rKYsj3pRkR0eK3yjT3XOgrhqfmIfj9pzNgxjh7mfFv4=
|
||||
go.etcd.io/etcd/client/pkg/v3 v3.7.1/go.mod h1:cnzZGIUzSfjEwLC6UBVsSXlEK1eepS/JUD7wE6PLRT0=
|
||||
go.etcd.io/etcd/client/v3 v3.7.1 h1:0PEMMC0KuZmVIN+RAbdqfkZ45pYTgKVtmBEbRCvZFUg=
|
||||
go.etcd.io/etcd/client/v3 v3.7.1/go.mod h1:ffNqALa8tRCYhYo1F9oR489y23K39Gz+BSR3ApAGYq0=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
|
||||
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
|
||||
go.opentelemetry.io/contrib/detectors/gcp v1.43.0 h1:62yY3dT7/ShwOxzA0RsKRgshBmfElKI4d/Myu2OxDFU=
|
||||
@@ -728,8 +725,8 @@ go.yaml.in/yaml/v2 v2.4.4 h1:tuyd0P+2Ont/d6e2rl3be67goVK4R6deVxCUX5vyPaQ=
|
||||
go.yaml.in/yaml/v2 v2.4.4/go.mod h1:gMZqIpDtDqOfM0uNfy0SkpRhvUryYH0Z6wdMYcacYXQ=
|
||||
go.yaml.in/yaml/v3 v3.0.5 h1:N6y/pJk8buWs9NY5ERU2HSMfm+IuD/OtfdAnq6kESPw=
|
||||
go.yaml.in/yaml/v3 v3.0.5/go.mod h1:HVTZu1O7/Vkt2N+BFy8Zza+lnLsABggaTM2ZpNIGuKg=
|
||||
goftp.io/server/v2 v2.0.2 h1:tkZpqyXys+vC15W5yGMi8Kzmbv1QSgeKr8qJXBnJbm8=
|
||||
goftp.io/server/v2 v2.0.2/go.mod h1:Fl1WdcV7fx1pjOWx7jEHb7tsJ8VwE7+xHu6bVJ6r2qg=
|
||||
goftp.io/server/v2 v2.0.3 h1:iz6Gxj7f2SFQVxrj0s1is+gueE6O9yTc+Ab0vtQ6Zn4=
|
||||
goftp.io/server/v2 v2.0.3/go.mod h1:Fl1WdcV7fx1pjOWx7jEHb7tsJ8VwE7+xHu6bVJ6r2qg=
|
||||
golang.org/x/crypto v0.0.0-20181203042331-505ab145d0a9/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=
|
||||
golang.org/x/crypto v0.0.0-20190308221718-c2843e01d9a2/go.mod h1:djNgcEr1/C05ACkg1iLfiJU5Ep61QUkGW8qpdssI0+w=
|
||||
golang.org/x/crypto v0.0.0-20191011191535-87dc89f01550/go.mod h1:yigFU9vqHzYiE8UmvKecakEJjdnWj3jj499lnFckfCI=
|
||||
@@ -742,15 +739,15 @@ golang.org/x/crypto v0.0.0-20211209193657-4570a0811e8b/go.mod h1:IxCIyHEi3zRg3s0
|
||||
golang.org/x/crypto v0.0.0-20220315160706-3147a52a75dd/go.mod h1:IxCIyHEi3zRg3s0A5j5BB6A9Jmi73HwBIUl50j+osU4=
|
||||
golang.org/x/crypto v0.5.0/go.mod h1:NK/OQwhpMQP3MwtdjgLlYHnH9ebylxKWv3e0fK+mkQU=
|
||||
golang.org/x/crypto v0.6.0/go.mod h1:OFC/31mSvZgRz0V1QTNCzfAI1aIRzbiufJtkMIlEp58=
|
||||
golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
|
||||
golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
|
||||
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa h1:Zt3DZoOFFYkKhDT3v7Lm9FDMEV06GpzjG2jrqW+QTE0=
|
||||
golang.org/x/exp v0.0.0-20260218203240-3dfff04db8fa/go.mod h1:K79w1Vqn7PoiZn+TkNpx3BUWUQksGO3JcVX6qIjytmA=
|
||||
golang.org/x/crypto v0.55.0 h1:+KWHjbgOaAQ66dh/YlkZKHlz9ZUlq61AFirAR9ntP8M=
|
||||
golang.org/x/crypto v0.55.0/go.mod h1:uq0V9dE/fzQuJtbnL+2EhWOE63vo164FY8xqEnV9xis=
|
||||
golang.org/x/exp v0.0.0-20260820142414-ca536658362e h1:01Ju2A/fZKkci4zqx0eZxw//DnRYOnBiGJG14hFBhO8=
|
||||
golang.org/x/exp v0.0.0-20260820142414-ca536658362e/go.mod h1:zeBbvyFKDaLwa7CH/zI8KXt7gTl14SF7sO08Pl5jBCM=
|
||||
golang.org/x/mod v0.2.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.3.0/go.mod h1:s0Qsj1ACt9ePp/hMypM3fl4fZqREWJwdYDEqhRiZZUA=
|
||||
golang.org/x/mod v0.6.0-dev.0.20220419223038-86c51ed26bb4/go.mod h1:jJ57K6gSWd91VN4djpZkiMVwK6gcyfeH4XE8wZrZaV4=
|
||||
golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
|
||||
golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
|
||||
golang.org/x/mod v0.40.0 h1:hUv+3cXcdRHz08UmSiOob7sadHig73uo5bkXxQ/tvUs=
|
||||
golang.org/x/mod v0.40.0/go.mod h1:0/weTWkPWGBikyTWAX3dkjVztMmBA5hM0DH6BElSupE=
|
||||
golang.org/x/net v0.0.0-20181201002055-351d144fa1fc/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
|
||||
golang.org/x/net v0.0.0-20190311183353-d8887717615a/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
golang.org/x/net v0.0.0-20190404232315-eb5bcb51f2a3/go.mod h1:t9HGtf8HONx5eT2rtn7q6eTqICYqUVnKs3thJo3Qplg=
|
||||
@@ -764,8 +761,8 @@ golang.org/x/net v0.0.0-20220722155237-a158d28d115b/go.mod h1:XRhObCWvk6IyKnWLug
|
||||
golang.org/x/net v0.5.0/go.mod h1:DivGGAXEgPSlEBzxGzZI+ZLohi+xUj054jfeKui00ws=
|
||||
golang.org/x/net v0.6.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.7.0/go.mod h1:2Tu9+aMcznHK/AK1HMvgo6xiTLG5rD5rZLDS+rp2Bjs=
|
||||
golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
|
||||
golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
|
||||
golang.org/x/net v0.58.0 h1:ynWG7rqYi4ccpTEuPZ2QGWHktVEM9DMCj9yzDE0Q7To=
|
||||
golang.org/x/net v0.58.0/go.mod h1:YwCddHnFlT7eLQqVprV19OnhLGtc5xOKgE0RyqgfWAU=
|
||||
golang.org/x/oauth2 v0.36.0 h1:peZ/1z27fi9hUOFCAZaHyrpWG5lwe0RJEEEeH0ThlIs=
|
||||
golang.org/x/oauth2 v0.36.0/go.mod h1:YDBUJMTkDnJS+A4BP4eZBjCqtokkg1hODuPjwiGPO7Q=
|
||||
golang.org/x/sync v0.0.0-20181108010431-42b317875d0f/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM=
|
||||
@@ -822,8 +819,8 @@ golang.org/x/text v0.3.6/go.mod h1:5Zoc/QRtKVWzQhOtBMvqHzDpF6irO9z98xDceosuGiQ=
|
||||
golang.org/x/text v0.3.7/go.mod h1:u+2+/6zg+i71rQMx5EYifcz6MCKuco9NR6JIITiCfzQ=
|
||||
golang.org/x/text v0.6.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.7.0/go.mod h1:mrYo+phRRbMaCq/xk9113O4dZlRixOauAjOtrjsXDZ8=
|
||||
golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
|
||||
golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
|
||||
golang.org/x/text v0.41.0 h1:vz/seA0lnX87Othu2f/0L24RcgrXD9/YFTSuGjj3rH8=
|
||||
golang.org/x/text v0.41.0/go.mod h1:jvf1O8ajNzZqhSrQBPbutR/EB83Cc0CFrezNQIwbb5M=
|
||||
golang.org/x/time v0.0.0-20211116232009-f0f3c7e86c11/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
|
||||
golang.org/x/time v0.15.0 h1:bbrp8t3bGUeFOx08pvsMYRTCVSMk89u4tKbNOZbp88U=
|
||||
golang.org/x/time v0.15.0/go.mod h1:Y4YMaQmXwGQZoFaVFk4YpCt4FLQMYKZe9oeV/f4MSno=
|
||||
@@ -833,8 +830,8 @@ golang.org/x/tools v0.0.0-20191119224855-298f0cb1881e/go.mod h1:b+2E5dAYhXwXZwtn
|
||||
golang.org/x/tools v0.0.0-20200619180055-7c47624df98f/go.mod h1:EkVYQZoAsY45+roYkvgYkIh4xh/qjgUK9TdY2XT94GE=
|
||||
golang.org/x/tools v0.0.0-20210106214847-113979e3529a/go.mod h1:emZCQorbCU4vsT4fOWvOPXz4eW1wZW4PmDk9uLelYpA=
|
||||
golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc=
|
||||
golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
|
||||
golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
|
||||
golang.org/x/tools v0.49.0 h1:3NI7VXzL9+1WZD52Dx2ttoPwD5DWrFGpl9mFZDlmisI=
|
||||
golang.org/x/tools v0.49.0/go.mod h1:SJNXV9DBKT0UbdttsQjbfJlAE/q+y36++zo3uL3N0Oo=
|
||||
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
|
||||
@@ -863,6 +860,8 @@ gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8
|
||||
gopkg.in/check.v1 v1.0.0-20190902080502-41f04d3bba15/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c h1:Hei/4ADfdWqJk1ZMxUNpqntNwaWcugrBjAiHlqqRiVk=
|
||||
gopkg.in/check.v1 v1.0.0-20201130134442-10cb98267c6c/go.mod h1:JHkPIbrfpd72SG/EVd6muEfDQjcINNoR0C8j2r3qZ4Q=
|
||||
gopkg.in/ini.v1 v1.67.3 h1:iM9Lhz5MRSGhHVGGwCuzG9KO8PoirCXj/m/qTmOJJQw=
|
||||
gopkg.in/ini.v1 v1.67.3/go.mod h1:x/cyOwCgZqOkJoDIJ3c1KNHMo10+nLGAhh+kn3Zizss=
|
||||
gopkg.in/urfave/cli.v1 v1.20.0/go.mod h1:vuBzUtMdQeixQj8LVd+/98pzhxNGQoyuPBlsXHOQNO0=
|
||||
gopkg.in/yaml.v2 v2.2.2/go.mod h1:hI93XBmqTisBFMUTm0b8Fm+jr3Dg1NNxqwp+5A1VGuI=
|
||||
gopkg.in/yaml.v2 v2.4.0 h1:D8xgwECY7CYvx+Y2n4sBz93Jn9JRvxdiyyo8CTfuKaY=
|
||||
|
||||
@@ -0,0 +1,370 @@
|
||||
// Copyright (c) 2015-2021 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
//
|
||||
// This program is distributed in the hope that it will be useful
|
||||
// but WITHOUT ANY WARRANTY; without even the implied warranty of
|
||||
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
|
||||
// GNU Affero General Public License for more details.
|
||||
//
|
||||
// You should have received a copy of the GNU Affero General Public License
|
||||
// along with this program. If not, see <http://www.gnu.org/licenses/>.
|
||||
|
||||
// Package cors implements the S3 per-bucket CORS configuration type,
|
||||
// its validation, and origin/method/header matching helpers.
|
||||
package cors
|
||||
|
||||
import (
|
||||
"encoding/xml"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// maxCORSRules is the maximum number of rules allowed per bucket (AWS S3 limit).
|
||||
const maxCORSRules = 100
|
||||
|
||||
// maxCORSRuleIDLen is the maximum length of a CORSRule <ID> (AWS S3 limit).
|
||||
const maxCORSRuleIDLen = 255
|
||||
|
||||
// maxCORSMaxAgeSeconds is the largest value representable by the int32
|
||||
// MaxAgeSeconds shape used by the S3 API model.
|
||||
const maxCORSMaxAgeSeconds = 1<<31 - 1
|
||||
|
||||
// supportedMethods are the HTTP methods permitted in an AllowedMethod element.
|
||||
var supportedMethods = map[string]bool{
|
||||
"GET": true,
|
||||
"PUT": true,
|
||||
"HEAD": true,
|
||||
"POST": true,
|
||||
"DELETE": true,
|
||||
}
|
||||
|
||||
// Config is the S3 <CORSConfiguration> document.
|
||||
type Config struct {
|
||||
XMLName xml.Name `xml:"CORSConfiguration"`
|
||||
CORSRules []Rule `xml:"CORSRule"`
|
||||
}
|
||||
|
||||
// Rule is a single <CORSRule>.
|
||||
type Rule struct {
|
||||
ID string `xml:"ID,omitempty"`
|
||||
AllowedHeaders []string `xml:"AllowedHeader"`
|
||||
AllowedMethods []string `xml:"AllowedMethod"`
|
||||
AllowedOrigins []string `xml:"AllowedOrigin"`
|
||||
ExposeHeaders []string `xml:"ExposeHeader"`
|
||||
MaxAgeSeconds int `xml:"MaxAgeSeconds"`
|
||||
|
||||
maxAgeSecondsSet bool
|
||||
}
|
||||
|
||||
type corsXMLUnknown struct {
|
||||
XMLName xml.Name
|
||||
}
|
||||
|
||||
type corsXMLValue struct {
|
||||
Text string `xml:",chardata"`
|
||||
Unknown []corsXMLUnknown `xml:",any"`
|
||||
}
|
||||
|
||||
type configXML struct {
|
||||
XMLName xml.Name `xml:"CORSConfiguration"`
|
||||
CORSRules []ruleXML `xml:"CORSRule"`
|
||||
Text string `xml:",chardata"`
|
||||
Unknown []corsXMLUnknown `xml:",any"`
|
||||
}
|
||||
|
||||
type ruleXML struct {
|
||||
ID []corsXMLValue `xml:"ID"`
|
||||
AllowedHeaders []corsXMLValue `xml:"AllowedHeader"`
|
||||
AllowedMethods []corsXMLValue `xml:"AllowedMethod"`
|
||||
AllowedOrigins []corsXMLValue `xml:"AllowedOrigin"`
|
||||
ExposeHeaders []corsXMLValue `xml:"ExposeHeader"`
|
||||
MaxAgeSeconds []corsXMLValue `xml:"MaxAgeSeconds"`
|
||||
Text string `xml:",chardata"`
|
||||
Unknown []corsXMLUnknown `xml:",any"`
|
||||
}
|
||||
|
||||
// ParseBucketCorsConfig parses a CORS configuration from the given reader.
|
||||
func ParseBucketCorsConfig(r io.Reader) (*Config, error) {
|
||||
var parsed configXML
|
||||
decoder := xml.NewDecoder(r)
|
||||
if err := decoder.Decode(&parsed); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if strings.TrimSpace(parsed.Text) != "" {
|
||||
return nil, xml.UnmarshalError("unexpected character data in CORSConfiguration")
|
||||
}
|
||||
if len(parsed.Unknown) > 0 {
|
||||
return nil, xml.UnmarshalError(fmt.Sprintf("unexpected element <%s> in CORSConfiguration", parsed.Unknown[0].XMLName.Local))
|
||||
}
|
||||
|
||||
c := Config{
|
||||
XMLName: parsed.XMLName,
|
||||
CORSRules: make([]Rule, len(parsed.CORSRules)),
|
||||
}
|
||||
for i := range parsed.CORSRules {
|
||||
rule, err := parseCORSRuleXML(parsed.CORSRules[i])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
c.CORSRules[i] = rule
|
||||
}
|
||||
|
||||
// Decode consumes one document element. Only XML whitespace, comments, and
|
||||
// processing instructions are permitted after it.
|
||||
for {
|
||||
token, err := decoder.Token()
|
||||
if err == io.EOF {
|
||||
break
|
||||
}
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
switch token := token.(type) {
|
||||
case xml.CharData:
|
||||
if strings.TrimSpace(string(token)) == "" {
|
||||
continue
|
||||
}
|
||||
case xml.Comment, xml.ProcInst:
|
||||
continue
|
||||
}
|
||||
return nil, errors.New("unexpected XML content after CORSConfiguration")
|
||||
}
|
||||
return &c, nil
|
||||
}
|
||||
|
||||
func parseCORSRuleXML(parsed ruleXML) (Rule, error) {
|
||||
if strings.TrimSpace(parsed.Text) != "" {
|
||||
return Rule{}, xml.UnmarshalError("unexpected character data in CORSRule")
|
||||
}
|
||||
if len(parsed.Unknown) > 0 {
|
||||
return Rule{}, xml.UnmarshalError(fmt.Sprintf("unexpected element <%s> in CORSRule", parsed.Unknown[0].XMLName.Local))
|
||||
}
|
||||
if len(parsed.ID) > 1 {
|
||||
return Rule{}, xml.UnmarshalError("duplicate ID element in CORSRule")
|
||||
}
|
||||
if len(parsed.MaxAgeSeconds) > 1 {
|
||||
return Rule{}, xml.UnmarshalError("duplicate MaxAgeSeconds element in CORSRule")
|
||||
}
|
||||
|
||||
rule := Rule{}
|
||||
var err error
|
||||
if len(parsed.ID) == 1 {
|
||||
if rule.ID, err = corsXMLText("ID", parsed.ID[0]); err != nil {
|
||||
return Rule{}, err
|
||||
}
|
||||
}
|
||||
if rule.AllowedHeaders, err = corsXMLTexts("AllowedHeader", parsed.AllowedHeaders); err != nil {
|
||||
return Rule{}, err
|
||||
}
|
||||
if rule.AllowedMethods, err = corsXMLTexts("AllowedMethod", parsed.AllowedMethods); err != nil {
|
||||
return Rule{}, err
|
||||
}
|
||||
if rule.AllowedOrigins, err = corsXMLTexts("AllowedOrigin", parsed.AllowedOrigins); err != nil {
|
||||
return Rule{}, err
|
||||
}
|
||||
if rule.ExposeHeaders, err = corsXMLTexts("ExposeHeader", parsed.ExposeHeaders); err != nil {
|
||||
return Rule{}, err
|
||||
}
|
||||
if len(parsed.MaxAgeSeconds) == 1 {
|
||||
value, valueErr := corsXMLText("MaxAgeSeconds", parsed.MaxAgeSeconds[0])
|
||||
if valueErr != nil {
|
||||
return Rule{}, valueErr
|
||||
}
|
||||
age, parseErr := strconv.ParseInt(strings.TrimSpace(value), 10, 32)
|
||||
if parseErr != nil {
|
||||
return Rule{}, xml.UnmarshalError("invalid MaxAgeSeconds value")
|
||||
}
|
||||
rule.MaxAgeSeconds = int(age)
|
||||
rule.maxAgeSecondsSet = true
|
||||
}
|
||||
return rule, nil
|
||||
}
|
||||
|
||||
func corsXMLTexts(name string, values []corsXMLValue) ([]string, error) {
|
||||
result := make([]string, len(values))
|
||||
for i := range values {
|
||||
value, err := corsXMLText(name, values[i])
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
result[i] = value
|
||||
}
|
||||
return result, nil
|
||||
}
|
||||
|
||||
func corsXMLText(name string, value corsXMLValue) (string, error) {
|
||||
if len(value.Unknown) > 0 {
|
||||
return "", xml.UnmarshalError(fmt.Sprintf("element <%s> must not contain child element <%s>", name, value.Unknown[0].XMLName.Local))
|
||||
}
|
||||
return value.Text, nil
|
||||
}
|
||||
|
||||
// Validate checks the config against the S3 constraints.
|
||||
func (c *Config) Validate() error {
|
||||
if len(c.CORSRules) == 0 {
|
||||
return errors.New("CORSConfiguration must contain at least one rule")
|
||||
}
|
||||
if len(c.CORSRules) > maxCORSRules {
|
||||
return errors.New("CORSConfiguration exceeds the maximum number of rules")
|
||||
}
|
||||
for _, r := range c.CORSRules {
|
||||
if !utf8.ValidString(r.ID) {
|
||||
return errors.New("CORSRule ID must contain valid UTF-8")
|
||||
}
|
||||
if utf8.RuneCountInString(r.ID) > maxCORSRuleIDLen {
|
||||
return errors.New("CORSRule ID exceeds the maximum length of 255 characters")
|
||||
}
|
||||
if len(r.AllowedOrigins) == 0 {
|
||||
return errors.New("CORSRule must contain at least one AllowedOrigin")
|
||||
}
|
||||
if len(r.AllowedMethods) == 0 {
|
||||
return errors.New("CORSRule must contain at least one AllowedMethod")
|
||||
}
|
||||
for _, o := range r.AllowedOrigins {
|
||||
if o == "" {
|
||||
return errors.New("AllowedOrigin must not be empty")
|
||||
}
|
||||
if strings.Contains(o, "?") {
|
||||
return errors.New("AllowedOrigin may not contain wildcard '?': " + o)
|
||||
}
|
||||
if strings.Count(o, "*") > 1 {
|
||||
return errors.New("AllowedOrigin may contain at most one wildcard '*': " + o)
|
||||
}
|
||||
}
|
||||
for _, m := range r.AllowedMethods {
|
||||
if !supportedMethods[m] {
|
||||
return errors.New("unsupported method in CORSRule: " + m)
|
||||
}
|
||||
}
|
||||
for _, h := range r.AllowedHeaders {
|
||||
if h == "" {
|
||||
return errors.New("AllowedHeader must not be empty")
|
||||
}
|
||||
if strings.Contains(h, "?") {
|
||||
return errors.New("AllowedHeader may not contain wildcard '?': " + h)
|
||||
}
|
||||
if strings.Count(h, "*") > 1 {
|
||||
return errors.New("AllowedHeader may contain at most one wildcard '*': " + h)
|
||||
}
|
||||
}
|
||||
for _, h := range r.ExposeHeaders {
|
||||
if h == "" {
|
||||
return errors.New("ExposeHeader must not be empty")
|
||||
}
|
||||
}
|
||||
if r.MaxAgeSeconds < 0 {
|
||||
return errors.New("MaxAgeSeconds must not be negative")
|
||||
}
|
||||
if int64(r.MaxAgeSeconds) > maxCORSMaxAgeSeconds {
|
||||
return errors.New("MaxAgeSeconds exceeds the maximum S3 integer value")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func matchSingleWildcard(pattern, value string) bool {
|
||||
prefix, suffix, found := strings.Cut(pattern, "*")
|
||||
if !found {
|
||||
return pattern == value
|
||||
}
|
||||
return len(value) >= len(prefix)+len(suffix) &&
|
||||
strings.HasPrefix(value, prefix) && strings.HasSuffix(value, suffix)
|
||||
}
|
||||
|
||||
func (r Rule) matchAllowedOrigin(origin string) (string, bool) {
|
||||
for _, allowedOrigin := range r.AllowedOrigins {
|
||||
if matchSingleWildcard(allowedOrigin, origin) {
|
||||
return allowedOrigin, true
|
||||
}
|
||||
}
|
||||
return "", false
|
||||
}
|
||||
|
||||
// HasAllowedOrigin reports whether the rule allows the given origin.
|
||||
func (r Rule) HasAllowedOrigin(origin string) bool {
|
||||
_, ok := r.matchAllowedOrigin(origin)
|
||||
return ok
|
||||
}
|
||||
|
||||
// HasAllowedMethod reports whether the rule allows the given HTTP method.
|
||||
func (r Rule) HasAllowedMethod(method string) bool {
|
||||
for _, m := range r.AllowedMethods {
|
||||
if m == method {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// FilterAllowedHeaders returns the subset of reqHeaders permitted by the rule
|
||||
// and whether every requested header was allowed.
|
||||
func (r Rule) FilterAllowedHeaders(reqHeaders []string) ([]string, bool) {
|
||||
var allowed []string
|
||||
for _, h := range reqHeaders {
|
||||
h = strings.TrimSpace(h)
|
||||
if h == "" {
|
||||
continue
|
||||
}
|
||||
if !r.headerAllowed(h) {
|
||||
return nil, false
|
||||
}
|
||||
allowed = append(allowed, h)
|
||||
}
|
||||
return allowed, true
|
||||
}
|
||||
|
||||
func (r Rule) headerAllowed(header string) bool {
|
||||
for _, h := range r.AllowedHeaders {
|
||||
if matchSingleWildcard(strings.ToLower(h), strings.ToLower(header)) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// MatchRule returns the first rule whose origin and method both match, along
|
||||
// with the configured origin pattern that matched.
|
||||
func (c *Config) MatchRule(origin, method string) (rule *Rule, allowedOrigin string, ok bool) {
|
||||
for i := range c.CORSRules {
|
||||
r := &c.CORSRules[i]
|
||||
matchedOrigin, originOK := r.matchAllowedOrigin(origin)
|
||||
if originOK && r.HasAllowedMethod(method) {
|
||||
return r, matchedOrigin, true
|
||||
}
|
||||
}
|
||||
return nil, "", false
|
||||
}
|
||||
|
||||
// MatchPreflight returns the first rule whose origin and method match and
|
||||
// whose AllowedHeaders permit every header in reqHeaders. Unlike MatchRule,
|
||||
// this keeps evaluating subsequent rules until one fully satisfies the
|
||||
// preflight request, since an earlier origin/method match with a more
|
||||
// restrictive header list must not shadow a later, more permissive rule.
|
||||
func (c *Config) MatchPreflight(origin, method string, reqHeaders []string) (rule *Rule, allowedOrigin string, allowedHeaders []string, maxAgeSeconds *int, ok bool) {
|
||||
for i := range c.CORSRules {
|
||||
r := &c.CORSRules[i]
|
||||
matchedOrigin, originOK := r.matchAllowedOrigin(origin)
|
||||
if !originOK || !r.HasAllowedMethod(method) {
|
||||
continue
|
||||
}
|
||||
allowed, headersOK := r.FilterAllowedHeaders(reqHeaders)
|
||||
if !headersOK {
|
||||
continue
|
||||
}
|
||||
if r.maxAgeSecondsSet || r.MaxAgeSeconds != 0 {
|
||||
maxAgeSeconds = &r.MaxAgeSeconds
|
||||
}
|
||||
return r, matchedOrigin, allowed, maxAgeSeconds, true
|
||||
}
|
||||
return nil, "", nil, nil, false
|
||||
}
|
||||
@@ -0,0 +1,222 @@
|
||||
// Copyright (c) 2015-2021 MinIO, Inc.
|
||||
//
|
||||
// This file is part of MinIO Object Storage stack
|
||||
//
|
||||
// This program is free software: you can redistribute it and/or modify
|
||||
// it under the terms of the GNU Affero General Public License as published by
|
||||
// the Free Software Foundation, either version 3 of the License, or
|
||||
// (at your option) any later version.
|
||||
|
||||
package cors
|
||||
|
||||
import (
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestParseStandardS3Namespace(t *testing.T) {
|
||||
doc := `<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><CORSRule><AllowedOrigin>https://app.example.com</AllowedOrigin><AllowedMethod>GET</AllowedMethod></CORSRule></CORSConfiguration>`
|
||||
cfg, err := ParseBucketCorsConfig(strings.NewReader(doc))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = cfg.Validate(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, _, ok := cfg.MatchRule("https://app.example.com", "GET"); !ok {
|
||||
t.Fatal("standard S3 namespace document did not produce a matching rule")
|
||||
}
|
||||
}
|
||||
|
||||
const minimalCORSConfig = `<CORSConfiguration><CORSRule><AllowedOrigin>*</AllowedOrigin><AllowedMethod>GET</AllowedMethod></CORSRule></CORSConfiguration>`
|
||||
|
||||
func TestParseRejectsTrailingXMLRoot(t *testing.T) {
|
||||
for name, suffix := range map[string]string{
|
||||
"second root": `<Extra/>`,
|
||||
"text": `junk`,
|
||||
"dangling close": `</Extra>`,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
if _, err := ParseBucketCorsConfig(strings.NewReader(minimalCORSConfig + suffix)); err == nil {
|
||||
t.Fatalf("expected trailing %s to be rejected", name)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseAllowsXMLMiscAfterRoot(t *testing.T) {
|
||||
for name, suffix := range map[string]string{
|
||||
"whitespace": " \n\t",
|
||||
"comment": `<!-- trailing comment -->`,
|
||||
"processing instruction": `<?cors-test done?>`,
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
if _, err := ParseBucketCorsConfig(strings.NewReader(minimalCORSConfig + suffix)); err != nil {
|
||||
t.Fatalf("valid trailing XML misc was rejected: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateCORSRuleIDCountsCharacters(t *testing.T) {
|
||||
doc := `<CORSConfiguration><CORSRule><ID>` + strings.Repeat("界", 255) + `</ID><AllowedOrigin>*</AllowedOrigin><AllowedMethod>GET</AllowedMethod></CORSRule></CORSConfiguration>`
|
||||
cfg, err := ParseBucketCorsConfig(strings.NewReader(doc))
|
||||
if err != nil {
|
||||
t.Fatalf("parse failed: %v", err)
|
||||
}
|
||||
if err = cfg.Validate(); err != nil {
|
||||
t.Fatalf("255-character rule ID must be accepted: %v", err)
|
||||
}
|
||||
|
||||
cfg.CORSRules[0].ID += "界"
|
||||
if err = cfg.Validate(); err == nil {
|
||||
t.Fatal("256-character rule ID must be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRejectsNonCanonicalAllowedMethod(t *testing.T) {
|
||||
doc := `<CORSConfiguration><CORSRule><AllowedOrigin>*</AllowedOrigin><AllowedMethod>get</AllowedMethod></CORSRule></CORSConfiguration>`
|
||||
cfg, err := ParseBucketCorsConfig(strings.NewReader(doc))
|
||||
if err != nil {
|
||||
t.Fatalf("parse failed: %v", err)
|
||||
}
|
||||
if err = cfg.Validate(); err == nil {
|
||||
t.Fatal("expected lowercase AllowedMethod to be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestAllowedMethodMatchingIsCaseSensitive(t *testing.T) {
|
||||
rule := Rule{AllowedMethods: []string{"GET"}}
|
||||
if !rule.HasAllowedMethod("GET") {
|
||||
t.Fatal("expected canonical GET to match")
|
||||
}
|
||||
if rule.HasAllowedMethod("get") {
|
||||
t.Fatal("lowercase request method must not match canonical GET")
|
||||
}
|
||||
}
|
||||
|
||||
func TestParseRejectsElementsOutsideCORSShape(t *testing.T) {
|
||||
tests := map[string]string{
|
||||
"unknown root child": `<CORSConfiguration><Unknown/><CORSRule><AllowedOrigin>*</AllowedOrigin><AllowedMethod>GET</AllowedMethod></CORSRule></CORSConfiguration>`,
|
||||
"unknown rule child": `<CORSConfiguration><CORSRule><AllowedOrigin>*</AllowedOrigin><AllowedMethod>GET</AllowedMethod><Unknown/></CORSRule></CORSConfiguration>`,
|
||||
"nested origin child": `<CORSConfiguration><CORSRule><AllowedOrigin><Unknown/></AllowedOrigin><AllowedMethod>GET</AllowedMethod></CORSRule></CORSConfiguration>`,
|
||||
"duplicate id": `<CORSConfiguration><CORSRule><ID>a</ID><ID>b</ID><AllowedOrigin>*</AllowedOrigin><AllowedMethod>GET</AllowedMethod></CORSRule></CORSConfiguration>`,
|
||||
"duplicate max age": `<CORSConfiguration><CORSRule><AllowedOrigin>*</AllowedOrigin><AllowedMethod>GET</AllowedMethod><MaxAgeSeconds>1</MaxAgeSeconds><MaxAgeSeconds>2</MaxAgeSeconds></CORSRule></CORSConfiguration>`,
|
||||
"empty max age": `<CORSConfiguration><CORSRule><AllowedOrigin>*</AllowedOrigin><AllowedMethod>GET</AllowedMethod><MaxAgeSeconds/></CORSRule></CORSConfiguration>`,
|
||||
"overflow max age": `<CORSConfiguration><CORSRule><AllowedOrigin>*</AllowedOrigin><AllowedMethod>GET</AllowedMethod><MaxAgeSeconds>2147483648</MaxAgeSeconds></CORSRule></CORSConfiguration>`,
|
||||
}
|
||||
|
||||
for name, doc := range tests {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
if _, err := ParseBucketCorsConfig(strings.NewReader(doc)); err == nil {
|
||||
t.Fatal("expected parse error")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestMaxAgeSecondsPresence(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
element string
|
||||
value int
|
||||
present bool
|
||||
}{
|
||||
{name: "absent"},
|
||||
{name: "zero", element: `<MaxAgeSeconds>0</MaxAgeSeconds>`, present: true},
|
||||
{name: "positive", element: `<MaxAgeSeconds>3000</MaxAgeSeconds>`, value: 3000, present: true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
doc := `<CORSConfiguration><CORSRule><AllowedOrigin>*</AllowedOrigin><AllowedMethod>GET</AllowedMethod>` + tt.element + `</CORSRule></CORSConfiguration>`
|
||||
cfg, err := ParseBucketCorsConfig(strings.NewReader(doc))
|
||||
if err != nil {
|
||||
t.Fatalf("parse failed: %v", err)
|
||||
}
|
||||
rule := cfg.CORSRules[0]
|
||||
_, _, _, maxAgeSeconds, ok := cfg.MatchPreflight("https://example.com", "GET", nil)
|
||||
if !ok {
|
||||
t.Fatal("expected rule to match")
|
||||
}
|
||||
present := maxAgeSeconds != nil
|
||||
if rule.MaxAgeSeconds != tt.value || present != tt.present {
|
||||
t.Fatalf("MaxAgeSeconds = %d, present = %v", rule.MaxAgeSeconds, present)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateRuleCountBoundary(t *testing.T) {
|
||||
rule := Rule{AllowedOrigins: []string{"*"}, AllowedMethods: []string{"GET"}}
|
||||
cfg := Config{CORSRules: make([]Rule, 100)}
|
||||
for i := range cfg.CORSRules {
|
||||
cfg.CORSRules[i] = rule
|
||||
}
|
||||
if err := cfg.Validate(); err != nil {
|
||||
t.Fatalf("100 rules must be accepted: %v", err)
|
||||
}
|
||||
cfg.CORSRules = append(cfg.CORSRules, rule)
|
||||
if err := cfg.Validate(); err == nil {
|
||||
t.Fatal("101 rules must be rejected")
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateMaxAgeSecondsBoundary(t *testing.T) {
|
||||
cfg := Config{CORSRules: []Rule{{
|
||||
AllowedOrigins: []string{"*"},
|
||||
AllowedMethods: []string{"GET"},
|
||||
MaxAgeSeconds: maxCORSMaxAgeSeconds,
|
||||
}}}
|
||||
if err := cfg.Validate(); err != nil {
|
||||
t.Fatalf("MaxAgeSeconds int32 maximum must be accepted: %v", err)
|
||||
}
|
||||
if strconv.IntSize > 32 {
|
||||
overflow := int64(maxCORSMaxAgeSeconds) + 1
|
||||
cfg.CORSRules[0].MaxAgeSeconds = int(overflow)
|
||||
if err := cfg.Validate(); err == nil {
|
||||
t.Fatal("MaxAgeSeconds above int32 maximum must be rejected")
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestSingleWildcardMatching(t *testing.T) {
|
||||
tests := []struct {
|
||||
pattern string
|
||||
value string
|
||||
want bool
|
||||
}{
|
||||
{"*", "https://example.com", true},
|
||||
{"https://*.example.com", "https://api.example.com", true},
|
||||
{"https://*.example.com", "https://.example.com", true},
|
||||
{"https://*.example.com", "http://api.example.com", false},
|
||||
{"https://?.example.com", "https://a.example.com", false},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
if got := matchSingleWildcard(tt.pattern, tt.value); got != tt.want {
|
||||
t.Errorf("matchSingleWildcard(%q, %q) = %v, want %v", tt.pattern, tt.value, got, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestMatchRuleReturnsMatchedOriginPattern(t *testing.T) {
|
||||
cfg := Config{CORSRules: []Rule{{
|
||||
AllowedOrigins: []string{"https://app.example.com", "https://*", "*"},
|
||||
AllowedMethods: []string{"GET"},
|
||||
}}}
|
||||
tests := []struct {
|
||||
origin string
|
||||
want string
|
||||
}{
|
||||
{"https://app.example.com", "https://app.example.com"},
|
||||
{"https://other.example.com", "https://*"},
|
||||
{"http://other.example.com", "*"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
_, got, ok := cfg.MatchRule(tt.origin, "GET")
|
||||
if !ok || got != tt.want {
|
||||
t.Errorf("origin %q matched %q, ok=%v; want %q", tt.origin, got, ok, tt.want)
|
||||
}
|
||||
}
|
||||
}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user