mirror of
https://github.com/pgsty/minio.git
synced 2026-11-29 02:24:04 +03:00
Compare commits
32 Commits
| Author | SHA1 | Date | |
|---|---|---|---|
| f175e98c34 | |||
| 12f631b502 | |||
| ccb676e60c | |||
| 51d41345f7 | |||
| e59a3d938e | |||
| b32f2d9dd0 | |||
| d63c92e393 | |||
| 68127c5a63 | |||
| c4b5e1cb45 | |||
| 9a303f5096 | |||
| 87d8b5967f | |||
| f760046c44 | |||
| 93e7ef4bcc | |||
| a4229b366f | |||
| 420340bc14 | |||
| e7e87402ed | |||
| a164e1dda1 | |||
| 2f61325d4a | |||
| a6145e1d2e | |||
| 5232546690 | |||
| 0c46cb641b | |||
| 1233254309 | |||
| 8a2fe9b7a0 | |||
| f26ee6bf0a | |||
| d69c4ccfe4 | |||
| 086e619505 | |||
| 48e1846525 | |||
| bcc8871b1d | |||
| 25cb3511c9 | |||
| cfefc049c1 | |||
| af56d17630 | |||
| 75ba0ce402 |
+3
-1
@@ -1,6 +1,6 @@
|
||||
# Contributors
|
||||
|
||||
SILO is built by **40 community contributors**, including its maintainers. This record covers every
|
||||
SILO is built by **41 community contributors**, including its maintainers. This record covers every
|
||||
human author who has opened an issue or pull request in the repositories listed below, in any state.
|
||||
It was checked against the complete, paginated GitHub API records on **2026-09-07 03:00:14 UTC**.
|
||||
|
||||
@@ -30,6 +30,7 @@ the Git history and [NOTICE](NOTICE); this record covers activity in the PGSTY r
|
||||
<a href="https://github.com/sulin37392"><img src="https://silo.pgsty.com/images/contributors/sulin37392.svg" width="48" height="48" alt="@sulin37392" title="@sulin37392 — Proposed dependency updates"></a>
|
||||
<a href="https://github.com/cbornet"><img src="https://silo.pgsty.com/images/contributors/cbornet.svg" width="60" height="60" alt="@cbornet" title="@cbornet — Reported multipart and streaming checksum defects and missing-bucket semantics"></a>
|
||||
<a href="https://github.com/vampywiz17"><img src="https://silo.pgsty.com/images/contributors/vampywiz17.svg" width="60" height="60" alt="@vampywiz17" title="@vampywiz17 — Reported LDAP TLS and Console login regressions"></a>
|
||||
<a href="https://github.com/orenyomtov"><img src="https://silo.pgsty.com/images/contributors/orenyomtov.svg" width="60" height="60" alt="@orenyomtov" title="@orenyomtov — Reported the unsigned-header CopyObject cross-object read (SN-2026-011)"></a>
|
||||
<a href="https://github.com/mumu-lab"><img src="https://silo.pgsty.com/images/contributors/mumu-lab.svg" width="48" height="48" alt="@mumu-lab" title="@mumu-lab — Reported bucket quota metrics reading a deprecated field"></a>
|
||||
<a href="https://github.com/jvasile"><img src="https://silo.pgsty.com/images/contributors/jvasile.svg" width="48" height="48" alt="@jvasile" title="@jvasile — Reported missing user, group, and defaults in Debian packages"></a>
|
||||
<a href="https://github.com/pmezhuev"><img src="https://silo.pgsty.com/images/contributors/pmezhuev.svg" width="48" height="48" alt="@pmezhuev" title="@pmezhuev — Reported missing RPM package signatures"></a>
|
||||
@@ -96,6 +97,7 @@ for their reports as well; the avatar wall and community total still count each
|
||||
| [@davinkevin](https://github.com/davinkevin) | [pgsty/silo#20](https://github.com/pgsty/silo/issues/20) Proposal: Enable Renovate for automated dependency updates |
|
||||
| [@cbornet](https://github.com/cbornet) | [pgsty/silo#31](https://github.com/pgsty/silo/issues/31) Multipart uploads with FULL_OBJECT CRC32 not working<br>[pgsty/silo#32](https://github.com/pgsty/silo/issues/32) `listObjects` should return `NoSuchBucket` when the bucket doesn't exist and prefix is passed<br>[pgsty/silo#107](https://github.com/pgsty/silo/issues/107) PutObject fails with chunked encoding and checksumType |
|
||||
| [@vampywiz17](https://github.com/vampywiz17) | [pgsty/silo#15](https://github.com/pgsty/silo/issues/15) LDAP TLS regression in RELEASE.2026-03-21T00-00-00Z breaks built-in Console and external Console LDAP login on Kubernetes Tenant<br>[pgsty/silo#108](https://github.com/pgsty/silo/issues/108) Web Console login regression in RELEASE.2026-09-03T13-18-01Z (local and LDAP users fail) |
|
||||
| [@orenyomtov](https://github.com/orenyomtov) | Private security disclosure: a presigned or signed PUT could be turned into a server-side CopyObject read of any object the signing key can reach via an unsigned `x-amz-copy-source` header. Fixed as [`SN-2026-011`](https://github.com/pgsty/silo/blob/main/docs/security/advisories.md) ([pgsty/silo#173](https://github.com/pgsty/silo/pull/173)) |
|
||||
| [@mumu-lab](https://github.com/mumu-lab) | [pgsty/silo#106](https://github.com/pgsty/silo/issues/106) 监控指标读取已弃用的 BucketQuota.Quota 字段导致 Quota 指标无值 |
|
||||
| [@jvasile](https://github.com/jvasile) | [pgsty/silo#33](https://github.com/pgsty/silo/issues/33) .deb doesn't create user/group/default files |
|
||||
| [@pmezhuev](https://github.com/pmezhuev) | [pgsty/silo#43](https://github.com/pgsty/silo/issues/43) RPM package for RELEASE.2026-06-18T00-00-00Z is missing GPG signature |
|
||||
|
||||
@@ -89,13 +89,33 @@ The S3 API, `MINIO_*` variables, `minio_*` metrics, `x-minio-*` headers, `/minio
|
||||
|
||||
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.
|
||||
|
||||
### TLS and Go upgrades
|
||||
|
||||
TLS key exchange follows Go's defaults across the S3 listener, node links,
|
||||
replication, identity providers, etcd, and external HTTP services. If an endpoint
|
||||
cannot accept ML-KEM, `GODEBUG=tlsmlkem=0` disables the default hybrid exchanges
|
||||
for the process; certificate verification remains enabled. This option does not
|
||||
disable ML-DSA signatures or resolve every TLS reset. Prefer updating the
|
||||
incompatible endpoint before removing the temporary setting.
|
||||
If only the new SecP hybrids cause problems, `GODEBUG=tlssecpmlkem=0` disables
|
||||
those groups while retaining X25519MLKEM768.
|
||||
|
||||
For builds targeting Go 1.27, setting either `SSL_CERT_FILE` or `SSL_CERT_DIR`
|
||||
on macOS replaces Keychain trust with on-disk roots and Go's verifier. Stale or
|
||||
incomplete CA paths can break previously trusted connections; unset inherited
|
||||
values to restore Keychain trust. Explicit certificates in the configured `CAs`
|
||||
directory remain additive to the selected root pool.
|
||||
Go 1.27 binaries require macOS 13 or later. See the
|
||||
[Go release notes](https://go.dev/doc/go1.27) and the
|
||||
[SILO stack investigation](docs/investigations/go127-stack.md).
|
||||
|
||||
## Security & Contributing
|
||||
|
||||
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).
|
||||
|
||||
## Contributors
|
||||
|
||||
**40 community contributors** build SILO, Console, mcli, shared packages, and related projects. The list includes maintainers and every human Issue or PR author, ordered by merged PRs, other PRs, then issue reports. Gold rings highlight significant contributions.
|
||||
**41 community contributors** build SILO, Console, mcli, shared packages, and related projects. The list includes maintainers and every human Issue or PR author, ordered by merged PRs, other PRs, then issue reports. Gold rings highlight significant contributions.
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/Vonng"><img src="https://silo.pgsty.com/images/contributors/Vonng.svg" width="60" height="60" alt="@Vonng" title="@Vonng — Maintains SILO, Console, mcli, shared packages, releases, and documentation"></a>
|
||||
@@ -115,6 +135,7 @@ Report vulnerabilities privately as described in [`SECURITY.md`](SECURITY.md); e
|
||||
<a href="https://github.com/sulin37392"><img src="https://silo.pgsty.com/images/contributors/sulin37392.svg" width="48" height="48" alt="@sulin37392" title="@sulin37392 — Proposed dependency updates"></a>
|
||||
<a href="https://github.com/cbornet"><img src="https://silo.pgsty.com/images/contributors/cbornet.svg" width="60" height="60" alt="@cbornet" title="@cbornet — Reported multipart and streaming checksum defects and missing-bucket semantics"></a>
|
||||
<a href="https://github.com/vampywiz17"><img src="https://silo.pgsty.com/images/contributors/vampywiz17.svg" width="60" height="60" alt="@vampywiz17" title="@vampywiz17 — Reported LDAP TLS and Console login regressions"></a>
|
||||
<a href="https://github.com/orenyomtov"><img src="https://silo.pgsty.com/images/contributors/orenyomtov.svg" width="60" height="60" alt="@orenyomtov" title="@orenyomtov — Reported the unsigned-header CopyObject cross-object read (SN-2026-011)"></a>
|
||||
<a href="https://github.com/mumu-lab"><img src="https://silo.pgsty.com/images/contributors/mumu-lab.svg" width="48" height="48" alt="@mumu-lab" title="@mumu-lab — Reported bucket quota metrics reading a deprecated field"></a>
|
||||
<a href="https://github.com/jvasile"><img src="https://silo.pgsty.com/images/contributors/jvasile.svg" width="48" height="48" alt="@jvasile" title="@jvasile — Reported missing user, group, and defaults in Debian packages"></a>
|
||||
<a href="https://github.com/pmezhuev"><img src="https://silo.pgsty.com/images/contributors/pmezhuev.svg" width="48" height="48" alt="@pmezhuev" title="@pmezhuev — Reported missing RPM package signatures"></a>
|
||||
|
||||
+2
-1
@@ -95,7 +95,7 @@ S3 API、`MINIO_*` 环境变量、`minio_*` 指标、`x-minio-*` 头、`/minio/*
|
||||
|
||||
## 贡献者
|
||||
|
||||
**40 位社区贡献者**共同建设 SILO、Console、mcli、公共包与相关项目。名单包含维护者,以及所有提出 Issue 或 PR 的真人作者;按已合并 PR、其他 PR、Issue 报告排序,黄圈标记显著贡献。
|
||||
**41 位社区贡献者**共同建设 SILO、Console、mcli、公共包与相关项目。名单包含维护者,以及所有提出 Issue 或 PR 的真人作者;按已合并 PR、其他 PR、Issue 报告排序,黄圈标记显著贡献。
|
||||
|
||||
<p align="center">
|
||||
<a href="https://github.com/Vonng"><img src="https://silo.pgsty.com/images/contributors/Vonng.svg" width="60" height="60" alt="@Vonng" title="@Vonng — 维护 SILO、Console、mcli、公共包、发行与文档"></a>
|
||||
@@ -115,6 +115,7 @@ S3 API、`MINIO_*` 环境变量、`minio_*` 指标、`x-minio-*` 头、`/minio/*
|
||||
<a href="https://github.com/sulin37392"><img src="https://silo.pgsty.com/images/contributors/sulin37392.svg" width="48" height="48" alt="@sulin37392" title="@sulin37392 — 提交依赖更新"></a>
|
||||
<a href="https://github.com/cbornet"><img src="https://silo.pgsty.com/images/contributors/cbornet.svg" width="60" height="60" alt="@cbornet" title="@cbornet — 报告分片与流式校验和缺陷及缺失桶语义问题"></a>
|
||||
<a href="https://github.com/vampywiz17"><img src="https://silo.pgsty.com/images/contributors/vampywiz17.svg" width="60" height="60" alt="@vampywiz17" title="@vampywiz17 — 报告 LDAP TLS 与 Console 登录回归"></a>
|
||||
<a href="https://github.com/orenyomtov"><img src="https://silo.pgsty.com/images/contributors/orenyomtov.svg" width="60" height="60" alt="@orenyomtov" title="@orenyomtov — 报告未签名头导致的 CopyObject 跨对象读取(SN-2026-011)"></a>
|
||||
<a href="https://github.com/mumu-lab"><img src="https://silo.pgsty.com/images/contributors/mumu-lab.svg" width="48" height="48" alt="@mumu-lab" title="@mumu-lab — 报告桶配额指标读取已弃用字段的问题"></a>
|
||||
<a href="https://github.com/jvasile"><img src="https://silo.pgsty.com/images/contributors/jvasile.svg" width="48" height="48" alt="@jvasile" title="@jvasile — 报告 Debian 包缺少用户、用户组与默认配置"></a>
|
||||
<a href="https://github.com/pmezhuev"><img src="https://silo.pgsty.com/images/contributors/pmezhuev.svg" width="48" height="48" alt="@pmezhuev" title="@pmezhuev — 报告 RPM 包缺少 GPG 签名"></a>
|
||||
|
||||
@@ -627,6 +627,7 @@
|
||||
"x-minio-internal-transitioned-object",
|
||||
"x-minio-internal-xyz",
|
||||
"x-minio-key",
|
||||
"x-minio-last-modified",
|
||||
"x-minio-lifecycleconfig-updatedat",
|
||||
"x-minio-meta",
|
||||
"x-minio-meta-appid",
|
||||
@@ -1071,6 +1072,7 @@
|
||||
"cmd/metrics.go=\"Version of current MinIO server instance\"",
|
||||
"cmd/metrics.go=\"minio\"",
|
||||
"cmd/object-api-utils.go=\".minio.sys\"",
|
||||
"cmd/object-handlers-common.go=\"X-Minio-Last-Modified\"",
|
||||
"cmd/object-handlers.go=\"minio-federated\"",
|
||||
"cmd/object-handlers.go=\"minio.metadata.\"",
|
||||
"cmd/object-handlers.go=\"minio.versionId\"",
|
||||
|
||||
@@ -115,7 +115,9 @@ func collect(repo string) (manifest, error) {
|
||||
fset := token.NewFileSet()
|
||||
|
||||
for _, rel := range files {
|
||||
// Investigation artifacts contain synthetic routes and archived configurations.
|
||||
if rel == "SILO_REBRANDING_MIGRATION.md" ||
|
||||
strings.HasPrefix(rel, "docs/investigations/") ||
|
||||
strings.HasPrefix(rel, "buildscripts/rebrand-guard/") ||
|
||||
strings.HasPrefix(rel, "buildscripts/helm-migration-guard/") {
|
||||
continue
|
||||
|
||||
@@ -502,11 +502,15 @@ func (a adminAPIHandlers) AddUser(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
|
||||
checkDenyOnly := accessKey == cred.AccessKey
|
||||
action := policy.Action(policy.CreateUserAdminAction)
|
||||
if checkDenyOnly {
|
||||
action = policy.ChangeMyPasswordAdminAction
|
||||
}
|
||||
|
||||
if !globalIAMSys.IsAllowed(policy.Args{
|
||||
AccountName: cred.AccessKey,
|
||||
Groups: cred.Groups,
|
||||
Action: policy.CreateUserAdminAction,
|
||||
Action: action,
|
||||
ConditionValues: getConditionValues(r, "", cred),
|
||||
IsOwner: owner,
|
||||
Claims: cred.Claims,
|
||||
|
||||
@@ -243,6 +243,7 @@ func TestIAMInternalIDPServerSuite(t *testing.T) {
|
||||
|
||||
suite.SetUpSuite(c)
|
||||
suite.TestUserCreate(c)
|
||||
suite.TestUserPasswordActionAuthorization(c)
|
||||
suite.TestUserStatusActionAuthorization(c)
|
||||
suite.TestGroupStatusActionAuthorization(c)
|
||||
suite.TestUserPolicyEscalationBug(c)
|
||||
@@ -356,6 +357,106 @@ func (s *TestSuiteIAM) TestUserCreate(c *check) {
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TestSuiteIAM) TestUserPasswordActionAuthorization(c *check) {
|
||||
for _, tt := range []struct {
|
||||
name string
|
||||
statements string
|
||||
self bool
|
||||
other bool
|
||||
}{
|
||||
{"readonly", "", true, false},
|
||||
{"consolereadonly", "", true, false},
|
||||
{"password grant", `{"Effect":"Allow","Action":"admin:ChangeMyPassword"}`, true, false},
|
||||
{"legacy CreateUser deny", `{"Effect":"Deny","Action":"admin:CreateUser","Resource":"arn:aws:s3:::*"}`, true, false},
|
||||
{"password deny", `{"Effect":"Deny","Action":"admin:ChangeMyPassword"}`, false, false},
|
||||
{"user admin", `{"Effect":"Allow","Action":"admin:CreateUser"}`, true, true},
|
||||
{"user admin with password deny", `{"Effect":"Allow","Action":"admin:CreateUser"},{"Effect":"Deny","Action":"admin:ChangeMyPassword"}`, false, true},
|
||||
{"password deny overrides grant", `{"Effect":"Allow","Action":"admin:ChangeMyPassword"},{"Effect":"Deny","Action":"admin:ChangeMyPassword"}`, false, false},
|
||||
{"wildcard deny", `{"Effect":"Deny","Action":"admin:*"}`, false, false},
|
||||
} {
|
||||
c.Run(tt.name, func(t *testing.T) {
|
||||
c := &check{t, s.serverType}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), testDefaultTimeout)
|
||||
defer cancel()
|
||||
var users []string
|
||||
policyName := tt.name
|
||||
defer func() {
|
||||
for _, user := range users {
|
||||
if err := s.adm.RemoveUser(ctx, user); err != nil {
|
||||
c.Errorf("remove test user: %v", err)
|
||||
}
|
||||
}
|
||||
if tt.statements != "" {
|
||||
if err := s.adm.RemoveCannedPolicy(ctx, policyName); err != nil {
|
||||
c.Errorf("remove test policy: %v", err)
|
||||
}
|
||||
}
|
||||
}()
|
||||
createUser := func() (string, string) {
|
||||
accessKey, secretKey := mustGenerateCredentials(c)
|
||||
if err := s.adm.SetUser(ctx, accessKey, secretKey, madmin.AccountEnabled); err != nil {
|
||||
c.Fatalf("create test user: %v", err)
|
||||
}
|
||||
users = append(users, accessKey)
|
||||
return accessKey, secretKey
|
||||
}
|
||||
client := func(accessKey, secretKey string) *madmin.AdminClient {
|
||||
adm, err := madmin.New(s.endpoint, accessKey, secretKey, s.secure)
|
||||
if err != nil {
|
||||
c.Fatal(err)
|
||||
}
|
||||
adm.SetCustomTransport(s.TestSuiteCommon.client.Transport)
|
||||
return adm
|
||||
}
|
||||
if tt.statements != "" {
|
||||
policyName = getRandomBucketName()
|
||||
doc := []byte(`{"Version":"2012-10-17","Statement":[` + tt.statements + `]}`)
|
||||
if err := s.adm.AddCannedPolicy(ctx, policyName, doc); err != nil {
|
||||
c.Fatalf("save test policy: %v", err)
|
||||
}
|
||||
}
|
||||
accessKey, secretKey := createUser()
|
||||
if _, err := s.adm.AttachPolicy(ctx, madmin.PolicyAssociationReq{
|
||||
User: accessKey, Policies: []string{policyName},
|
||||
}); err != nil {
|
||||
c.Fatalf("attach test policy: %v", err)
|
||||
}
|
||||
adm := client(accessKey, secretKey)
|
||||
_, newSecretKey := mustGenerateCredentials(c)
|
||||
err := adm.SetUser(ctx, accessKey, newSecretKey, madmin.AccountEnabled)
|
||||
if tt.self {
|
||||
if err != nil {
|
||||
c.Fatalf("change own password: %v", err)
|
||||
}
|
||||
if _, err = adm.AccountInfo(ctx, madmin.AccountOpts{}); err == nil {
|
||||
c.Fatal("old password still authenticates")
|
||||
}
|
||||
adm = client(accessKey, newSecretKey)
|
||||
} else if err == nil || madmin.ToErrorResponse(err).Code != "AccessDenied" {
|
||||
c.Fatalf("self password change: expected AccessDenied, got %v", err)
|
||||
}
|
||||
if _, err := adm.AccountInfo(ctx, madmin.AccountOpts{}); err != nil {
|
||||
c.Fatalf("current password no longer authenticates: %v", err)
|
||||
}
|
||||
target, _ := createUser()
|
||||
newUser, newUserSecret := mustGenerateCredentials(c)
|
||||
for _, key := range []string{target, newUser} {
|
||||
err := adm.SetUser(ctx, key, newUserSecret, madmin.AccountEnabled)
|
||||
if tt.other {
|
||||
if err != nil {
|
||||
c.Fatalf("create or update another user: %v", err)
|
||||
}
|
||||
if key == newUser {
|
||||
users = append(users, newUser)
|
||||
}
|
||||
} else if err == nil || madmin.ToErrorResponse(err).Code != "AccessDenied" {
|
||||
c.Fatalf("create or update another user: expected AccessDenied, got %v", err)
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func (s *TestSuiteIAM) TestUserStatusActionAuthorization(c *check) {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), testDefaultTimeout)
|
||||
defer cancel()
|
||||
@@ -946,6 +1047,7 @@ func (s *TestSuiteIAM) TestCannedPolicies(c *check) {
|
||||
defaultPolicies := []string{
|
||||
"readwrite",
|
||||
"readonly",
|
||||
"consolereadonly",
|
||||
"writeonly",
|
||||
"diagnostics",
|
||||
"consoleAdmin",
|
||||
|
||||
+4
-11
@@ -632,18 +632,11 @@ func isReqAuthenticated(ctx context.Context, r *http.Request, region string, sty
|
||||
return ErrInvalidDigest
|
||||
}
|
||||
|
||||
// Extract either 'X-Amz-Content-Sha256' header or 'X-Amz-Content-Sha256' query parameter (if V4 presigned)
|
||||
// Do not verify 'X-Amz-Content-Sha256' if skipSHA256.
|
||||
// Honor the selected header/query checksum, including the header fallback
|
||||
// for a presigned request. STS separately hashes its body for its signature.
|
||||
var contentSHA256 []byte
|
||||
if skipSHA256 := skipContentSha256Cksum(r); !skipSHA256 && isRequestPresignedSignatureV4(r) {
|
||||
if sha256Sum, ok := r.Form[xhttp.AmzContentSha256]; ok && len(sha256Sum) > 0 {
|
||||
contentSHA256, err = hex.DecodeString(sha256Sum[0])
|
||||
if err != nil {
|
||||
return ErrContentSHA256Mismatch
|
||||
}
|
||||
}
|
||||
} else if _, ok := r.Header[xhttp.AmzContentSha256]; !skipSHA256 && ok {
|
||||
contentSHA256, err = hex.DecodeString(r.Header.Get(xhttp.AmzContentSha256))
|
||||
if !skipContentSha256Cksum(r) {
|
||||
contentSHA256, err = hex.DecodeString(getContentSha256Cksum(r, serviceS3))
|
||||
if err != nil || len(contentSHA256) == 0 {
|
||||
return ErrContentSHA256Mismatch
|
||||
}
|
||||
|
||||
@@ -4,22 +4,15 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/minio/internal/auth"
|
||||
"github.com/minio/minio/internal/event"
|
||||
"github.com/minio/minio/internal/grid"
|
||||
)
|
||||
|
||||
func TestDeleteBucketMetadataLockCancellation(t *testing.T) {
|
||||
@@ -34,21 +27,43 @@ func testDeleteBucketMetadataLockCancellation(obj ObjectLayer, instanceType, buc
|
||||
}
|
||||
release := sync.OnceFunc(unlock)
|
||||
defer release()
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 250*time.Millisecond)
|
||||
|
||||
// Observe DeleteBucket's ACTUAL metadata.lock attempt. Set the hook after
|
||||
// our own acquisition above so it only trips on the delete.
|
||||
delAtLock := make(chan struct{})
|
||||
var once sync.Once
|
||||
hook := func(b string) {
|
||||
if b == bucket {
|
||||
once.Do(func() { close(delAtLock) })
|
||||
}
|
||||
}
|
||||
lockBucketMetadataAcquireHook.Store(&hook)
|
||||
defer lockBucketMetadataAcquireHook.Store(nil)
|
||||
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- obj.DeleteBucket(ctx, bucket, DeleteBucketOptions{Force: true, NoLock: true}) }()
|
||||
<-ctx.Done()
|
||||
// A metadata-lock failure must happen before the destructive operation.
|
||||
if _, err := obj.GetBucketInfo(t.Context(), bucket, BucketOptions{}); err != nil {
|
||||
t.Errorf("%s: bucket disappeared while metadata.lock was unavailable: %v", instanceType, err)
|
||||
}
|
||||
release()
|
||||
if err := <-done; err == nil {
|
||||
t.Errorf("%s: canceled deletion succeeded", instanceType)
|
||||
}
|
||||
if _, err := readBucketMetadata(t.Context(), obj, bucket); err != nil {
|
||||
t.Errorf("%s: canceled deletion removed metadata: %v", instanceType, err)
|
||||
|
||||
select {
|
||||
case <-delAtLock:
|
||||
// Fixed tree: the delete reached metadata.lock and is blocking on the
|
||||
// lock we hold. Cancel it and confirm it fails WITHOUT deleting, while we
|
||||
// still hold the lock (release stays deferred until after the checks).
|
||||
cancel()
|
||||
if err := <-done; err == nil {
|
||||
t.Errorf("%s: canceled deletion succeeded", instanceType)
|
||||
}
|
||||
if _, err := obj.GetBucketInfo(t.Context(), bucket, BucketOptions{}); err != nil {
|
||||
t.Errorf("%s: bucket disappeared while metadata.lock was held: %v", instanceType, err)
|
||||
}
|
||||
if _, err := readBucketMetadata(t.Context(), obj, bucket); err != nil {
|
||||
t.Errorf("%s: canceled deletion removed metadata: %v", instanceType, err)
|
||||
}
|
||||
case err := <-done:
|
||||
// Broken tree: the delete finished without ever taking metadata.lock,
|
||||
// i.e. it did not serialize the destructive operation behind the lock.
|
||||
t.Errorf("%s: delete bypassed metadata.lock (err=%v)", instanceType, err)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -94,110 +109,3 @@ func TestQueuedMetadataUpdateAfterDelete(t *testing.T) {
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Pause the first actual peer-handler read, without replacing the handler or
|
||||
// requiring it to accept a test-only context.
|
||||
type peerMetadataReadBarrier struct {
|
||||
ObjectLayer
|
||||
bucket string
|
||||
once sync.Once
|
||||
reading, release chan struct{}
|
||||
}
|
||||
|
||||
func (o *peerMetadataReadBarrier) GetObjectNInfo(ctx context.Context, bucket, object string, rs *HTTPRangeSpec, h http.Header, opts ObjectOptions) (*GetObjectReader, error) {
|
||||
first := false
|
||||
if bucket == minioMetaBucket && object == pathJoin(bucketMetaPrefix, o.bucket, bucketMetadataFile) {
|
||||
o.once.Do(func() { first = true })
|
||||
}
|
||||
gr, err := o.ObjectLayer.GetObjectNInfo(ctx, bucket, object, rs, h, opts)
|
||||
if err != nil || !first {
|
||||
return gr, err
|
||||
}
|
||||
data, err := io.ReadAll(gr)
|
||||
oi := gr.ObjInfo
|
||||
gr.Close()
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
close(o.reading)
|
||||
select {
|
||||
case <-o.release:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return NewGetObjectReaderFromReader(bytes.NewReader(data), oi, opts)
|
||||
}
|
||||
|
||||
func TestPeerMetadataReloadPreservesCurrentTargets(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{t: t, objAPITest: testPeerMetadataReloadPreservesCurrentTargets})
|
||||
}
|
||||
|
||||
func testPeerMetadataReloadPreservesCurrentTargets(obj ObjectLayer, instanceType, bucket string, _ http.Handler, _ auth.Credentials, t *testing.T) {
|
||||
seed := func(revision string) {
|
||||
t.Helper()
|
||||
arn := event.ARN{TargetID: event.TargetID{ID: revision, Name: "webhook"}}
|
||||
notification := []byte(`<NotificationConfiguration><QueueConfiguration><Id>` + revision + `</Id><Queue>` + arn.String() + `</Queue><Event>s3:ObjectCreated:*</Event></QueueConfiguration></NotificationConfiguration>`)
|
||||
targets, err := json.Marshal(madmin.BucketTargets{Targets: []madmin.BucketTarget{{
|
||||
SourceBucket: bucket, TargetBucket: bucket, Endpoint: "127.0.0.1:9000", Arn: revision,
|
||||
Credentials: &madmin.Credentials{AccessKey: "fixture", SecretKey: "fixture-secret"},
|
||||
}}})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, config := range []struct {
|
||||
name string
|
||||
data []byte
|
||||
}{{bucketNotificationConfig, notification}, {bucketTargetsFile, targets}} {
|
||||
if _, err := globalBucketMetadataSys.Update(t.Context(), bucket, config.name, config.data); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
}
|
||||
reload := func() error {
|
||||
args := grid.MSS{peerRESTBucket: bucket}
|
||||
_, err := (&peerRESTServer{}).LoadBucketMetadataHandler(&args)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
return nil
|
||||
}
|
||||
seed("old")
|
||||
previous := newObjectLayerFn()
|
||||
barrier := &peerMetadataReadBarrier{ObjectLayer: obj, bucket: bucket, reading: make(chan struct{}), release: make(chan struct{})}
|
||||
setObjectLayer(barrier)
|
||||
defer setObjectLayer(previous)
|
||||
release := sync.OnceFunc(func() { close(barrier.release) })
|
||||
defer release()
|
||||
done := make(chan error, 1)
|
||||
go func() { done <- reload() }()
|
||||
select {
|
||||
case <-barrier.reading:
|
||||
case <-time.After(10 * time.Second):
|
||||
t.Fatal("peer handler did not read metadata")
|
||||
}
|
||||
seed("new")
|
||||
if err := reload(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
release()
|
||||
if err := <-done; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
meta, err := globalBucketMetadataSys.Get(bucket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
globalEventNotifier.RLock()
|
||||
rules := globalEventNotifier.bucketRulesMap[bucket].Clone()
|
||||
globalEventNotifier.RUnlock()
|
||||
if !reflect.DeepEqual(rules, meta.notificationConfig.ToRulesMap()) {
|
||||
t.Errorf("%s: stale peer reload replaced current notification rules", instanceType)
|
||||
}
|
||||
globalBucketTargetSys.RLock()
|
||||
targets := append([]madmin.BucketTarget(nil), globalBucketTargetSys.targetsMap[bucket]...)
|
||||
globalBucketTargetSys.RUnlock()
|
||||
if len(targets) != 1 || targets[0].Arn != "new" {
|
||||
t.Errorf("%s: stale peer reload replaced current replication targets: %+v", instanceType, targets)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -11,11 +11,9 @@
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"sync"
|
||||
"testing"
|
||||
@@ -163,14 +161,24 @@ func testLifecycleExpiryMergeRaceLosesConcurrentTransition(obj ObjectLayer, inst
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Target 2 (issue #105): DeleteBucket racing an already in-flight metadata
|
||||
// writer and resurrecting a ghost .metadata.bin record.
|
||||
// Target 2 (issue #105): DeleteBucket racing an in-flight metadata writer must
|
||||
// not resurrect a ghost .metadata.bin record.
|
||||
//
|
||||
// erasureServerPools.DeleteBucket takes only <bucket>.lck and purges the whole
|
||||
// metadata prefix with deleteAll. Config writers (updateAndParse) take only
|
||||
// metadata.lock. The two locks do not exclude each other, so a writer that is
|
||||
// past its read and holding metadata.lock can persist .metadata.bin AFTER the
|
||||
// delete has purged the prefix, resurrecting a record for a deleted bucket.
|
||||
// Before the fix, erasureServerPools.DeleteBucket took only <bucket>.lck and
|
||||
// purged the metadata prefix while config writers (updateAndParse) took only
|
||||
// metadata.lock, so a writer already MID-SAVE (holding metadata.lock, past
|
||||
// saveMetadata's existence recheck) could persist .metadata.bin after the purge.
|
||||
// DeleteBucket now takes metadata.lock before deleting, so it waits for that
|
||||
// writer and then purges whatever the writer wrote.
|
||||
//
|
||||
// This test isolates the DeleteBucket-lock fix specifically: the writer holds
|
||||
// metadata.lock and is paused at the .metadata.bin PutObject, so the earlier
|
||||
// saveMetadata existence recheck cannot save it — only serializing the delete
|
||||
// behind the writer can. Removing just DeleteBucket's metadata.lock (keeping the
|
||||
// recheck) therefore makes this test fail. The delete's ACTUAL metadata.lock
|
||||
// attempt is observed with lockBucketMetadataAcquireHook (its lock is taken
|
||||
// through the erasureServerPools receiver, invisible to the object-layer
|
||||
// barrier), so the handshake is deterministic with no timing assumption.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
func TestDeleteBucketResurrectsGhostMetadata(t *testing.T) {
|
||||
@@ -185,6 +193,8 @@ func testDeleteBucketResurrectsGhostMetadata(obj ObjectLayer, instanceType, buck
|
||||
_ http.Handler, _ auth.Credentials, t *testing.T,
|
||||
) {
|
||||
previousObjectAPI := newObjectLayerFn()
|
||||
// Writer A holds metadata.lock and pauses at the .metadata.bin PutObject,
|
||||
// i.e. already past saveMetadata's existence recheck and mid-save.
|
||||
barrier := &metadataRMWBarrierObjectLayer{
|
||||
ObjectLayer: obj,
|
||||
bucket: bucket,
|
||||
@@ -200,8 +210,9 @@ func testDeleteBucketResurrectsGhostMetadata(obj ObjectLayer, instanceType, buck
|
||||
aCtx := context.WithValue(ctx, metadataRMWWriterKey{}, "A")
|
||||
|
||||
policyJSON := []byte(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":"*","Action":"s3:GetObject","Resource":"arn:aws:s3:::` + bucket + `/*"}]}`)
|
||||
aReleased := sync.OnceFunc(func() { close(barrier.aRelease) })
|
||||
defer aReleased()
|
||||
aDone := make(chan error, 1)
|
||||
// Writer A holds metadata.lock and pauses at the .metadata.bin PutObject.
|
||||
go func() {
|
||||
_, err := globalBucketMetadataSys.Update(aCtx, bucket, bucketPolicyConfig, policyJSON)
|
||||
aDone <- err
|
||||
@@ -215,33 +226,46 @@ func testDeleteBucketResurrectsGhostMetadata(obj ObjectLayer, instanceType, buck
|
||||
t.Fatalf("%s: writer A never reached metadata save: %v", instanceType, ctx.Err())
|
||||
}
|
||||
|
||||
// Delete the bucket while writer A is paused mid-save.
|
||||
// A now holds metadata.lock mid-save. Observe DeleteBucket's ACTUAL
|
||||
// metadata.lock attempt via the acquire hook, set only now so A's earlier
|
||||
// acquisition does not trip it.
|
||||
delAtLock := make(chan struct{})
|
||||
var once sync.Once
|
||||
hook := func(b string) {
|
||||
if b == bucket {
|
||||
once.Do(func() { close(delAtLock) })
|
||||
}
|
||||
}
|
||||
lockBucketMetadataAcquireHook.Store(&hook)
|
||||
defer lockBucketMetadataAcquireHook.Store(nil)
|
||||
|
||||
delDone := make(chan error, 1)
|
||||
go func() {
|
||||
delDone <- obj.DeleteBucket(ctx, bucket, DeleteBucketOptions{Force: true})
|
||||
}()
|
||||
|
||||
select {
|
||||
case err := <-delDone:
|
||||
// Unfixed path: DeleteBucket does not serialize on metadata.lock, so it
|
||||
// purges the prefix immediately. Release A so its save recreates the file.
|
||||
if err != nil {
|
||||
t.Fatalf("%s: delete bucket: %v", instanceType, err)
|
||||
}
|
||||
close(barrier.aRelease)
|
||||
case <-delAtLock:
|
||||
// Fixed tree: DeleteBucket reached metadata.lock and blocks on A. Release
|
||||
// A so it finishes its save and unlocks; the delete then acquires the
|
||||
// lock and purges the record A wrote.
|
||||
aReleased()
|
||||
if err := <-aDone; err != nil {
|
||||
t.Fatalf("%s: writer A failed: %v", instanceType, err)
|
||||
}
|
||||
case <-time.After(3 * time.Second):
|
||||
// Fixed path: DeleteBucket is blocked waiting for metadata.lock held by
|
||||
// A. Release A so it finishes, then the purge runs after the save.
|
||||
close(barrier.aRelease)
|
||||
if err := <-aDone; err != nil {
|
||||
t.Fatalf("%s: writer A failed: %v", instanceType, err)
|
||||
t.Fatalf("%s: writer A save failed while holding metadata.lock: %v", instanceType, err)
|
||||
}
|
||||
if err := <-delDone; err != nil {
|
||||
t.Fatalf("%s: delete bucket: %v", instanceType, err)
|
||||
}
|
||||
case err := <-delDone:
|
||||
// Broken tree: DeleteBucket purged without taking metadata.lock. Release
|
||||
// A so its mid-save PutObject recreates .metadata.bin (the ghost).
|
||||
if err != nil {
|
||||
t.Fatalf("%s: delete bucket: %v", instanceType, err)
|
||||
}
|
||||
aReleased()
|
||||
if err := <-aDone; err != nil {
|
||||
t.Fatalf("%s: writer A save failed: %v", instanceType, err)
|
||||
}
|
||||
}
|
||||
|
||||
// After DeleteBucket, no .metadata.bin record may remain on disk.
|
||||
@@ -252,157 +276,3 @@ func testDeleteBucketResurrectsGhostMetadata(obj ObjectLayer, instanceType, buck
|
||||
t.Fatalf("%s: unexpected error reading deleted bucket metadata: %v", instanceType, err)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------------------
|
||||
// Target 3 (issue #105): overlapping peer reloads publishing an older cache
|
||||
// record after a newer save, leaving the resident cache one revision behind
|
||||
// until refresh.
|
||||
//
|
||||
// LoadBucketMetadataHandler does loadBucketMetadata (read) followed by a publish
|
||||
// into the resident cache. Before the fix that publish was an unconditional
|
||||
// BucketMetadataSys.Set, so a reload that read an older on-disk revision could
|
||||
// overwrite a newer resident record when it published late (unlike
|
||||
// refreshBucketsMetadataLoop, which guards on lastUpdate()). The publish is now
|
||||
// BucketMetadataSys.setReloaded, which refuses to regress a newer resident copy.
|
||||
//
|
||||
// The peer handler hardcodes context.Background(), so its reload core is mirrored
|
||||
// here to inject deterministic ordering. This is a resident-cache freshness
|
||||
// defect only: the persisted record always stays correct.
|
||||
// ---------------------------------------------------------------------------
|
||||
|
||||
type reloadWriterKey struct{}
|
||||
|
||||
// reloadStaleBarrier captures the old on-disk metadata for the reload tagged
|
||||
// "R1" and holds R1's read open until released, so a newer revision can be
|
||||
// written and published before R1 finishes publishing the stale copy.
|
||||
type reloadStaleBarrier struct {
|
||||
ObjectLayer
|
||||
bucket string
|
||||
r1Reading chan struct{}
|
||||
r1Release chan struct{}
|
||||
once sync.Once
|
||||
}
|
||||
|
||||
func (o *reloadStaleBarrier) metadataObject() string {
|
||||
return pathJoin(bucketMetaPrefix, o.bucket, bucketMetadataFile)
|
||||
}
|
||||
|
||||
func (o *reloadStaleBarrier) GetObjectNInfo(ctx context.Context, bucket, object string, rs *HTTPRangeSpec, h http.Header, opts ObjectOptions) (*GetObjectReader, error) {
|
||||
if bucket == minioMetaBucket && object == o.metadataObject() && ctx.Value(reloadWriterKey{}) == "R1" {
|
||||
gr, err := o.ObjectLayer.GetObjectNInfo(ctx, bucket, object, rs, h, opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
data, rerr := io.ReadAll(gr)
|
||||
oi := gr.ObjInfo
|
||||
gr.Close()
|
||||
if rerr != nil {
|
||||
return nil, rerr
|
||||
}
|
||||
o.once.Do(func() { close(o.r1Reading) })
|
||||
select {
|
||||
case <-o.r1Release:
|
||||
case <-ctx.Done():
|
||||
return nil, ctx.Err()
|
||||
}
|
||||
return NewGetObjectReaderFromReader(bytes.NewReader(data), oi, opts)
|
||||
}
|
||||
return o.ObjectLayer.GetObjectNInfo(ctx, bucket, object, rs, h, opts)
|
||||
}
|
||||
|
||||
func TestOverlappingReloadPublishesStaleResidentCache(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testOverlappingReloadPublishesStaleResidentCache,
|
||||
})
|
||||
}
|
||||
|
||||
func residentTagValue(t *testing.T, instanceType, bucket string) string {
|
||||
t.Helper()
|
||||
cfg, _, err := globalBucketMetadataSys.GetTaggingConfig(bucket)
|
||||
if err != nil {
|
||||
t.Fatalf("%s: read resident tagging: %v", instanceType, err)
|
||||
}
|
||||
return cfg.ToMap()["rev"]
|
||||
}
|
||||
|
||||
func testOverlappingReloadPublishesStaleResidentCache(obj ObjectLayer, instanceType, bucket string,
|
||||
_ http.Handler, _ auth.Credentials, t *testing.T,
|
||||
) {
|
||||
// Revision 0 on disk and in the resident cache.
|
||||
tag0 := []byte(`<Tagging><TagSet><Tag><Key>rev</Key><Value>0</Value></Tag></TagSet></Tagging>`)
|
||||
if _, err := globalBucketMetadataSys.Update(t.Context(), bucket, bucketTaggingConfig, tag0); err != nil {
|
||||
t.Fatalf("%s: seed rev0: %v", instanceType, err)
|
||||
}
|
||||
|
||||
previousObjectAPI := newObjectLayerFn()
|
||||
barrier := &reloadStaleBarrier{
|
||||
ObjectLayer: obj,
|
||||
bucket: bucket,
|
||||
r1Reading: make(chan struct{}),
|
||||
r1Release: make(chan struct{}),
|
||||
}
|
||||
setObjectLayer(barrier)
|
||||
defer setObjectLayer(previousObjectAPI)
|
||||
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 30*time.Second)
|
||||
defer cancel()
|
||||
r1Ctx := context.WithValue(ctx, reloadWriterKey{}, "R1")
|
||||
|
||||
// reload mirrors the core of LoadBucketMetadataHandler (which hardcodes
|
||||
// context.Background() and cannot take an injected context). The publish
|
||||
// uses setReloaded, exactly as the fixed handler does.
|
||||
reload := func(rctx context.Context) error {
|
||||
meta, err := loadBucketMetadata(rctx, newObjectLayerFn(), bucket)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
globalBucketMetadataSys.setReloaded(bucket, meta)
|
||||
return nil
|
||||
}
|
||||
|
||||
// R1: an overlapping peer reload that reads rev0 and then stalls before it
|
||||
// publishes.
|
||||
r1Done := make(chan error, 1)
|
||||
go func() { r1Done <- reload(r1Ctx) }()
|
||||
|
||||
select {
|
||||
case <-barrier.r1Reading:
|
||||
case err := <-r1Done:
|
||||
t.Fatalf("%s: R1 finished before publishing: %v", instanceType, err)
|
||||
case <-ctx.Done():
|
||||
t.Fatalf("%s: R1 never read metadata: %v", instanceType, ctx.Err())
|
||||
}
|
||||
|
||||
// A newer save commits revision 1 to disk and the resident cache.
|
||||
tag1 := []byte(`<Tagging><TagSet><Tag><Key>rev</Key><Value>1</Value></Tag></TagSet></Tagging>`)
|
||||
if _, err := globalBucketMetadataSys.Update(ctx, bucket, bucketTaggingConfig, tag1); err != nil {
|
||||
t.Fatalf("%s: commit rev1: %v", instanceType, err)
|
||||
}
|
||||
// R2: a second overlapping peer reload that reads rev1 and publishes it.
|
||||
if err := reload(ctx); err != nil {
|
||||
t.Fatalf("%s: R2 reload: %v", instanceType, err)
|
||||
}
|
||||
if got := residentTagValue(t, instanceType, bucket); got != "1" {
|
||||
t.Fatalf("%s: precondition failed, resident cache should be rev1 before R1 publishes, got %q", instanceType, got)
|
||||
}
|
||||
|
||||
// Release R1 so its stale publish lands after the newer save.
|
||||
close(barrier.r1Release)
|
||||
if err := <-r1Done; err != nil {
|
||||
t.Fatalf("%s: R1 reload: %v", instanceType, err)
|
||||
}
|
||||
|
||||
// The persisted record must stay at rev1 (persistent correctness).
|
||||
if dcfg, perr := globalBucketMetadataSys.GetConfigFromDisk(ctx, bucket); perr != nil {
|
||||
t.Fatalf("%s: reload disk metadata: %v", instanceType, perr)
|
||||
} else if got := dcfg.taggingConfig.ToMap()["rev"]; got != "1" {
|
||||
t.Fatalf("%s: persisted record regressed to rev %q, want rev1", instanceType, got)
|
||||
}
|
||||
|
||||
// The resident cache must not be left behind at rev0.
|
||||
if got := residentTagValue(t, instanceType, bucket); got != "1" {
|
||||
t.Fatalf("%s: overlapping reload left resident cache at rev %q, want rev1", instanceType, got)
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,54 @@
|
||||
// Copyright 2026 PGSTY contributors.
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio/internal/auth"
|
||||
"github.com/minio/minio/internal/grid"
|
||||
)
|
||||
|
||||
func TestPeerMetadataReloadWithEqualMaximumTimestamp(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{t: t, objAPITest: testPeerMetadataReloadWithEqualMaximumTimestamp})
|
||||
}
|
||||
|
||||
func testPeerMetadataReloadWithEqualMaximumTimestamp(obj ObjectLayer, instanceType, bucket string, _ http.Handler, _ auth.Credentials, t *testing.T) {
|
||||
disk, err := loadBucketMetadata(t.Context(), obj, bucket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
disk.TaggingConfigXML = []byte(`<Tagging><TagSet><Tag><Key>revision</Key><Value>new</Value></Tag></TagSet></Tagging>`)
|
||||
disk.TaggingConfigUpdatedAt = UTCNow()
|
||||
// An unrelated configuration has the greatest timestamp in both records.
|
||||
disk.PolicyConfigUpdatedAt = disk.TaggingConfigUpdatedAt.Add(time.Hour)
|
||||
if err := disk.Save(t.Context(), obj); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resident := disk
|
||||
resident.TaggingConfigXML = []byte(`<Tagging><TagSet><Tag><Key>revision</Key><Value>old</Value></Tag></TagSet></Tagging>`)
|
||||
resident.TaggingConfigUpdatedAt = disk.TaggingConfigUpdatedAt.Add(-time.Minute)
|
||||
if err := resident.parseAllConfigs(t.Context(), obj); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !resident.lastUpdate().Equal(disk.lastUpdate()) {
|
||||
t.Fatal("fixture must have equal maximum timestamps")
|
||||
}
|
||||
globalBucketMetadataSys.Set(bucket, resident)
|
||||
|
||||
args := grid.MSS{peerRESTBucket: bucket}
|
||||
if _, err := (&peerRESTServer{}).LoadBucketMetadataHandler(&args); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tagging, _, err := globalBucketMetadataSys.GetTaggingConfig(bucket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := tagging.ToMap()["revision"]; got != "new" {
|
||||
t.Errorf("%s: peer reload retained tag %q despite a newer tagging configuration", instanceType, got)
|
||||
}
|
||||
}
|
||||
+28
-36
@@ -24,6 +24,7 @@ import (
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"sync"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"github.com/minio/madmin-go/v3"
|
||||
@@ -125,34 +126,6 @@ func (sys *BucketMetadataSys) Set(bucket string, meta BucketMetadata) {
|
||||
}
|
||||
}
|
||||
|
||||
// setReloaded publishes the newest known revision and its derived registries
|
||||
// together. An old reload may finish after a local save or another reload;
|
||||
// applying its notification/replication targets would regress live behavior
|
||||
// even if the metadata cache itself rejected that old revision.
|
||||
func (sys *BucketMetadataSys) setReloaded(bucket string, meta BucketMetadata) {
|
||||
if isMinioMetaBucketName(bucket) {
|
||||
return
|
||||
}
|
||||
sys.Lock()
|
||||
defer sys.Unlock()
|
||||
if cur, ok := sys.metadataMap[bucket]; ok && !cur.lastUpdate().Before(meta.lastUpdate()) {
|
||||
meta = cur
|
||||
} else {
|
||||
sys.metadataMap[bucket] = meta
|
||||
}
|
||||
sys.clearLoadFailure(bucket)
|
||||
// These registry updates only change local state; no peer/network I/O runs
|
||||
// under the metadata mutex. Keep publication ordered against Set/Remove.
|
||||
if globalEventNotifier != nil {
|
||||
if meta.notificationConfig != nil {
|
||||
globalEventNotifier.AddRulesMap(bucket, meta.notificationConfig.ToRulesMap())
|
||||
} else {
|
||||
globalEventNotifier.RemoveNotification(bucket)
|
||||
}
|
||||
}
|
||||
globalBucketTargetSys.UpdateAllTargets(bucket, meta.bucketTargetConfig)
|
||||
}
|
||||
|
||||
func (sys *BucketMetadataSys) updateAndParse(ctx context.Context, bucket string, configFile string, configData []byte, parse, lifecycleDelete bool) (updatedAt time.Time, err error) {
|
||||
objAPI := newObjectLayerFn()
|
||||
if objAPI == nil {
|
||||
@@ -273,8 +246,19 @@ func lockBucketMetadata(ctx context.Context, objectAPI ObjectLayer, bucket strin
|
||||
return lockBucketMetadataWithTimeout(ctx, objectAPI, bucket, globalOperationTimeout)
|
||||
}
|
||||
|
||||
// lockBucketMetadataAcquireHook, when set, is invoked at the start of every
|
||||
// metadata.lock acquisition, immediately before the blocking Lock() call. It is
|
||||
// nil in production (a single atomic load, no behavior change) and exists only
|
||||
// so tests can deterministically observe a caller reaching the metadata lock —
|
||||
// notably DeleteBucket, whose lock is taken through its erasureServerPools
|
||||
// receiver and is therefore invisible to an injected object layer.
|
||||
var lockBucketMetadataAcquireHook atomic.Pointer[func(bucket string)]
|
||||
|
||||
func lockBucketMetadataWithTimeout(ctx context.Context, objectAPI ObjectLayer, bucket string, timeout *dynamicTimeout) (context.Context, func(), error) {
|
||||
lock := objectAPI.NewNSLock(minioMetaBucket, pathJoin(bucketMetaPrefix, bucket, "metadata.lock"))
|
||||
if hook := lockBucketMetadataAcquireHook.Load(); hook != nil {
|
||||
(*hook)(bucket)
|
||||
}
|
||||
lkctx, err := lock.GetLock(ctx, timeout)
|
||||
if err != nil {
|
||||
return nil, nil, err
|
||||
@@ -686,13 +670,7 @@ func (sys *BucketMetadataSys) GetConfig(ctx context.Context, bucket string) (met
|
||||
return meta, false, err
|
||||
}
|
||||
sys.Lock()
|
||||
if cur, ok := sys.metadataMap[bucket]; ok && !cur.lastUpdate().Before(meta.lastUpdate()) {
|
||||
// A concurrent publish installed a resident revision at least as new as
|
||||
// this cache-miss load; return it instead of regressing (issue #105).
|
||||
meta = cur
|
||||
} else {
|
||||
sys.metadataMap[bucket] = meta
|
||||
}
|
||||
sys.metadataMap[bucket] = meta
|
||||
sys.clearLoadFailure(bucket)
|
||||
sys.Unlock()
|
||||
|
||||
@@ -793,6 +771,8 @@ func (sys *BucketMetadataSys) refreshBucketsMetadataLoop(ctx context.Context) {
|
||||
wait := sleeper.Timer(ctx)
|
||||
|
||||
bucket := buckets[i].Name
|
||||
updated := false
|
||||
|
||||
meta, err := loadBucketMetadata(ctx, sys.objAPI, bucket)
|
||||
if err != nil {
|
||||
internalLogIf(ctx, err, logger.WarningKind)
|
||||
@@ -803,7 +783,19 @@ func (sys *BucketMetadataSys) refreshBucketsMetadataLoop(ctx context.Context) {
|
||||
continue
|
||||
}
|
||||
|
||||
sys.setReloaded(bucket, meta)
|
||||
sys.Lock()
|
||||
// Update if the bucket metadata in the memory is older than on-disk one
|
||||
if lu := sys.metadataMap[bucket].lastUpdate(); lu.Before(meta.lastUpdate()) {
|
||||
updated = true
|
||||
sys.metadataMap[bucket] = meta
|
||||
}
|
||||
sys.clearLoadFailure(bucket)
|
||||
sys.Unlock()
|
||||
|
||||
if updated {
|
||||
globalEventNotifier.set(bucket, meta)
|
||||
globalBucketTargetSys.set(bucket, meta)
|
||||
}
|
||||
|
||||
wait() // wait to proceed to next entry.
|
||||
}
|
||||
|
||||
@@ -334,11 +334,10 @@ func checkPutObjectLockAllowed(ctx context.Context, rq *http.Request, bucket, ob
|
||||
return mode, retainDate, legalHold, ErrObjectLocked
|
||||
}
|
||||
|
||||
if !legalHoldRequested && retentionCfg.LockEnabled {
|
||||
// inherit retention from bucket configuration
|
||||
return retentionCfg.Mode, objectlock.RetentionDate{Time: t.Add(retentionCfg.Validity)}, legalHold, ErrNone
|
||||
}
|
||||
return "", objectlock.RetentionDate{}, legalHold, ErrNone
|
||||
// Inherit retention from the bucket configuration. A legal-hold header
|
||||
// on the same request, ON or OFF, is independent of retention and must
|
||||
// not suppress the default (#165).
|
||||
return retentionCfg.Mode, objectlock.RetentionDate{Time: t.Add(retentionCfg.Validity)}, legalHold, ErrNone
|
||||
}
|
||||
return mode, retainDate, legalHold, ErrNone
|
||||
}
|
||||
|
||||
+26
-7
@@ -255,13 +255,32 @@ func getConditionValuesWithTags(r *http.Request, lc string, cred auth.Credential
|
||||
}
|
||||
|
||||
cloneHeader := r.Header.Clone()
|
||||
signatureAge := cloneHeader.Get("x-amz-signature-age")
|
||||
cloneHeader.Del("x-amz-signature-age")
|
||||
// The presigned V4 verifier overwrites this internal scratch header after
|
||||
// validating the signature. Ignore a value supplied on every other request
|
||||
// type, where it would otherwise synthesize s3:signatureAge.
|
||||
if authType == authTypePresigned && signatureAge != "" {
|
||||
args["signatureAge"] = []string{signatureAge}
|
||||
|
||||
// s3:signatureAge is derived from the presigned X-Amz-Date rather than from
|
||||
// anything the verifier writes back: PutObject and UploadPart authorize
|
||||
// before they verify the signature, so a post-verification value is not yet
|
||||
// available on the first evaluation. The date is bound by the signature
|
||||
// (doesPresignedSignatureMatch rebuilds and compares it), so a forged date
|
||||
// only changes the authorization outcome of a request that then fails
|
||||
// verification. A date that does not parse leaves the key absent; the
|
||||
// verifier rejects the request as ErrMalformedPresignedDate.
|
||||
if authType == authTypePresigned {
|
||||
if signedDate, err := time.Parse(iso8601Format, r.Form.Get(xhttp.AmzDate)); err == nil {
|
||||
args["signatureAge"] = []string{strconv.FormatInt(currTime.Sub(signedDate).Milliseconds(), 10)}
|
||||
}
|
||||
}
|
||||
|
||||
// s3:x-amz-content-sha256 must name the payload hash the request is actually
|
||||
// verified and enforced against, and only one such value. Presence of the
|
||||
// header controls whether the key exists at all (AWS documents that the
|
||||
// query-string form does not populate it), but the value comes from the same
|
||||
// selection getContentSha256Cksum makes for verification: the presigned query
|
||||
// value takes precedence over the header, and a repeated header contributes
|
||||
// only its first value. Exposing every raw header value instead let a
|
||||
// request satisfy a policy with a value the verifier never checked.
|
||||
if _, ok := cloneHeader[xhttp.AmzContentSha256]; ok {
|
||||
args[xhttp.AmzContentSha256] = []string{getContentSha256Cksum(r, serviceS3)}
|
||||
cloneHeader.Del(xhttp.AmzContentSha256)
|
||||
}
|
||||
|
||||
userTags := cloneHeader.Get(xhttp.AmzObjectTagging)
|
||||
|
||||
@@ -23,8 +23,10 @@ import (
|
||||
"net/url"
|
||||
"os"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio/internal/auth"
|
||||
"github.com/minio/minio/internal/handlers"
|
||||
@@ -579,8 +581,20 @@ func TestGetConditionValuesRejectsAbsentInternalKeys(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// s3:signatureAge is derived from the presigned X-Amz-Date, which the signature
|
||||
// binds. A client header under the former scratch name must never supply it on
|
||||
// any auth type, and a presign whose date is missing or malformed leaves the
|
||||
// key absent (the verifier then rejects the request).
|
||||
func TestGetConditionValuesOnlyAcceptsPresignedSignatureAge(t *testing.T) {
|
||||
const signatureAgeHeader = "x-amz-signature-age"
|
||||
signedDate := UTCNow().Add(-90 * time.Second)
|
||||
presignQuery := func(date string) string {
|
||||
q := url.Values{xhttp.AmzCredential: {"access/20260803/us-east-1/s3/aws4_request"}}
|
||||
if date != "" {
|
||||
q.Set(xhttp.AmzDate, date)
|
||||
}
|
||||
return "http://minio.local/bkt/obj?" + q.Encode()
|
||||
}
|
||||
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
@@ -602,19 +616,33 @@ func TestGetConditionValuesOnlyAcceptsPresignedSignatureAge(t *testing.T) {
|
||||
},
|
||||
},
|
||||
{
|
||||
name: "presigned verifier value",
|
||||
target: "http://minio.local/bkt/obj?" + url.Values{
|
||||
xhttp.AmzCredential: {"access/20260803/us-east-1/s3/aws4_request"},
|
||||
}.Encode(),
|
||||
name: "presigned client header without date",
|
||||
target: presignQuery(""),
|
||||
headers: map[string]string{signatureAgeHeader: "250"},
|
||||
},
|
||||
{
|
||||
name: "presigned malformed date",
|
||||
target: presignQuery("yesterday"),
|
||||
},
|
||||
{
|
||||
name: "presigned signed date",
|
||||
target: presignQuery(signedDate.Format(iso8601Format)),
|
||||
headers: map[string]string{signatureAgeHeader: "250"},
|
||||
want: true,
|
||||
},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
got := condValuesForRequest(t, tc.target, tc.headers)
|
||||
_, ok := got["signatureAge"]
|
||||
v, ok := got["signatureAge"]
|
||||
if ok != tc.want {
|
||||
t.Fatalf("signatureAge presence: expected %v, got %v", tc.want, got["signatureAge"])
|
||||
t.Fatalf("signatureAge presence: expected %v, got %v", tc.want, v)
|
||||
}
|
||||
if !tc.want {
|
||||
return
|
||||
}
|
||||
age, err := strconv.ParseInt(strings.Join(v, ""), 10, 64)
|
||||
if err != nil || age < (90*time.Second).Milliseconds() || age > (2*time.Minute).Milliseconds() {
|
||||
t.Fatalf("signatureAge = %v, want about 90s derived from X-Amz-Date rather than the client header", v)
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
@@ -1068,6 +1068,11 @@ func (er erasureObjects) HealObject(ctx context.Context, bucket, object, version
|
||||
newReqInfo = logger.NewReqInfo("", "", globalDeploymentID(), "", "Heal", bucket, object)
|
||||
}
|
||||
healCtx := logger.SetReqInfo(GlobalContext, newReqInfo)
|
||||
if opts.NoLock {
|
||||
// The caller owns the namespace lock. Stop if that lock's context is
|
||||
// canceled instead of continuing metadata writes after losing it.
|
||||
healCtx = logger.SetReqInfo(ctx, newReqInfo)
|
||||
}
|
||||
|
||||
// Healing directories handle it separately.
|
||||
if HasSuffix(object, SlashSeparator) {
|
||||
|
||||
@@ -157,6 +157,13 @@ func copyPartWithoutChecksumHTTP(t *testing.T, apiRouter http.Handler, creds aut
|
||||
if sourceRange != "" {
|
||||
req.Header.Set(xhttp.AmzCopySourceRange, sourceRange)
|
||||
}
|
||||
// Re-sign so the copy-source x-amz-* headers are covered by the signature,
|
||||
// as real S3 clients send them; the verifier rejects unsigned x-amz-*.
|
||||
if creds.AccessKey != "" && creds.SecretKey != "" {
|
||||
if err := signRequestV4(req, creds.AccessKey, creds.SecretKey); err != nil {
|
||||
t.Fatalf("failed to re-sign UploadPartCopy request: %v", err)
|
||||
}
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
|
||||
+10
-12
@@ -1155,17 +1155,10 @@ func (er erasureObjects) CompleteMultipartUpload(ctx context.Context, bucket str
|
||||
return oi, toObjectErr(err, bucket, object, uploadID)
|
||||
}
|
||||
|
||||
// A trusted SSE-C replica completion re-orders the Object Lock carried in the
|
||||
// upload metadata against the version it is about to replace, read on this
|
||||
// erasure set under the write lock held above, so a hold or retention that
|
||||
// reached the version after this upload was initiated is not rolled back at
|
||||
// completion (issue #120). Scoped to SSE-C uploads, the only ones this issue
|
||||
// routes through completion.
|
||||
//
|
||||
// Scope: correct for a single erasure set. A multi-pool deployment (duplicate
|
||||
// versions across pools, ModTime ties, cross-pool lock authority) is out of
|
||||
// scope and tracked in pgsty/silo#133.
|
||||
if opts.ReplicaLockReconcile && crypto.SSEC.IsEncrypted(fi.Metadata) {
|
||||
// Reconcile against the upload's persisted version, under the object lock.
|
||||
// Multi-pool callers supply a resolver spanning all pools, including those
|
||||
// draining their contents; the upload itself stays in its original pool.
|
||||
if opts.ReplicaLockReconcile {
|
||||
// A persisted upload records the null version as an empty VersionID; look
|
||||
// it up as the null version so the reconcile reads the addressed version's
|
||||
// stored lock, not the latest version's.
|
||||
@@ -1173,7 +1166,11 @@ func (er erasureObjects) CompleteMultipartUpload(ctx context.Context, bucket str
|
||||
if lookupVersionID == "" {
|
||||
lookupVersionID = nullVersionID
|
||||
}
|
||||
curr, gerr := er.getObjectInfo(ctx, bucket, object, ObjectOptions{
|
||||
getObjectInfo := er.getObjectInfo
|
||||
if opts.replicaObjectInfo != nil {
|
||||
getObjectInfo = opts.replicaObjectInfo
|
||||
}
|
||||
curr, gerr := getObjectInfo(ctx, bucket, object, ObjectOptions{
|
||||
VersionID: lookupVersionID,
|
||||
Versioned: opts.Versioned,
|
||||
VersionSuspended: opts.VersionSuspended,
|
||||
@@ -1182,6 +1179,7 @@ func (er erasureObjects) CompleteMultipartUpload(ctx context.Context, bucket str
|
||||
switch {
|
||||
case gerr == nil:
|
||||
reconcileStoredObjectLock(fi.Metadata, storedObjectLockState(curr.UserDefined))
|
||||
reconcileStoredObjectTags(fi.Metadata, curr.UserDefined)
|
||||
case isErrVersionNotFound(gerr) || isErrObjectNotFound(gerr):
|
||||
// No existing version to order against: keep the upload's own accepted
|
||||
// lock, including a pre-upgrade upload that persisted values without
|
||||
|
||||
+14
-10
@@ -133,6 +133,11 @@ func (er erasureObjects) CopyObject(ctx context.Context, srcBucket, srcObject, d
|
||||
return fi.ToObjectInfo(srcBucket, srcObject, srcOpts.Versioned || srcOpts.VersionSuspended), toObjectErr(errMethodNotAllowed, srcBucket, srcObject)
|
||||
}
|
||||
|
||||
if dstOpts.ReplicaLockReconcile {
|
||||
reconcileStoredObjectLock(srcInfo.UserDefined, storedObjectLockState(fi.Metadata))
|
||||
reconcileStoredObjectTags(srcInfo.UserDefined, fi.Metadata)
|
||||
}
|
||||
|
||||
filterOnlineDisksInplace(fi, metaArr, onlineDisks)
|
||||
|
||||
versionID := srcInfo.VersionID
|
||||
@@ -1280,7 +1285,11 @@ func (er erasureObjects) putObject(ctx context.Context, bucket string, object st
|
||||
opts.NoLock = true
|
||||
}
|
||||
|
||||
obj, err := er.getObjectInfo(ctx, bucket, object, opts)
|
||||
getObjectInfo := er.getObjectInfo
|
||||
if opts.replicaObjectInfo != nil {
|
||||
getObjectInfo = opts.replicaObjectInfo
|
||||
}
|
||||
obj, err := getObjectInfo(ctx, bucket, object, opts)
|
||||
// A destination read that fails for a reason other than not-found must not
|
||||
// be taken as a passed precondition or as absent lock state.
|
||||
if err != nil && !isErrVersionNotFound(err) && !isErrObjectNotFound(err) {
|
||||
@@ -1297,17 +1306,12 @@ func (er erasureObjects) putObject(ctx context.Context, bucket string, object st
|
||||
}
|
||||
}
|
||||
|
||||
// Order this trusted SSE-C replica's Object Lock against the addressed
|
||||
// version's stored state, read on this erasure set under the write lock,
|
||||
// so a value that lost the ordering cannot overwrite a newer one committed
|
||||
// after the handler decided (issue #120). Only reconcile against an
|
||||
// existing version; on not-found the write's own accepted lock is kept.
|
||||
//
|
||||
// Scope: correct for a single erasure set. A multi-pool deployment
|
||||
// (duplicate versions across pools, ModTime ties, cross-pool lock
|
||||
// authority) is out of scope and tracked in pgsty/silo#133.
|
||||
// Re-read under the write lock, using the pools-layer resolver when
|
||||
// present. A missing version keeps the incoming accepted state; an
|
||||
// existing version contributes independently ordered lock and tags.
|
||||
if opts.ReplicaLockReconcile && err == nil {
|
||||
reconcileStoredObjectLock(opts.UserDefined, storedObjectLockState(obj.UserDefined))
|
||||
reconcileStoredObjectTags(opts.UserDefined, obj.UserDefined)
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,350 @@
|
||||
// Copyright (c) 2026 Feng Ruohang
|
||||
//
|
||||
// This file is part of Silo 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"
|
||||
"maps"
|
||||
"sort"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
madmin "github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/minio/internal/bucket/lifecycle"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
)
|
||||
|
||||
// objectPoolInfos reads the addressed version in every pool, including pools
|
||||
// draining their contents. The caller must hold the pools-layer object lock.
|
||||
// An unreadable pool may contain a newer version or metadata; it is not absence.
|
||||
func (z *erasureServerPools) objectPoolInfos(ctx context.Context, bucket, object string, opts ObjectOptions) ([]PoolObjInfo, error) {
|
||||
opts.NoLock = true
|
||||
opts.CheckPrecondFn = nil
|
||||
var copies []PoolObjInfo
|
||||
for i, pool := range z.serverPools {
|
||||
oi, err := pool.GetObjectInfo(ctx, bucket, object, opts)
|
||||
if err == nil || (oi.DeleteMarker && (isErrObjectNotFound(err) || isErrMethodNotAllowed(err))) {
|
||||
copies = append(copies, PoolObjInfo{Index: i, ObjInfo: oi})
|
||||
continue
|
||||
}
|
||||
if !isErrObjectNotFound(err) && !isErrVersionNotFound(err) {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
sort.Slice(copies, func(i, j int) bool {
|
||||
a, b := copies[i], copies[j]
|
||||
if a.ObjInfo.ModTime.Equal(b.ObjInfo.ModTime) {
|
||||
return a.Index < b.Index
|
||||
}
|
||||
return a.ObjInfo.ModTime.After(b.ObjInfo.ModTime)
|
||||
})
|
||||
if len(copies) == 0 {
|
||||
if opts.VersionID != "" {
|
||||
return nil, VersionNotFound{Bucket: bucket, Object: decodeDirObject(object), VersionID: opts.VersionID}
|
||||
}
|
||||
return nil, ObjectNotFound{Bucket: bucket, Object: decodeDirObject(object)}
|
||||
}
|
||||
return copies, nil
|
||||
}
|
||||
|
||||
// Healing also commits object metadata. Both queued healing and drive healing
|
||||
// must use the same namespace as pooled writes, rather than racing them under
|
||||
// a destination set's independent namespace.
|
||||
func (z *erasureServerPools) healObjectInPool(ctx context.Context, er *erasureObjects, bucket, object, versionID string, opts madmin.HealOpts) (madmin.HealResultItem, error) {
|
||||
if !z.SinglePool() && !opts.NoLock {
|
||||
lk := z.NewNSLock(bucket, object)
|
||||
lkctx, err := lk.GetLock(ctx, globalOperationTimeout)
|
||||
if err != nil {
|
||||
return madmin.HealResultItem{}, err
|
||||
}
|
||||
ctx = lkctx.Context()
|
||||
defer lk.Unlock(lkctx)
|
||||
opts.NoLock = true
|
||||
}
|
||||
return er.HealObject(ctx, bucket, object, versionID, opts)
|
||||
}
|
||||
|
||||
// mergePoolLockState resolves each independently ordered field. An ordered
|
||||
// removal is a value in its own right; an absent unordered field is not one.
|
||||
func mergePoolLockState(copies []PoolObjInfo) objectLockState {
|
||||
state := storedObjectLockState(copies[0].ObjInfo.UserDefined)
|
||||
for _, copy := range copies[1:] {
|
||||
next := storedObjectLockState(copy.ObjInfo.UserDefined)
|
||||
retentionTime, _ := time.Parse(time.RFC3339Nano, next.retentionTimestamp)
|
||||
if state.retentionIsOlderThan(retentionTime) || (state.retentionTimestamp == "" && state.mode == "" && next.mode != "") {
|
||||
state.mode, state.retainUntil, state.retentionTimestamp = next.mode, next.retainUntil, next.retentionTimestamp
|
||||
}
|
||||
holdTime, _ := time.Parse(time.RFC3339Nano, next.legalHoldTimestamp)
|
||||
if state.legalHoldIsOlderThan(holdTime) || (state.legalHoldTimestamp == "" && state.legalHold == "" && next.legalHold != "") {
|
||||
state.legalHold, state.legalHoldTimestamp = next.legalHold, next.legalHoldTimestamp
|
||||
}
|
||||
}
|
||||
return state
|
||||
}
|
||||
|
||||
func replaceObjectLockMetadata(metadata map[string]string, state objectLockState) {
|
||||
for _, key := range []string{
|
||||
strings.ToLower(xhttp.AmzObjectLockMode), strings.ToLower(xhttp.AmzObjectLockRetainUntilDate),
|
||||
strings.ToLower(xhttp.AmzObjectLockLegalHold),
|
||||
ReservedMetadataPrefixLower + ObjectLockRetentionTimestamp,
|
||||
ReservedMetadataPrefixLower + ObjectLockLegalHoldTimestamp,
|
||||
} {
|
||||
// Metadata updates use maps.Copy at the set layer. Empty values also
|
||||
// clear a previous value there, including timestamp-only removals.
|
||||
if _, exists := metadata[key]; exists {
|
||||
metadata[key] = ""
|
||||
}
|
||||
}
|
||||
state.restoreRetention(metadata)
|
||||
state.restoreLegalHold(metadata)
|
||||
}
|
||||
|
||||
func mergedPoolObjectInfo(copies []PoolObjInfo) ObjectInfo {
|
||||
oi := copies[0].ObjInfo
|
||||
oi.UserDefined = maps.Clone(oi.UserDefined)
|
||||
if oi.UserDefined == nil {
|
||||
oi.UserDefined = make(map[string]string)
|
||||
}
|
||||
replaceObjectLockMetadata(oi.UserDefined, mergePoolLockState(copies))
|
||||
for _, copy := range copies[1:] {
|
||||
ts := copy.ObjInfo.UserDefined[ReservedMetadataPrefixLower+TaggingTimestamp]
|
||||
stamp, _ := time.Parse(time.RFC3339Nano, ts)
|
||||
if olderThan(oi.UserDefined[ReservedMetadataPrefixLower+TaggingTimestamp], stamp) {
|
||||
oi.UserDefined[ReservedMetadataPrefixLower+TaggingTimestamp] = ts
|
||||
oi.UserDefined[xhttp.AmzObjectTagging] = copy.ObjInfo.UserDefined[xhttp.AmzObjectTagging]
|
||||
}
|
||||
}
|
||||
oi.UserTags = oi.UserDefined[xhttp.AmzObjectTagging]
|
||||
return oi
|
||||
}
|
||||
|
||||
func (z *erasureServerPools) replicaObjectInfo(ctx context.Context, bucket, object string, opts ObjectOptions) (ObjectInfo, error) {
|
||||
if opts.VersionID == "" {
|
||||
opts.VersionID = nullVersionID
|
||||
}
|
||||
copies, err := z.objectPoolInfos(ctx, bucket, object, opts)
|
||||
if err != nil {
|
||||
return ObjectInfo{}, err
|
||||
}
|
||||
if copies[0].ObjInfo.DeleteMarker {
|
||||
return copies[0].ObjInfo, MethodNotAllowed{Bucket: bucket, Object: decodeDirObject(object), VersionID: opts.VersionID}
|
||||
}
|
||||
return mergedPoolObjectInfo(copies), nil
|
||||
}
|
||||
|
||||
// metadataPoolInfos resolves an unqualified metadata request to one logical
|
||||
// version before collecting its copies, rather than mixing different versions.
|
||||
func (z *erasureServerPools) metadataPoolInfos(ctx context.Context, bucket, object string, opts ObjectOptions) ([]PoolObjInfo, error) {
|
||||
copies, err := z.objectPoolInfos(ctx, bucket, object, opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if copies[0].ObjInfo.DeleteMarker {
|
||||
return nil, MethodNotAllowed{Bucket: bucket, Object: decodeDirObject(object), VersionID: opts.VersionID}
|
||||
}
|
||||
if opts.VersionID == "" {
|
||||
opts.VersionID = copies[0].ObjInfo.VersionID
|
||||
if opts.VersionID == "" {
|
||||
opts.VersionID = nullVersionID
|
||||
}
|
||||
return z.objectPoolInfos(ctx, bucket, object, opts)
|
||||
}
|
||||
return copies, nil
|
||||
}
|
||||
|
||||
func (z *erasureServerPools) updatePoolMetadata(ctx context.Context, bucket, object string, opts ObjectOptions) (ObjectInfo, error) {
|
||||
copies, err := z.metadataPoolInfos(ctx, bucket, object, opts)
|
||||
if err != nil {
|
||||
return ObjectInfo{}, err
|
||||
}
|
||||
updated := mergedPoolObjectInfo(copies)
|
||||
before := maps.Clone(updated.UserDefined)
|
||||
if opts.EvalMetadataFn != nil {
|
||||
if _, err := opts.EvalMetadataFn(&updated, nil); err != nil {
|
||||
return ObjectInfo{}, err
|
||||
}
|
||||
}
|
||||
changes := make(map[string]string)
|
||||
for key, value := range updated.UserDefined {
|
||||
if prior, ok := before[key]; !ok || prior != value {
|
||||
changes[key] = value
|
||||
}
|
||||
}
|
||||
for key := range before {
|
||||
if _, ok := updated.UserDefined[key]; !ok {
|
||||
changes[key] = ""
|
||||
}
|
||||
}
|
||||
state := storedObjectLockState(updated.UserDefined)
|
||||
opts.VersionID = updated.VersionID
|
||||
if opts.VersionID == "" {
|
||||
opts.VersionID = nullVersionID
|
||||
}
|
||||
opts.NoLock = true
|
||||
opts.EvalMetadataFn = func(oi *ObjectInfo, _ error) (ReplicateDecision, error) {
|
||||
maps.Copy(oi.UserDefined, changes)
|
||||
replaceObjectLockMetadata(oi.UserDefined, state)
|
||||
for _, key := range []string{xhttp.AmzObjectTagging, ReservedMetadataPrefixLower + TaggingTimestamp} {
|
||||
value, exists := updated.UserDefined[key]
|
||||
if exists || oi.UserDefined[key] != "" {
|
||||
oi.UserDefined[key] = value
|
||||
}
|
||||
}
|
||||
return ReplicateDecision{}, nil
|
||||
}
|
||||
var primary ObjectInfo
|
||||
for _, copy := range copies {
|
||||
oi, err := z.serverPools[copy.Index].PutObjectMetadata(ctx, bucket, object, opts)
|
||||
if err != nil {
|
||||
return ObjectInfo{}, err
|
||||
}
|
||||
if copy.Index == copies[0].Index {
|
||||
primary = oi
|
||||
}
|
||||
}
|
||||
return primary, nil
|
||||
}
|
||||
|
||||
func reconcileStoredObjectTags(metadata, stored map[string]string) {
|
||||
key := ReservedMetadataPrefixLower + TaggingTimestamp
|
||||
stamp, err := time.Parse(time.RFC3339Nano, stored[key])
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
incoming, err := time.Parse(time.RFC3339Nano, metadata[key])
|
||||
if err != nil || !stamp.Before(incoming) {
|
||||
metadata[key] = stored[key]
|
||||
metadata[xhttp.AmzObjectTagging] = stored[xhttp.AmzObjectTagging]
|
||||
}
|
||||
}
|
||||
|
||||
// A restored version still owns its tier reference even while IsRemote is
|
||||
// false. Only the last copy of a reference may schedule its contents for GC.
|
||||
func sharesTierObject(oi ObjectInfo, copies []PoolObjInfo) bool {
|
||||
ref := oi.TransitionedObject
|
||||
if ref.Status != lifecycle.TransitionComplete {
|
||||
return false
|
||||
}
|
||||
for _, copy := range copies {
|
||||
other := copy.ObjInfo.TransitionedObject
|
||||
if other.Status == lifecycle.TransitionComplete && ref.Tier == other.Tier && ref.Name == other.Name && ref.VersionID == other.VersionID {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// retireReplicaCopies runs only after committing a replacement. Failures are
|
||||
// returned to the caller, so a stale copy cannot be hidden behind a successful
|
||||
// response. Data movement owns its source cleanup and does not use this helper.
|
||||
func (z *erasureServerPools) retireReplicaCopies(ctx context.Context, bucket, object string, keep int, oi ObjectInfo) error {
|
||||
versionID := oi.VersionID
|
||||
if versionID == "" {
|
||||
versionID = nullVersionID
|
||||
}
|
||||
copies, err := z.objectPoolInfos(ctx, bucket, object, ObjectOptions{VersionID: versionID})
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
var retained []PoolObjInfo
|
||||
for _, copy := range copies {
|
||||
if copy.Index == keep {
|
||||
retained = []PoolObjInfo{copy}
|
||||
break
|
||||
}
|
||||
}
|
||||
if len(retained) == 0 {
|
||||
return VersionNotFound{Bucket: bucket, Object: decodeDirObject(object), VersionID: versionID}
|
||||
}
|
||||
for i, copy := range copies {
|
||||
if copy.Index == keep {
|
||||
continue
|
||||
}
|
||||
_, err := z.serverPools[copy.Index].DeleteObject(ctx, bucket, object,
|
||||
ObjectOptions{
|
||||
VersionID: versionID, NoLock: true, NoAuditLog: true,
|
||||
SkipFreeVersion: sharesTierObject(copy.ObjInfo, retained) || sharesTierObject(copy.ObjInfo, copies[i+1:]),
|
||||
})
|
||||
if err != nil && !isErrObjectNotFound(err) && !isErrVersionNotFound(err) {
|
||||
return err
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// deleteObjectConditional evaluates the condition once against the logical
|
||||
// version, then removes all its copies under the same lock as pooled writers.
|
||||
func (z *erasureServerPools) deleteObjectConditional(ctx context.Context, bucket, object string, opts ObjectOptions) (ObjectInfo, error) {
|
||||
copies, err := z.objectPoolInfos(ctx, bucket, object, opts)
|
||||
if err != nil {
|
||||
return ObjectInfo{}, err
|
||||
}
|
||||
primary := copies[0]
|
||||
if opts.CheckPrecondFn(primary.ObjInfo) {
|
||||
return ObjectInfo{}, PreConditionFailed{}
|
||||
}
|
||||
opts.CheckPrecondFn = nil
|
||||
opts.NoLock = true
|
||||
if opts.EvalRetentionBypassFn != nil || opts.EvalMetadataFn != nil {
|
||||
versions, err := z.metadataPoolInfos(ctx, bucket, object, opts)
|
||||
if err != nil {
|
||||
return ObjectInfo{}, err
|
||||
}
|
||||
logical := mergedPoolObjectInfo(versions)
|
||||
if opts.EvalRetentionBypassFn != nil {
|
||||
if err := opts.EvalRetentionBypassFn(logical, nil); err != nil {
|
||||
return ObjectInfo{}, err
|
||||
}
|
||||
opts.EvalRetentionBypassFn = nil
|
||||
}
|
||||
if opts.EvalMetadataFn != nil {
|
||||
decision, err := opts.EvalMetadataFn(&logical, nil)
|
||||
if err != nil {
|
||||
return ObjectInfo{}, err
|
||||
}
|
||||
if decision.ReplicateAny() {
|
||||
opts.SetDeleteReplicationState(decision, opts.VersionID)
|
||||
}
|
||||
opts.EvalMetadataFn = nil
|
||||
}
|
||||
}
|
||||
if opts.VersionID == "" && (opts.Versioned || opts.VersionSuspended) {
|
||||
// A single new delete marker hides the current version. Older versions
|
||||
// remain history and must not be removed by an unqualified DELETE.
|
||||
oi, err := z.serverPools[primary.Index].DeleteObject(ctx, bucket, object, opts)
|
||||
oi.Name = decodeDirObject(object)
|
||||
oi.replicationDecision = opts.DeleteReplication.ReplicateDecisionStr
|
||||
return oi, err
|
||||
}
|
||||
// Retire non-authoritative copies first. If cleanup fails, retain the
|
||||
// authoritative version and report the error instead of acknowledging a
|
||||
// deletion that would expose an older copy.
|
||||
for i := 1; i < len(copies); i++ {
|
||||
candidate := copies[i]
|
||||
deleteOpts := opts
|
||||
deleteOpts.SkipFreeVersion = opts.SkipFreeVersion || sharesTierObject(candidate.ObjInfo, copies[:1]) || sharesTierObject(candidate.ObjInfo, copies[i+1:])
|
||||
_, err := z.serverPools[candidate.Index].DeleteObject(ctx, bucket, object, deleteOpts)
|
||||
if err != nil && !isErrObjectNotFound(err) && !isErrVersionNotFound(err) {
|
||||
return ObjectInfo{}, err
|
||||
}
|
||||
}
|
||||
oi, err := z.serverPools[primary.Index].DeleteObject(ctx, bucket, object, opts)
|
||||
oi.Name = decodeDirObject(object)
|
||||
oi.replicationDecision = opts.DeleteReplication.ReplicateDecisionStr
|
||||
return oi, err
|
||||
}
|
||||
@@ -0,0 +1,682 @@
|
||||
// Copyright (c) 2026 Feng Ruohang
|
||||
//
|
||||
// This file is part of Silo 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"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
madmin "github.com/minio/madmin-go/v3"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
)
|
||||
|
||||
func consistencyPools(t *testing.T) (*erasureServerPools, string) {
|
||||
t.Helper()
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
obj, dirs, err := prepareErasurePoolsWithContext(ctx)
|
||||
if err != nil {
|
||||
cancel()
|
||||
t.Fatal(err)
|
||||
}
|
||||
z := obj.(*erasureServerPools)
|
||||
previous := newObjectLayerFn()
|
||||
setObjectLayer(z)
|
||||
t.Cleanup(func() { cancel(); z.Shutdown(context.Background()); removeRoots(dirs); setObjectLayer(previous) })
|
||||
bucket := "pool-consistency"
|
||||
if err := z.MakeBucket(t.Context(), bucket, MakeBucketOptions{}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return z, bucket
|
||||
}
|
||||
|
||||
func putConsistencyObject(t *testing.T, z *erasureServerPools, bucket, object string, pool int, body string, opts ObjectOptions) ObjectInfo {
|
||||
t.Helper()
|
||||
oi, err := z.serverPools[pool].PutObject(t.Context(), bucket, object,
|
||||
mustGetPutObjReader(t, bytes.NewBufferString(body), int64(len(body)), "", ""), opts)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return oi
|
||||
}
|
||||
|
||||
func TestPoolsConditionalDeleteVersionSelection(t *testing.T) {
|
||||
z, bucket := consistencyPools(t)
|
||||
const object = "split-versions"
|
||||
old := putConsistencyObject(t, z, bucket, object, 1, "old", ObjectOptions{Versioned: true, MTime: time.Now().Add(-time.Hour)})
|
||||
latest := putConsistencyObject(t, z, bucket, object, 0, "latest", ObjectOptions{Versioned: true})
|
||||
_, err := z.DeleteObject(t.Context(), bucket, object, ObjectOptions{
|
||||
Versioned: true, VersionID: old.VersionID, HasIfMatch: true,
|
||||
CheckPrecondFn: func(oi ObjectInfo) bool { return oi.ETag != old.ETag },
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatalf("delete addressed version in pool 1: %v", err)
|
||||
}
|
||||
if _, err := z.GetObjectInfo(t.Context(), bucket, object, ObjectOptions{VersionID: old.VersionID}); !isErrVersionNotFound(err) {
|
||||
t.Errorf("addressed version survived: %v", err)
|
||||
}
|
||||
if oi, err := z.GetObjectInfo(t.Context(), bucket, object, ObjectOptions{}); err != nil || oi.VersionID != latest.VersionID {
|
||||
t.Errorf("delete changed the latest version: %+v, %v", oi, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolsConditionalDeleteDuplicateVersion(t *testing.T) {
|
||||
z, bucket := consistencyPools(t)
|
||||
const object = "duplicate-version"
|
||||
oi := putConsistencyObject(t, z, bucket, object, 0, "payload", ObjectOptions{Versioned: true})
|
||||
putConsistencyObject(t, z, bucket, object, 1, "payload", ObjectOptions{Versioned: true, VersionID: oi.VersionID, MTime: oi.ModTime})
|
||||
_, err := z.DeleteObject(t.Context(), bucket, object, ObjectOptions{
|
||||
Versioned: true, VersionID: oi.VersionID, HasIfMatch: true,
|
||||
CheckPrecondFn: func(current ObjectInfo) bool { return current.ETag != oi.ETag },
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := z.GetObjectInfo(t.Context(), bucket, object, ObjectOptions{VersionID: oi.VersionID}); !isErrVersionNotFound(err) {
|
||||
t.Fatalf("success left a readable duplicate version: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolsConditionalDeleteReportsOtherPoolFailure(t *testing.T) {
|
||||
z, bucket := consistencyPools(t)
|
||||
const object = "delete-failure"
|
||||
putConsistencyObject(t, z, bucket, object, 1, "older", ObjectOptions{MTime: time.Now().Add(-time.Hour)})
|
||||
oi := putConsistencyObject(t, z, bucket, object, 0, "latest", ObjectOptions{})
|
||||
set := z.serverPools[1].getHashedSet(object)
|
||||
getDisks := set.getDisks
|
||||
faulty := append([]StorageAPI(nil), getDisks()...)
|
||||
for i := range faulty {
|
||||
faulty[i] = accessMoveDeleteFaultDisk{StorageAPI: faulty[i], bucket: bucket, object: object}
|
||||
}
|
||||
set.getDisks = func() []StorageAPI { return faulty }
|
||||
defer func() { set.getDisks = getDisks }()
|
||||
_, err := z.DeleteObject(t.Context(), bucket, object, ObjectOptions{
|
||||
HasIfMatch: true, CheckPrecondFn: func(current ObjectInfo) bool { return current.ETag != oi.ETag },
|
||||
})
|
||||
if err == nil {
|
||||
t.Fatal("delete reported success despite the other pool's write failure")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolsConditionalDeleteSerializesPut(t *testing.T) {
|
||||
testPoolsConditionalDeleteWriter(t, false)
|
||||
}
|
||||
|
||||
func TestPoolsConditionalDeleteSerializesCompletion(t *testing.T) {
|
||||
testPoolsConditionalDeleteWriter(t, true)
|
||||
}
|
||||
|
||||
func testPoolsConditionalDeleteWriter(t *testing.T, multipart bool) {
|
||||
z, bucket := consistencyPools(t)
|
||||
const object = "concurrent-put"
|
||||
initial := putConsistencyObject(t, z, bucket, object, 1, "before", ObjectOptions{})
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
|
||||
defer cancel()
|
||||
reader := mustGetPutObjReader(t, bytes.NewBufferString("after"), 5, "", "")
|
||||
destination := 1
|
||||
write := func() error {
|
||||
_, err := z.PutObject(ctx, bucket, object, reader, ObjectOptions{DataMovement: true, SrcPoolIdx: 0, DstPoolIdx: &destination})
|
||||
return err
|
||||
}
|
||||
if multipart {
|
||||
mp, err := z.serverPools[1].NewMultipartUpload(ctx, bucket, object, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
part, err := z.serverPools[1].PutObjectPart(ctx, bucket, object, mp.UploadID, 1, reader, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
write = func() error {
|
||||
_, err := z.CompleteMultipartUpload(ctx, bucket, object, mp.UploadID,
|
||||
[]CompletePart{{PartNumber: 1, ETag: part.ETag}}, ObjectOptions{})
|
||||
return err
|
||||
}
|
||||
}
|
||||
checked, resume := make(chan struct{}), make(chan struct{})
|
||||
var resumeOnce sync.Once
|
||||
release := func() { resumeOnce.Do(func() { close(resume) }) }
|
||||
defer release()
|
||||
deleted := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := z.DeleteObject(ctx, bucket, object, ObjectOptions{
|
||||
HasIfMatch: true,
|
||||
CheckPrecondFn: func(oi ObjectInfo) bool {
|
||||
close(checked)
|
||||
<-resume
|
||||
return oi.ETag != initial.ETag
|
||||
},
|
||||
})
|
||||
deleted <- err
|
||||
}()
|
||||
select {
|
||||
case <-checked:
|
||||
case err := <-deleted:
|
||||
t.Fatalf("delete did not evaluate the precondition: %v", err)
|
||||
case <-ctx.Done():
|
||||
t.Fatal(ctx.Err())
|
||||
}
|
||||
written := make(chan error, 1)
|
||||
go func() { written <- write() }()
|
||||
var early bool
|
||||
select {
|
||||
case err := <-written:
|
||||
early = true
|
||||
if err != nil {
|
||||
t.Errorf("concurrent PUT: %v", err)
|
||||
}
|
||||
case <-time.After(250 * time.Millisecond):
|
||||
}
|
||||
release()
|
||||
if err := <-deleted; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !early {
|
||||
if err := <-written; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
if early {
|
||||
t.Error("PUT committed while DELETE was between its comparison and removal")
|
||||
}
|
||||
if _, err := z.GetObjectInfo(ctx, bucket, object, ObjectOptions{}); err != nil {
|
||||
t.Errorf("matching the old ETag removed the concurrent replacement: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
type consistencyGateReader struct {
|
||||
io.Reader
|
||||
entered, resume chan struct{}
|
||||
once sync.Once
|
||||
release sync.Once
|
||||
}
|
||||
|
||||
func (r *consistencyGateReader) Read(p []byte) (int, error) {
|
||||
r.once.Do(func() { close(r.entered); <-r.resume })
|
||||
return r.Reader.Read(p)
|
||||
}
|
||||
|
||||
func TestPoolsReplicaSerializesMetadataAndHealing(t *testing.T) {
|
||||
for _, heal := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("heal=%t", heal), func(t *testing.T) {
|
||||
z, bucket := consistencyPools(t)
|
||||
const object = "metadata-race"
|
||||
old, recent := "2026-09-09T09:00:00Z", "2026-09-09T10:00:00Z"
|
||||
meta := poolLockMetadata("GOVERNANCE", "OFF", old, old)
|
||||
oi := putConsistencyObject(t, z, bucket, object, 1, "data", ObjectOptions{Versioned: true, UserDefined: meta})
|
||||
z.poolMetaMutex.Lock()
|
||||
z.poolMeta.Pools[0].Decommission = &PoolDecommissionInfo{}
|
||||
z.poolMetaMutex.Unlock()
|
||||
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
|
||||
defer cancel()
|
||||
gate := &consistencyGateReader{Reader: strings.NewReader("data"), entered: make(chan struct{}), resume: make(chan struct{})}
|
||||
release := func() { gate.release.Do(func() { close(gate.resume) }) }
|
||||
defer release()
|
||||
reader := mustGetPutObjReader(t, gate, 4, "", "")
|
||||
written := make(chan error, 1)
|
||||
go func() {
|
||||
_, err := z.PutObject(ctx, bucket, object, reader, ObjectOptions{
|
||||
Versioned: true, VersionID: oi.VersionID, MTime: oi.ModTime,
|
||||
ReplicaLockReconcile: true, UserDefined: maps.Clone(meta),
|
||||
})
|
||||
written <- err
|
||||
}()
|
||||
select {
|
||||
case <-gate.entered:
|
||||
case err := <-written:
|
||||
t.Fatalf("write failed before consuming the body: %v", err)
|
||||
case <-ctx.Done():
|
||||
t.Fatal(ctx.Err())
|
||||
}
|
||||
mutated := make(chan error, 1)
|
||||
go func() {
|
||||
var err error
|
||||
if heal {
|
||||
_, err = z.healObjectInPool(ctx, z.serverPools[1].getHashedSet(object), bucket, object, oi.VersionID, madmin.HealOpts{})
|
||||
} else {
|
||||
_, err = z.PutObjectMetadata(ctx, bucket, object, ObjectOptions{
|
||||
VersionID: oi.VersionID, MTime: oi.ModTime,
|
||||
EvalMetadataFn: func(current *ObjectInfo, _ error) (ReplicateDecision, error) {
|
||||
current.UserDefined[strings.ToLower(xhttp.AmzObjectLockLegalHold)] = "ON"
|
||||
current.UserDefined[ReservedMetadataPrefixLower+ObjectLockLegalHoldTimestamp] = recent
|
||||
return ReplicateDecision{}, nil
|
||||
},
|
||||
})
|
||||
}
|
||||
mutated <- err
|
||||
}()
|
||||
var early bool
|
||||
select {
|
||||
case err := <-mutated:
|
||||
early = true
|
||||
t.Errorf("mutation completed during the paused replica write: %v", err)
|
||||
case <-time.After(250 * time.Millisecond):
|
||||
}
|
||||
release()
|
||||
if err := <-written; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !early {
|
||||
if err := <-mutated; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
got, err := z.GetObjectInfo(ctx, bucket, object, ObjectOptions{VersionID: oi.VersionID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !heal && storedObjectLockState(got.UserDefined).legalHold != "ON" {
|
||||
t.Error("replica write rolled back the newer metadata update")
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolsConditionalDeletePreservesVersionHistory(t *testing.T) {
|
||||
z, bucket := consistencyPools(t)
|
||||
const object = "conditional-marker"
|
||||
older := putConsistencyObject(t, z, bucket, object, 1, "older", ObjectOptions{Versioned: true, MTime: time.Now().Add(-time.Hour)})
|
||||
latest := putConsistencyObject(t, z, bucket, object, 0, "latest", ObjectOptions{Versioned: true})
|
||||
_, err := z.DeleteObject(t.Context(), bucket, object, ObjectOptions{
|
||||
Versioned: true,
|
||||
CheckPrecondFn: func(oi ObjectInfo) bool { return oi.ETag != older.ETag },
|
||||
})
|
||||
if !isErrPreconditionFailed(err) {
|
||||
t.Fatalf("wrong latest ETag: %v", err)
|
||||
}
|
||||
marker, err := z.DeleteObject(t.Context(), bucket, object, ObjectOptions{
|
||||
Versioned: true,
|
||||
CheckPrecondFn: func(oi ObjectInfo) bool { return oi.ETag != latest.ETag },
|
||||
})
|
||||
if err != nil || !marker.DeleteMarker {
|
||||
t.Fatalf("logical delete did not create a marker: %+v, %v", marker, err)
|
||||
}
|
||||
if got, err := z.GetObjectInfo(t.Context(), bucket, object, ObjectOptions{}); !isErrObjectNotFound(err) || !got.DeleteMarker {
|
||||
t.Errorf("delete marker did not hide the split object: %+v, %v", got, err)
|
||||
}
|
||||
for _, version := range []string{older.VersionID, latest.VersionID} {
|
||||
if _, err := z.GetObjectInfo(t.Context(), bucket, object, ObjectOptions{VersionID: version}); err != nil {
|
||||
t.Errorf("conditional marker removed history %s: %v", version, err)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func poolLockMetadata(retention, hold, retentionTime, holdTime string) map[string]string {
|
||||
return map[string]string{
|
||||
strings.ToLower(xhttp.AmzObjectLockMode): retention,
|
||||
strings.ToLower(xhttp.AmzObjectLockRetainUntilDate): "2030-01-01T00:00:00Z",
|
||||
strings.ToLower(xhttp.AmzObjectLockLegalHold): hold,
|
||||
ReservedMetadataPrefixLower + ObjectLockRetentionTimestamp: retentionTime,
|
||||
ReservedMetadataPrefixLower + ObjectLockLegalHoldTimestamp: holdTime,
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolsReplicaIndependentLockWinners(t *testing.T) {
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
multipart, rebalance bool
|
||||
}{
|
||||
{"put-decommission", false, false},
|
||||
{"put-rebalance", false, true},
|
||||
{"multipart-decommission", true, false},
|
||||
{"multipart-rebalance", true, true},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
z, bucket := consistencyPools(t)
|
||||
const object = "split-lock-state"
|
||||
old, recent := "2026-09-09T09:00:00Z", "2026-09-09T10:00:00Z"
|
||||
first := poolLockMetadata("GOVERNANCE", "OFF", recent, old)
|
||||
second := poolLockMetadata("", "ON", old, recent)
|
||||
oi := putConsistencyObject(t, z, bucket, object, 0, "data", ObjectOptions{Versioned: true, UserDefined: first})
|
||||
putConsistencyObject(t, z, bucket, object, 1, "data", ObjectOptions{
|
||||
Versioned: true, VersionID: oi.VersionID, MTime: oi.ModTime, UserDefined: second,
|
||||
})
|
||||
opts := ObjectOptions{
|
||||
Versioned: true, VersionID: oi.VersionID, MTime: oi.ModTime,
|
||||
ReplicaLockReconcile: true, UserDefined: poolLockMetadata("", "OFF", old, old),
|
||||
}
|
||||
var uploadID string
|
||||
var parts []CompletePart
|
||||
if tc.multipart {
|
||||
mp, err := z.serverPools[1].NewMultipartUpload(t.Context(), bucket, object, opts)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
uploadID = mp.UploadID
|
||||
part, err := z.serverPools[1].PutObjectPart(t.Context(), bucket, object, uploadID, 1,
|
||||
mustGetPutObjReader(t, bytes.NewBufferString("data"), 4, "", ""), ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parts = []CompletePart{{PartNumber: 1, ETag: part.ETag}}
|
||||
}
|
||||
// The upload and both versions predate the routing change. Retention's
|
||||
// winner remains in the draining pool; legal hold's winner is in pool 1.
|
||||
if tc.rebalance {
|
||||
z.rebalMu.Lock()
|
||||
z.rebalMeta = &rebalanceMeta{PoolStats: []*rebalanceStats{
|
||||
{Participating: true, Info: rebalanceInfo{Status: rebalStarted}}, {},
|
||||
}}
|
||||
z.rebalMu.Unlock()
|
||||
} else {
|
||||
z.poolMetaMutex.Lock()
|
||||
z.poolMeta.Pools[0].Decommission = &PoolDecommissionInfo{}
|
||||
z.poolMetaMutex.Unlock()
|
||||
}
|
||||
var err error
|
||||
if tc.multipart {
|
||||
_, err = z.CompleteMultipartUpload(t.Context(), bucket, object, uploadID, parts,
|
||||
ObjectOptions{Versioned: true, MTime: oi.ModTime, ReplicaLockReconcile: true})
|
||||
} else {
|
||||
_, err = z.PutObject(t.Context(), bucket, object,
|
||||
mustGetPutObjReader(t, bytes.NewBufferString("data"), 4, "", ""), opts)
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := z.GetObjectInfo(t.Context(), bucket, object, ObjectOptions{VersionID: oi.VersionID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state := storedObjectLockState(got.UserDefined)
|
||||
if state.mode != "GOVERNANCE" || state.retentionTimestamp != recent || state.legalHold != "ON" || state.legalHoldTimestamp != recent {
|
||||
t.Errorf("pooled read lost independently ordered lock state: %+v", state)
|
||||
}
|
||||
if _, err := z.serverPools[0].GetObjectInfo(t.Context(), bucket, object, ObjectOptions{VersionID: oi.VersionID}); !isErrVersionNotFound(err) {
|
||||
t.Errorf("successful replacement left its stale competing copy: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolsReplicaSoleDrainingOwner(t *testing.T) {
|
||||
for _, rebalance := range []bool{false, true} {
|
||||
for _, null := range []bool{false, true} {
|
||||
t.Run(fmt.Sprintf("rebalance=%t/null=%t", rebalance, null), func(t *testing.T) {
|
||||
z, bucket := consistencyPools(t)
|
||||
const object = "sole-owner"
|
||||
old, recent := "2026-09-09T09:00:00Z", "2026-09-09T10:00:00Z"
|
||||
meta := poolLockMetadata("", "ON", recent, recent)
|
||||
delete(meta, strings.ToLower(xhttp.AmzObjectLockRetainUntilDate))
|
||||
oi := putConsistencyObject(t, z, bucket, object, 0, "data", ObjectOptions{Versioned: !null, UserDefined: meta})
|
||||
versionID := oi.VersionID
|
||||
if null {
|
||||
versionID = nullVersionID
|
||||
// A different latest version must not donate its lock to the null version.
|
||||
putConsistencyObject(t, z, bucket, object, 1, "other-version", ObjectOptions{Versioned: true})
|
||||
}
|
||||
if rebalance {
|
||||
z.rebalMu.Lock()
|
||||
z.rebalMeta = &rebalanceMeta{PoolStats: []*rebalanceStats{
|
||||
{Participating: true, Info: rebalanceInfo{Status: rebalStarted}}, {},
|
||||
}}
|
||||
z.rebalMu.Unlock()
|
||||
} else {
|
||||
z.poolMetaMutex.Lock()
|
||||
z.poolMeta.Pools[0].Decommission = &PoolDecommissionInfo{}
|
||||
z.poolMetaMutex.Unlock()
|
||||
}
|
||||
_, err := z.PutObject(t.Context(), bucket, object,
|
||||
mustGetPutObjReader(t, bytes.NewBufferString("data"), 4, "", ""), ObjectOptions{
|
||||
Versioned: !null, VersionSuspended: null, VersionID: versionID, MTime: oi.ModTime,
|
||||
ReplicaLockReconcile: true, UserDefined: poolLockMetadata("GOVERNANCE", "OFF", old, old),
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := z.GetObjectInfo(t.Context(), bucket, object, ObjectOptions{VersionID: versionID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state := storedObjectLockState(got.UserDefined)
|
||||
if state.mode != "" || state.retainUntil != "" || state.retentionTimestamp != recent || state.legalHold != "ON" {
|
||||
t.Errorf("lost a removal or legal hold from the sole draining owner: %+v", state)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolsMetadataUpdateUsesMergedVersion(t *testing.T) {
|
||||
z, bucket := consistencyPools(t)
|
||||
const object = "metadata-update"
|
||||
old, recent := "2026-09-09T09:00:00Z", "2026-09-09T10:00:00Z"
|
||||
oi := putConsistencyObject(t, z, bucket, object, 0, "data", ObjectOptions{
|
||||
Versioned: true, UserDefined: poolLockMetadata("GOVERNANCE", "OFF", recent, old),
|
||||
})
|
||||
putConsistencyObject(t, z, bucket, object, 1, "data", ObjectOptions{
|
||||
Versioned: true, VersionID: oi.VersionID, MTime: oi.ModTime, UserDefined: poolLockMetadata("", "ON", old, recent),
|
||||
})
|
||||
latest := putConsistencyObject(t, z, bucket, object, 1, "latest", ObjectOptions{Versioned: true})
|
||||
called := 0
|
||||
_, err := z.PutObjectMetadata(t.Context(), bucket, object, ObjectOptions{
|
||||
VersionID: oi.VersionID, MTime: oi.ModTime,
|
||||
EvalMetadataFn: func(current *ObjectInfo, _ error) (ReplicateDecision, error) {
|
||||
called++
|
||||
state := storedObjectLockState(current.UserDefined)
|
||||
if state.mode != "GOVERNANCE" || state.legalHold != "ON" {
|
||||
return ReplicateDecision{}, fmt.Errorf("metadata policy evaluated stale state: %+v", state)
|
||||
}
|
||||
current.UserDefined["custom-update"] = "preserved"
|
||||
return ReplicateDecision{}, nil
|
||||
},
|
||||
})
|
||||
if err != nil || called != 1 {
|
||||
t.Fatalf("metadata update: %v; callback count %d", err, called)
|
||||
}
|
||||
for i, pool := range z.serverPools {
|
||||
got, err := pool.GetObjectInfo(t.Context(), bucket, object, ObjectOptions{VersionID: oi.VersionID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state := storedObjectLockState(got.UserDefined)
|
||||
if state.mode != "GOVERNANCE" || state.legalHold != "ON" || got.UserDefined["custom-update"] != "preserved" {
|
||||
t.Errorf("pool %d did not receive the merged update: %+v", i, got.UserDefined)
|
||||
}
|
||||
}
|
||||
if current, err := z.GetObjectInfo(t.Context(), bucket, object, ObjectOptions{}); err != nil || current.VersionID != latest.VersionID {
|
||||
t.Errorf("updating an older version changed the latest: %+v, %v", current, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolsReplicaMetadataCopyReconcilesLockAndTags(t *testing.T) {
|
||||
z, bucket := consistencyPools(t)
|
||||
const object = "replica-metadata-copy"
|
||||
old, recent := "2026-09-09T09:00:00Z", "2026-09-09T10:00:00Z"
|
||||
meta := poolLockMetadata("GOVERNANCE", "OFF", recent, old)
|
||||
meta[xhttp.AmzObjectTagging] = "key=new"
|
||||
meta[ReservedMetadataPrefixLower+TaggingTimestamp] = recent
|
||||
oi := putConsistencyObject(t, z, bucket, object, 0, "data", ObjectOptions{Versioned: true, UserDefined: meta})
|
||||
putConsistencyObject(t, z, bucket, object, 1, "data", ObjectOptions{
|
||||
Versioned: true, VersionID: oi.VersionID, MTime: oi.ModTime, UserDefined: poolLockMetadata("", "ON", old, recent),
|
||||
})
|
||||
stale := oi
|
||||
stale.metadataOnly = true
|
||||
stale.UserDefined = maps.Clone(oi.UserDefined)
|
||||
stale.UserDefined[xhttp.AmzObjectTagging] = "key=old"
|
||||
stale.UserDefined[ReservedMetadataPrefixLower+TaggingTimestamp] = old
|
||||
_, err := z.CopyObject(t.Context(), bucket, object, bucket, object, stale,
|
||||
ObjectOptions{VersionID: oi.VersionID}, ObjectOptions{
|
||||
Versioned: true, VersionID: oi.VersionID, MTime: oi.ModTime, ReplicaLockReconcile: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got, err := z.GetObjectInfo(t.Context(), bucket, object, ObjectOptions{VersionID: oi.VersionID})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
state := storedObjectLockState(got.UserDefined)
|
||||
if state.mode != "GOVERNANCE" || state.legalHold != "ON" || got.UserTags != "key=new" {
|
||||
t.Errorf("metadata replication rolled back a newer field: %+v", got.UserDefined)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolsReplicaCleanupFailureCanRetry(t *testing.T) {
|
||||
z, bucket := consistencyPools(t)
|
||||
const object = "replica-cleanup-failure"
|
||||
old, recent := "2026-09-09T09:00:00Z", "2026-09-09T10:00:00Z"
|
||||
oi := putConsistencyObject(t, z, bucket, object, 0, "data", ObjectOptions{
|
||||
Versioned: true, UserDefined: poolLockMetadata("GOVERNANCE", "ON", recent, recent),
|
||||
})
|
||||
z.poolMetaMutex.Lock()
|
||||
z.poolMeta.Pools[0].Decommission = &PoolDecommissionInfo{}
|
||||
z.poolMetaMutex.Unlock()
|
||||
set := z.serverPools[0].getHashedSet(object)
|
||||
getDisks := set.getDisks
|
||||
faulty := append([]StorageAPI(nil), getDisks()...)
|
||||
for i := range faulty {
|
||||
faulty[i] = accessMoveDeleteFaultDisk{StorageAPI: faulty[i], bucket: bucket, object: object, version: oi.VersionID}
|
||||
}
|
||||
set.getDisks = func() []StorageAPI { return faulty }
|
||||
defer func() { set.getDisks = getDisks }()
|
||||
write := func() error {
|
||||
_, err := z.PutObject(t.Context(), bucket, object,
|
||||
mustGetPutObjReader(t, bytes.NewBufferString("data"), 4, "", ""), ObjectOptions{
|
||||
Versioned: true, VersionID: oi.VersionID, MTime: oi.ModTime, ReplicaLockReconcile: true,
|
||||
UserDefined: poolLockMetadata("", "OFF", old, old),
|
||||
})
|
||||
return err
|
||||
}
|
||||
if err := write(); err == nil {
|
||||
t.Fatal("replica replacement hid a competing-copy cleanup failure")
|
||||
}
|
||||
if got, err := z.serverPools[1].GetObjectInfo(t.Context(), bucket, object, ObjectOptions{VersionID: oi.VersionID}); err != nil || storedObjectLockState(got.UserDefined).legalHold != "ON" {
|
||||
t.Fatalf("cleanup failure lost the committed reconciled version: %+v, %v", got, err)
|
||||
}
|
||||
set.getDisks = getDisks
|
||||
if err := write(); err != nil {
|
||||
t.Fatalf("retry could not finish cleanup: %v", err)
|
||||
}
|
||||
if _, err := z.serverPools[0].GetObjectInfo(t.Context(), bucket, object, ObjectOptions{VersionID: oi.VersionID}); !isErrVersionNotFound(err) {
|
||||
t.Errorf("retry left the competing version: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPoolsRetiringCopyPreservesSharedTierObject(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
deleting bool
|
||||
failPrimaryDelete bool
|
||||
differentRemote bool
|
||||
restored bool
|
||||
}{
|
||||
{name: "metadata-copy"},
|
||||
{name: "restored-metadata-copy", restored: true},
|
||||
{name: "metadata-copy-distinct-reference", differentRemote: true},
|
||||
{name: "failed-primary-delete", deleting: true, failPrimaryDelete: true},
|
||||
{name: "failed-primary-delete-distinct-reference", deleting: true, failPrimaryDelete: true, differentRemote: true},
|
||||
{name: "successful-delete", deleting: true},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
z, bucket := consistencyPools(t)
|
||||
const object = "shared-tier-object"
|
||||
metadata := map[string]string{
|
||||
ReservedMetadataPrefixLower + TransitionStatus: "complete",
|
||||
ReservedMetadataPrefixLower + TransitionTier: "TEST-TIER",
|
||||
ReservedMetadataPrefixLower + TransitionedObjectName: "shared-remote-object",
|
||||
ReservedMetadataPrefixLower + TransitionedVersionID: "shared-remote-version",
|
||||
}
|
||||
if test.restored {
|
||||
metadata[xhttp.AmzRestore] = completedRestoreObj(time.Now().Add(time.Hour)).String()
|
||||
}
|
||||
oi := putConsistencyObject(t, z, bucket, object, 0, "data", ObjectOptions{Versioned: true, UserDefined: metadata})
|
||||
secondaryMetadata := maps.Clone(metadata)
|
||||
if test.differentRemote {
|
||||
secondaryMetadata[ReservedMetadataPrefixLower+TransitionedObjectName] = "other-remote-object"
|
||||
}
|
||||
putConsistencyObject(t, z, bucket, object, 1, "data", ObjectOptions{
|
||||
Versioned: true, VersionID: oi.VersionID, MTime: oi.ModTime, UserDefined: secondaryMetadata,
|
||||
})
|
||||
current, err := z.GetObjectInfo(t.Context(), bucket, object, ObjectOptions{VersionID: oi.VersionID})
|
||||
if err != nil || current.TransitionedObject.Status != "complete" || current.IsRemote() == test.restored {
|
||||
t.Fatalf("fixture did not persist the tier reference: %+v, %v", current.TransitionedObject, err)
|
||||
}
|
||||
if test.failPrimaryDelete {
|
||||
// The authoritative copy remains readable if its deletion fails.
|
||||
// Retiring a secondary copy must not schedule its shared remote
|
||||
// contents for garbage collection in that case.
|
||||
set := z.serverPools[0].getHashedSet(object)
|
||||
getDisks := set.getDisks
|
||||
faulty := append([]StorageAPI(nil), getDisks()...)
|
||||
for i := range faulty {
|
||||
faulty[i] = accessMoveDeleteFaultDisk{StorageAPI: faulty[i], bucket: bucket, object: object, version: oi.VersionID}
|
||||
}
|
||||
set.getDisks = func() []StorageAPI { return faulty }
|
||||
defer func() { set.getDisks = getDisks }()
|
||||
}
|
||||
if test.deleting {
|
||||
_, err := z.DeleteObject(t.Context(), bucket, object, ObjectOptions{
|
||||
Versioned: true, VersionID: oi.VersionID,
|
||||
CheckPrecondFn: func(info ObjectInfo) bool { return info.ETag != current.ETag },
|
||||
})
|
||||
if (err != nil) != test.failPrimaryDelete {
|
||||
t.Fatalf("unexpected authoritative delete result: %v", err)
|
||||
}
|
||||
} else {
|
||||
current.metadataOnly = true
|
||||
current.UserDefined["metadata-update"] = "new"
|
||||
_, err := z.CopyObject(t.Context(), bucket, object, bucket, object, current,
|
||||
ObjectOptions{VersionID: oi.VersionID}, ObjectOptions{
|
||||
Versioned: true, VersionID: oi.VersionID, MTime: oi.ModTime, ReplicaLockReconcile: true,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
_, err = z.serverPools[0].GetObjectInfo(t.Context(), bucket, object, ObjectOptions{VersionID: oi.VersionID})
|
||||
primaryDeleted := test.deleting && !test.failPrimaryDelete
|
||||
if primaryDeleted {
|
||||
if !isErrVersionNotFound(err) {
|
||||
t.Fatalf("authoritative copy survived successful delete: %v", err)
|
||||
}
|
||||
} else if err != nil {
|
||||
t.Fatalf("lost retained authoritative copy: %v", err)
|
||||
}
|
||||
for pool, wantFree := range []bool{primaryDeleted, test.differentRemote} {
|
||||
for _, disk := range z.serverPools[pool].getHashedSet(object).getDisks() {
|
||||
data, err := disk.ReadAll(t.Context(), bucket, pathJoin(object, xlStorageFormatFile))
|
||||
if errors.Is(err, errFileNotFound) && !wantFree {
|
||||
continue
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
versions, err := getFileInfoVersions(data, bucket, object, false)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
wantCount := 0
|
||||
if wantFree {
|
||||
wantCount = 1
|
||||
}
|
||||
if len(versions.FreeVersions) != wantCount {
|
||||
t.Fatalf("pool %d has %d tier GC markers, want %d", pool, len(versions.FreeVersions), wantCount)
|
||||
}
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,10 @@ import (
|
||||
)
|
||||
|
||||
func prepareErasurePools() (ObjectLayer, []string, error) {
|
||||
return prepareErasurePoolsWithContext(context.Background())
|
||||
}
|
||||
|
||||
func prepareErasurePoolsWithContext(ctx context.Context) (ObjectLayer, []string, error) {
|
||||
nDisks := 32
|
||||
fsDirs, err := getRandomDisks(nDisks)
|
||||
if err != nil {
|
||||
@@ -32,7 +36,7 @@ func prepareErasurePools() (ObjectLayer, []string, error) {
|
||||
pools := mustGetPoolEndpoints(0, fsDirs[:16]...)
|
||||
pools = append(pools, mustGetPoolEndpoints(1, fsDirs[16:]...)...)
|
||||
|
||||
objLayer, _, err := initObjectLayer(context.Background(), pools)
|
||||
objLayer, _, err := initObjectLayer(ctx, pools)
|
||||
if err != nil {
|
||||
removeRoots(fsDirs)
|
||||
return nil, nil, err
|
||||
|
||||
+111
-56
@@ -645,6 +645,12 @@ func (z *erasureServerPools) getPoolIdxNoLock(ctx context.Context, bucket, objec
|
||||
// if none are found falls back to most available space pool, this function is
|
||||
// designed to be only used by PutObject, CopyObject (newObject creation) and NewMultipartUpload.
|
||||
func (z *erasureServerPools) getPoolIdx(ctx context.Context, bucket, object string, size int64, dstPoolIdx *int) (idx int, err error) {
|
||||
return z.getWritePoolIdx(ctx, bucket, object, size, dstPoolIdx, false)
|
||||
}
|
||||
|
||||
// getWritePoolIdx keeps the write-allocation policy when the caller already
|
||||
// holds the pools-layer object lock and must not reacquire a set read lock.
|
||||
func (z *erasureServerPools) getWritePoolIdx(ctx context.Context, bucket, object string, size int64, dstPoolIdx *int, noLock bool) (idx int, err error) {
|
||||
if dstPoolIdx != nil {
|
||||
if *dstPoolIdx < 0 || *dstPoolIdx >= len(z.serverPools) {
|
||||
return -1, errInvalidArgument
|
||||
@@ -656,6 +662,7 @@ func (z *erasureServerPools) getPoolIdx(ctx context.Context, bucket, object stri
|
||||
}
|
||||
|
||||
pinfo, _, err := z.getPoolInfoExistingWithOpts(ctx, bucket, object, ObjectOptions{
|
||||
NoLock: noLock,
|
||||
SkipDecommissioned: true,
|
||||
SkipRebalancing: true,
|
||||
})
|
||||
@@ -1164,7 +1171,18 @@ func (z *erasureServerPools) PutObject(ctx context.Context, bucket string, objec
|
||||
return z.serverPools[0].PutObject(ctx, bucket, object, data, opts)
|
||||
}
|
||||
|
||||
idx, err := z.getPoolIdx(ctx, bucket, object, data.Size(), dataMovementDstPool(opts))
|
||||
if !opts.NoLock {
|
||||
lk := z.NewNSLock(bucket, object)
|
||||
lkctx, err := lk.GetLock(ctx, globalOperationTimeout)
|
||||
if err != nil {
|
||||
return ObjectInfo{}, err
|
||||
}
|
||||
ctx = lkctx.Context()
|
||||
defer lk.Unlock(lkctx)
|
||||
}
|
||||
opts.NoLock = true
|
||||
|
||||
idx, err := z.getWritePoolIdx(ctx, bucket, object, data.Size(), dataMovementDstPool(opts), true)
|
||||
if err != nil {
|
||||
return ObjectInfo{}, err
|
||||
}
|
||||
@@ -1178,7 +1196,15 @@ func (z *erasureServerPools) PutObject(ctx context.Context, bucket string, objec
|
||||
}
|
||||
}
|
||||
|
||||
return z.serverPools[idx].PutObject(ctx, bucket, object, data, opts)
|
||||
if opts.ReplicaLockReconcile || opts.DataMovement {
|
||||
opts.ReplicaLockReconcile = true
|
||||
opts.replicaObjectInfo = z.replicaObjectInfo
|
||||
}
|
||||
oi, err := z.serverPools[idx].PutObject(ctx, bucket, object, data, opts)
|
||||
if err == nil && opts.ReplicaLockReconcile && !opts.DataMovement {
|
||||
err = z.retireReplicaCopies(ctx, bucket, object, idx, oi)
|
||||
}
|
||||
return oi, err
|
||||
}
|
||||
|
||||
func (z *erasureServerPools) deletePrefix(ctx context.Context, bucket string, prefix string) error {
|
||||
@@ -1199,15 +1225,7 @@ func (z *erasureServerPools) DeleteObject(ctx context.Context, bucket string, ob
|
||||
object = encodeDirObject(object)
|
||||
}
|
||||
|
||||
// Acquire a write lock before deleting the object.
|
||||
//
|
||||
// NOTE: this lock is taken at the server-pool level. The conditional
|
||||
// (If-Match) precondition below relies on this lock making the read-check-
|
||||
// delete sequence atomic. That holds for a single erasure set: the write
|
||||
// path (PutObject) locks at the destination set, which shares this lock's
|
||||
// namespace only within one set. Multi-pool conditional-delete atomicity
|
||||
// (concurrent writers across pools, cross-pool version selection) is a
|
||||
// separate concern tracked as a follow-up.
|
||||
// Serialize logical deletion with pooled writes and metadata updates.
|
||||
lk := z.NewNSLock(bucket, object)
|
||||
lkctx, err := lk.GetLock(ctx, globalDeleteOperationTimeout)
|
||||
if err != nil {
|
||||
@@ -1242,6 +1260,10 @@ func (z *erasureServerPools) DeleteObject(ctx context.Context, bucket string, ob
|
||||
return objInfo, err
|
||||
}
|
||||
|
||||
if !z.SinglePool() && opts.CheckPrecondFn != nil {
|
||||
return z.deleteObjectConditional(ctx, bucket, object, opts)
|
||||
}
|
||||
|
||||
gopts := opts
|
||||
gopts.NoLock = true
|
||||
|
||||
@@ -1377,8 +1399,12 @@ func (z *erasureServerPools) deleteObjectFromAllPools(ctx context.Context, bucke
|
||||
// the delete call tries to clean up other pools during DeleteObject call.
|
||||
objInfo = dobjects[0]
|
||||
objInfo.Name = decodeDirObject(object)
|
||||
err = derrs[0]
|
||||
return objInfo, err
|
||||
for _, derr := range derrs {
|
||||
if derr != nil && !isErrObjectNotFound(derr) && !isErrVersionNotFound(derr) {
|
||||
return objInfo, derr
|
||||
}
|
||||
}
|
||||
return objInfo, derrs[0]
|
||||
}
|
||||
|
||||
func (z *erasureServerPools) DeleteObjects(ctx context.Context, bucket string, objects []ObjectToDelete, opts ObjectOptions) ([]DeletedObject, []error) {
|
||||
@@ -1466,6 +1492,22 @@ func (z *erasureServerPools) CopyObject(ctx context.Context, srcBucket, srcObjec
|
||||
dstOpts.NoLock = true
|
||||
}
|
||||
|
||||
if !z.SinglePool() && cpSrcDstSame && srcInfo.metadataOnly && dstOpts.ReplicaLockReconcile && srcOpts.VersionID == dstOpts.VersionID {
|
||||
copies, err := z.metadataPoolInfos(ctx, dstBucket, dstObject, dstOpts)
|
||||
if err != nil {
|
||||
return ObjectInfo{}, err
|
||||
}
|
||||
stored := mergedPoolObjectInfo(copies)
|
||||
reconcileStoredObjectLock(srcInfo.UserDefined, storedObjectLockState(stored.UserDefined))
|
||||
reconcileStoredObjectTags(srcInfo.UserDefined, stored.UserDefined)
|
||||
idx := copies[0].Index
|
||||
oi, err := z.serverPools[idx].CopyObject(ctx, srcBucket, srcObject, dstBucket, dstObject, srcInfo, srcOpts, dstOpts)
|
||||
if err == nil {
|
||||
err = z.retireReplicaCopies(ctx, dstBucket, dstObject, idx, oi)
|
||||
}
|
||||
return oi, err
|
||||
}
|
||||
|
||||
poolIdx, err := z.getPoolIdxNoLock(ctx, dstBucket, dstObject, srcInfo.Size, dataMovementDstPool(dstOpts))
|
||||
if err != nil {
|
||||
return objInfo, err
|
||||
@@ -1477,6 +1519,17 @@ func (z *erasureServerPools) CopyObject(ctx context.Context, srcBucket, srcObjec
|
||||
}
|
||||
}
|
||||
|
||||
if !z.SinglePool() && dstOpts.ReplicaLockReconcile {
|
||||
dstOpts.replicaObjectInfo = z.replicaObjectInfo
|
||||
if !dstOpts.DataMovement {
|
||||
defer func() {
|
||||
if err == nil {
|
||||
err = z.retireReplicaCopies(ctx, dstBucket, dstObject, poolIdx, objInfo)
|
||||
}
|
||||
}()
|
||||
}
|
||||
}
|
||||
|
||||
// CopyObjectHandler predicts the outcome of this decision in
|
||||
// copyRewritesObjectData(); keep the two in sync.
|
||||
if cpSrcDstSame && srcInfo.metadataOnly {
|
||||
@@ -1511,6 +1564,8 @@ func (z *erasureServerPools) CopyObject(ctx context.Context, srcBucket, srcObjec
|
||||
EncryptFn: dstOpts.EncryptFn,
|
||||
WantChecksum: dstOpts.WantChecksum,
|
||||
WantServerSideChecksumType: dstOpts.WantServerSideChecksumType,
|
||||
ReplicaLockReconcile: dstOpts.ReplicaLockReconcile,
|
||||
replicaObjectInfo: dstOpts.replicaObjectInfo,
|
||||
}
|
||||
|
||||
return z.serverPools[poolIdx].PutObject(ctx, dstBucket, dstObject, srcInfo.PutObjReader, putOpts)
|
||||
@@ -2158,6 +2213,19 @@ func (z *erasureServerPools) CompleteMultipartUpload(ctx context.Context, bucket
|
||||
}
|
||||
}()
|
||||
|
||||
if !z.SinglePool() {
|
||||
if !opts.NoLock {
|
||||
lk := z.NewNSLock(bucket, encodeDirObject(object))
|
||||
lkctx, err := lk.GetLock(ctx, globalOperationTimeout)
|
||||
if err != nil {
|
||||
return objInfo, err
|
||||
}
|
||||
ctx = lkctx.Context()
|
||||
defer lk.Unlock(lkctx)
|
||||
}
|
||||
opts.NoLock = true
|
||||
}
|
||||
|
||||
// Hold write locks to verify uploaded parts, also disallows any
|
||||
// parallel PutObjectPart() requests.
|
||||
uploadIDLock := z.NewNSLock(bucket, pathJoin(object, uploadID))
|
||||
@@ -2172,13 +2240,21 @@ func (z *erasureServerPools) CompleteMultipartUpload(ctx context.Context, bucket
|
||||
return z.serverPools[0].CompleteMultipartUpload(ctx, bucket, object, uploadID, uploadedParts, opts)
|
||||
}
|
||||
|
||||
if opts.ReplicaLockReconcile || opts.DataMovement {
|
||||
opts.ReplicaLockReconcile = true
|
||||
opts.replicaObjectInfo = z.replicaObjectInfo
|
||||
}
|
||||
|
||||
for idx, pool := range z.serverPools {
|
||||
if z.IsSuspended(idx) {
|
||||
continue
|
||||
}
|
||||
objInfo, err = pool.CompleteMultipartUpload(ctx, bucket, object, uploadID, uploadedParts, opts)
|
||||
if err == nil {
|
||||
return objInfo, nil
|
||||
if opts.ReplicaLockReconcile && !opts.DataMovement {
|
||||
err = z.retireReplicaCopies(ctx, bucket, encodeDirObject(object), idx, objInfo)
|
||||
}
|
||||
return objInfo, err
|
||||
}
|
||||
if _, ok := err.(InvalidUploadID); ok {
|
||||
// upload id not found move to next pool
|
||||
@@ -2705,7 +2781,7 @@ func (z *erasureServerPools) HealObject(ctx context.Context, bucket, object, ver
|
||||
wg.Add(1)
|
||||
go func(idx int, pool *erasureSets) {
|
||||
defer wg.Done()
|
||||
result, err := pool.HealObject(ctx, bucket, object, versionID, opts)
|
||||
result, err := z.healObjectInPool(ctx, pool.getHashedSet(object), bucket, object, versionID, opts)
|
||||
result.Object = decodeDirObject(result.Object)
|
||||
errs[idx] = err
|
||||
results[idx] = result
|
||||
@@ -2974,15 +3050,7 @@ func (z *erasureServerPools) PutObjectMetadata(ctx context.Context, bucket, obje
|
||||
defer lk.Unlock(lkctx)
|
||||
}
|
||||
|
||||
opts.MetadataChg = true
|
||||
opts.NoLock = true
|
||||
// We don't know the size here set 1GiB at least.
|
||||
idx, err := z.getPoolIdxExistingWithOpts(ctx, bucket, object, opts)
|
||||
if err != nil {
|
||||
return ObjectInfo{}, err
|
||||
}
|
||||
|
||||
return z.serverPools[idx].PutObjectMetadata(ctx, bucket, object, opts)
|
||||
return z.updatePoolMetadata(ctx, bucket, object, opts)
|
||||
}
|
||||
|
||||
// PutObjectTags - replace or add tags to an existing object
|
||||
@@ -3003,44 +3071,31 @@ func (z *erasureServerPools) PutObjectTags(ctx context.Context, bucket, object s
|
||||
defer lk.Unlock(lkctx)
|
||||
}
|
||||
|
||||
opts.MetadataChg = true
|
||||
opts.NoLock = true
|
||||
|
||||
// We don't know the size here set 1GiB at least.
|
||||
idx, err := z.getPoolIdxExistingWithOpts(ctx, bucket, object, opts)
|
||||
copies, err := z.metadataPoolInfos(ctx, bucket, object, opts)
|
||||
if err != nil {
|
||||
return ObjectInfo{}, err
|
||||
}
|
||||
|
||||
return z.serverPools[idx].PutObjectTags(ctx, bucket, object, tags, opts)
|
||||
opts.NoLock = true
|
||||
opts.VersionID = copies[0].ObjInfo.VersionID
|
||||
if opts.VersionID == "" {
|
||||
opts.VersionID = nullVersionID
|
||||
}
|
||||
var primary ObjectInfo
|
||||
for _, copy := range copies {
|
||||
oi, err := z.serverPools[copy.Index].PutObjectTags(ctx, bucket, object, tags, opts)
|
||||
if err != nil {
|
||||
return ObjectInfo{}, err
|
||||
}
|
||||
if copy.Index == copies[0].Index {
|
||||
primary = oi
|
||||
}
|
||||
}
|
||||
return primary, nil
|
||||
}
|
||||
|
||||
// DeleteObjectTags - delete object tags from an existing object
|
||||
func (z *erasureServerPools) DeleteObjectTags(ctx context.Context, bucket, object string, opts ObjectOptions) (ObjectInfo, error) {
|
||||
object = encodeDirObject(object)
|
||||
if z.SinglePool() {
|
||||
return z.serverPools[0].DeleteObjectTags(ctx, bucket, object, opts)
|
||||
}
|
||||
|
||||
if !opts.NoLock {
|
||||
// Lock the object before deleting tags.
|
||||
lk := z.NewNSLock(bucket, object)
|
||||
lkctx, err := lk.GetLock(ctx, globalOperationTimeout)
|
||||
if err != nil {
|
||||
return ObjectInfo{}, err
|
||||
}
|
||||
ctx = lkctx.Context()
|
||||
defer lk.Unlock(lkctx)
|
||||
}
|
||||
|
||||
opts.MetadataChg = true
|
||||
opts.NoLock = true
|
||||
idx, err := z.getPoolIdxExistingWithOpts(ctx, bucket, object, opts)
|
||||
if err != nil {
|
||||
return ObjectInfo{}, err
|
||||
}
|
||||
|
||||
return z.serverPools[idx].DeleteObjectTags(ctx, bucket, object, opts)
|
||||
return z.PutObjectTags(ctx, bucket, object, "", opts)
|
||||
}
|
||||
|
||||
// GetObjectTags - get object tags from an existing object
|
||||
@@ -3050,7 +3105,7 @@ func (z *erasureServerPools) GetObjectTags(ctx context.Context, bucket, object s
|
||||
return z.serverPools[0].GetObjectTags(ctx, bucket, object, opts)
|
||||
}
|
||||
|
||||
oi, _, err := z.getLatestObjectInfoWithIdx(ctx, bucket, object, opts)
|
||||
oi, err := z.GetObjectInfo(ctx, bucket, object, opts)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
+8
-2
@@ -166,6 +166,12 @@ func (er *erasureObjects) healErasureSet(ctx context.Context, buckets []string,
|
||||
if objAPI == nil {
|
||||
return errServerNotInitialized
|
||||
}
|
||||
healInPool := er.HealObject
|
||||
if z, ok := objAPI.(*erasureServerPools); ok && !z.SinglePool() {
|
||||
healInPool = func(ctx context.Context, bucket, object, versionID string, opts madmin.HealOpts) (madmin.HealResultItem, error) {
|
||||
return z.healObjectInPool(ctx, er, bucket, object, versionID, opts)
|
||||
}
|
||||
}
|
||||
|
||||
started := tracker.Started
|
||||
if started.IsZero() || started.Equal(timeSentinel) {
|
||||
@@ -419,7 +425,7 @@ func (er *erasureObjects) healErasureSet(ctx context.Context, buckets []string,
|
||||
var result healEntryResult
|
||||
fivs, err := entry.fileInfoVersions(bucket)
|
||||
if err != nil {
|
||||
res, err := er.HealObject(ctx, bucket, encodedEntryName, "",
|
||||
res, err := healInPool(ctx, bucket, encodedEntryName, "",
|
||||
madmin.HealOpts{
|
||||
ScanMode: scanMode,
|
||||
Remove: healDeleteDangling,
|
||||
@@ -455,7 +461,7 @@ func (er *erasureObjects) healErasureSet(ctx context.Context, buckets []string,
|
||||
continue
|
||||
}
|
||||
|
||||
res, err := er.HealObject(ctx, bucket, encodedEntryName,
|
||||
res, err := healInPool(ctx, bucket, encodedEntryName,
|
||||
version.VersionID, madmin.HealOpts{
|
||||
ScanMode: scanMode,
|
||||
Remove: healDeleteDangling,
|
||||
|
||||
+4
-6
@@ -51,9 +51,8 @@ func initGlobalGrid(ctx context.Context, eps EndpointServerPools) error {
|
||||
grid.ContextDialer(xhttp.DialContextWithLookupHost(lookupHost, xhttp.NewInternodeDialContext(rest.DefaultTimeout, globalTCPOptions.ForWebsocket()))),
|
||||
newCachedAuthToken(),
|
||||
&tls.Config{
|
||||
RootCAs: globalRootCAs,
|
||||
CipherSuites: crypto.TLSCiphers(),
|
||||
CurvePreferences: crypto.TLSCurveIDs(),
|
||||
RootCAs: globalRootCAs,
|
||||
CipherSuites: crypto.TLSCiphers(),
|
||||
}),
|
||||
Local: local,
|
||||
Hosts: hosts,
|
||||
@@ -84,9 +83,8 @@ func initGlobalLockGrid(ctx context.Context, eps EndpointServerPools) error {
|
||||
grid.ContextDialer(xhttp.DialContextWithLookupHost(lookupHost, xhttp.NewInternodeDialContext(rest.DefaultTimeout, globalTCPOptions.ForWebsocket()))),
|
||||
newCachedAuthToken(),
|
||||
&tls.Config{
|
||||
RootCAs: globalRootCAs,
|
||||
CipherSuites: crypto.TLSCiphers(),
|
||||
CurvePreferences: crypto.TLSCurveIDs(),
|
||||
RootCAs: globalRootCAs,
|
||||
CipherSuites: crypto.TLSCiphers(),
|
||||
}, grid.RouteLockPath),
|
||||
Local: local,
|
||||
Hosts: hosts,
|
||||
|
||||
@@ -99,10 +99,13 @@ type ObjectOptions struct {
|
||||
ReplicationSourceTaggingTimestamp time.Time // set if MinIOSourceTaggingTimestamp received
|
||||
ReplicationSourceLegalholdTimestamp time.Time // set if MinIOSourceObjectLegalholdTimestamp received
|
||||
ReplicationSourceRetentionTimestamp time.Time // set if MinIOSourceObjectRetentionTimestamp received
|
||||
ReplicaLockReconcile bool // set for a trusted SSE-C replica full write/completion: re-order Object Lock against the destination version read under the write lock (single erasure set; see pgsty/silo#133)
|
||||
ReplicaLockReconcile bool // re-order a trusted replica write against the destination version under the object write lock
|
||||
DeletePrefix bool // set true to enforce a prefix deletion, only application for DeleteObject API,
|
||||
DeletePrefixObject bool // set true when object's erasure set is resolvable by object name (using getHashedSetIndex)
|
||||
|
||||
// Pools-layer version resolver; the caller holds the shared object lock.
|
||||
replicaObjectInfo GetObjectInfoFn
|
||||
|
||||
Speedtest bool // object call specifically meant for SpeedTest code, set to 'true' when invoked by SpeedtestHandler.
|
||||
|
||||
// Use the maximum parity (N/2), used when saving server configuration files
|
||||
@@ -136,8 +139,8 @@ type ObjectOptions struct {
|
||||
// when looking up a version by fi.VersionID
|
||||
InclFreeVersions bool
|
||||
// SkipFreeVersion skips adding a free version when a tiered version is
|
||||
// being 'replaced'
|
||||
// Note: Used only when a tiered object is being expired.
|
||||
// being replaced. Used when expiring tiered content or retiring a copy
|
||||
// whose tier reference is still owned by another copy.
|
||||
SkipFreeVersion bool
|
||||
|
||||
MetadataChg bool // is true if it is a metadata update operation.
|
||||
|
||||
@@ -433,7 +433,16 @@ func putOptsFromHeaders(ctx context.Context, hdr http.Header, metadata map[strin
|
||||
if err != nil {
|
||||
return ObjectOptions{}, err
|
||||
}
|
||||
sseKms, err := encrypt.NewSSEKMS(keyID, context)
|
||||
// kms.Context implements encoding.TextMarshaler, so handing it to the
|
||||
// SDK's interface{} parameter would serialize the context as a JSON
|
||||
// string, which the receiving ParseHTTP rejects; a nil Context is a
|
||||
// typed nil there and would be sent as "{}". Pass a plain map, or
|
||||
// nothing when no context was requested.
|
||||
var sdkContext any
|
||||
if context != nil {
|
||||
sdkContext = map[string]string(context)
|
||||
}
|
||||
sseKms, err := encrypt.NewSSEKMS(keyID, sdkContext)
|
||||
if err != nil {
|
||||
return ObjectOptions{}, err
|
||||
}
|
||||
|
||||
@@ -62,6 +62,13 @@ func copyChecksumRequest(t *testing.T, apiRouter http.Handler, credentials auth.
|
||||
t.Fatalf("failed to build CopyObject request: %v", err)
|
||||
}
|
||||
req.Header.Set(xhttp.AmzCopySource, SlashSeparator+pathJoin(bucket, source))
|
||||
// Re-sign so x-amz-copy-source is covered by the signature, as real S3
|
||||
// clients send it; the verifier rejects unsigned x-amz-* headers.
|
||||
if credentials.AccessKey != "" && credentials.SecretKey != "" {
|
||||
if err := signRequestV4(req, credentials.AccessKey, credentials.SecretKey); err != nil {
|
||||
t.Fatalf("failed to re-sign CopyObject request: %v", err)
|
||||
}
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
return rec
|
||||
|
||||
@@ -0,0 +1,241 @@
|
||||
// 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"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio/internal/auth"
|
||||
objectlock "github.com/minio/minio/internal/bucket/object/lock"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
"github.com/minio/minio/internal/kms"
|
||||
)
|
||||
|
||||
// enableBucketObjectLock puts a lock-enabled configuration on an existing
|
||||
// bucket so checkPutObjectLockAllowed accepts a legal-hold header instead of
|
||||
// rejecting the request with ErrInvalidBucketObjectLockConfiguration.
|
||||
func enableBucketObjectLock(t *testing.T, bucket string) {
|
||||
t.Helper()
|
||||
meta, err := globalBucketMetadataSys.Get(bucket)
|
||||
if err != nil {
|
||||
t.Fatalf("unable to read bucket metadata for %s: %v", bucket, err)
|
||||
}
|
||||
updated := meta
|
||||
updated.ObjectLockConfigXML = enabledBucketObjectLockConfig
|
||||
updated.VersioningConfigXML = enabledBucketVersioningConfig
|
||||
// The XML alone is not enough: BucketMetadata keeps a parsed copy that the
|
||||
// lookups actually read, and it is only populated by parseAllConfigs.
|
||||
if err := updated.parseAllConfigs(t.Context(), newObjectLayerFn()); err != nil {
|
||||
t.Fatalf("unable to parse bucket metadata for %s: %v", bucket, err)
|
||||
}
|
||||
globalBucketMetadataSys.Set(bucket, updated)
|
||||
}
|
||||
|
||||
// Exercise #165 and #166 together, including hold OFF, default retention and
|
||||
// explicit subsecond retention. Ordinary copies must not inherit source locks.
|
||||
func TestAPIFederatedCopyObjectLockParity(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
endpoints: []string{"CopyObject", "PutObject", "HeadObject", "GetObject"},
|
||||
objAPITest: func(obj ObjectLayer, instanceType, bucket string, router http.Handler, cred auth.Credentials, t *testing.T) {
|
||||
testKMS, err := kms.NewBuiltin(federationTestKMSKeyID, bytes.Repeat([]byte{0x58}, 32))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
previousKMS := GlobalKMS
|
||||
GlobalKMS = testKMS
|
||||
defer func() { GlobalKMS = previousKMS }()
|
||||
remoteBucket, capture, cleanup := setupCopyObjectFederation(t, obj, router, instanceType, bucket)
|
||||
defer cleanup()
|
||||
enableBucketObjectLock(t, bucket)
|
||||
until := UTCNow().Add(7 * 24 * time.Hour).Truncate(time.Second).Add(789 * time.Millisecond).Format(time.RFC3339Nano)
|
||||
for _, sourceType := range []string{"plain", "s3"} {
|
||||
source := sourceType + "-held-source"
|
||||
headers := federationSSEHeaders(sourceType, 0, false)
|
||||
headers[xhttp.AmzObjectLockLegalHold] = "ON"
|
||||
putCopyChecksumSource(t, router, cred, bucket, source, []byte("held source"), headers)
|
||||
for _, tc := range []struct {
|
||||
name, hold, defaultMode, explicitMode string
|
||||
replace bool
|
||||
}{
|
||||
{name: "on", hold: "ON"},
|
||||
{name: "off", hold: "OFF"},
|
||||
{name: "no source inheritance"},
|
||||
{name: "on with default", hold: "ON", defaultMode: "GOVERNANCE"},
|
||||
{name: "off with default", hold: "OFF", defaultMode: "COMPLIANCE"},
|
||||
{name: "explicit retention", explicitMode: "GOVERNANCE"},
|
||||
{name: "hold and explicit retention", hold: "ON", explicitMode: "COMPLIANCE"},
|
||||
{name: "replace metadata", hold: "ON", explicitMode: "GOVERNANCE", replace: true},
|
||||
} {
|
||||
t.Run(instanceType+"/"+sourceType+"/"+tc.name, func(t *testing.T) {
|
||||
setTestBucketDefaultRetention(t, bucket, tc.defaultMode)
|
||||
setTestBucketDefaultRetention(t, remoteBucket, tc.defaultMode)
|
||||
headers := map[string]string{}
|
||||
if tc.hold != "" {
|
||||
headers[xhttp.AmzObjectLockLegalHold] = tc.hold
|
||||
}
|
||||
if tc.explicitMode != "" {
|
||||
headers[xhttp.AmzObjectLockMode] = tc.explicitMode
|
||||
headers[xhttp.AmzObjectLockRetainUntilDate] = until
|
||||
}
|
||||
if tc.replace {
|
||||
headers[xhttp.AmzMetadataDirective] = "REPLACE"
|
||||
headers["X-Amz-Meta-Origin"] = "replacement"
|
||||
}
|
||||
capture.mu.Lock()
|
||||
capture.headers = nil
|
||||
capture.mu.Unlock()
|
||||
for _, destinationBucket := range []string{bucket, remoteBucket} {
|
||||
destination := sourceType + "-copy-" + strings.ReplaceAll(tc.name, " ", "-")
|
||||
rec := federatedCopyRequest(t, router, cred, bucket, source, destinationBucket, destination, headers)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("copy to %s: %d %s", destinationBucket, rec.Code, rec.Body.String())
|
||||
}
|
||||
info, err := obj.GetObjectInfo(t.Context(), destinationBucket, destination, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got := objectlock.GetObjectLegalHoldMeta(info.UserDefined).Status; string(got) != tc.hold {
|
||||
t.Errorf("stored hold = %q, want %q", got, tc.hold)
|
||||
}
|
||||
retention := objectlock.GetObjectRetentionMeta(info.UserDefined)
|
||||
mode := tc.explicitMode
|
||||
if mode == "" {
|
||||
mode = tc.defaultMode
|
||||
}
|
||||
if string(retention.Mode) != mode {
|
||||
t.Errorf("stored retention = %q, want %q", retention.Mode, mode)
|
||||
}
|
||||
if tc.explicitMode != "" && retention.RetainUntilDate.Format(time.RFC3339Nano) != until {
|
||||
t.Errorf("retention date lost precision: %s, want %s", retention.RetainUntilDate, until)
|
||||
}
|
||||
for key := range info.UserDefined {
|
||||
if stringsHasPrefixFold(key, "X-Amz-Meta-X-Amz-Object-Lock-") {
|
||||
t.Errorf("lock state became user metadata: %s", key)
|
||||
}
|
||||
}
|
||||
if tc.replace && info.UserDefined["X-Amz-Meta-Origin"] != "replacement" {
|
||||
t.Errorf("replacement metadata was lost: %v", info.UserDefined)
|
||||
}
|
||||
}
|
||||
typed, asMetadata := capture.legalHoldHeaders()
|
||||
if len(asMetadata) != 0 || (tc.hold != "" && strings.Join(typed, "") != tc.hold) || (tc.hold == "" && len(typed) != 0) {
|
||||
t.Errorf("forwarded hold headers = %v, metadata = %v; want %q", typed, asMetadata, tc.hold)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// legalHoldHeaders returns the forwarded legal-hold headers the remote saw,
|
||||
// separated into the real Object Lock header and the user-metadata spelling
|
||||
// minio-go produces for an unrecognized UserMetadata key.
|
||||
func (c *federationRemoteCapture) legalHoldHeaders() (typed, asMetadata []string) {
|
||||
c.mu.Lock()
|
||||
defer c.mu.Unlock()
|
||||
metaKey := "X-Amz-Meta-" + xhttp.AmzObjectLockLegalHold
|
||||
for _, h := range c.headers {
|
||||
for k, v := range h {
|
||||
switch {
|
||||
case strings.EqualFold(k, xhttp.AmzObjectLockLegalHold):
|
||||
typed = append(typed, strings.Join(v, ","))
|
||||
case strings.EqualFold(k, metaKey):
|
||||
asMetadata = append(asMetadata, strings.Join(v, ","))
|
||||
}
|
||||
}
|
||||
}
|
||||
return typed, asMetadata
|
||||
}
|
||||
|
||||
// TestAPIFederatedCopyObjectLegalHold drives the legacy etcd federation branch
|
||||
// of CopyObjectHandler with an explicit legal hold on the copy.
|
||||
//
|
||||
// Before the fix the resolved hold was forwarded inside
|
||||
// PutObjectOptions.UserMetadata. minio-go's Header() prefixes every
|
||||
// UserMetadata key it does not recognize with "x-amz-meta-", and
|
||||
// x-amz-object-lock-legal-hold is in neither supportedHeaders nor isAmzHeader,
|
||||
// so the hold reached the remote as X-Amz-Meta-X-Amz-Object-Lock-Legal-Hold.
|
||||
// The destination stored no hold and the copy still answered 200 -- a silent
|
||||
// loss of a WORM control (#166). Retention requested on the same copy survived,
|
||||
// which is what made it easy to miss.
|
||||
func TestAPIFederatedCopyObjectLegalHold(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPIFederatedCopyObjectLegalHold,
|
||||
endpoints: []string{"CopyObject", "PutObject", "HeadObject", "GetObject"},
|
||||
})
|
||||
}
|
||||
|
||||
func testAPIFederatedCopyObjectLegalHold(objectAPI ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
data := []byte("federated copy with a legal hold")
|
||||
srcObject := "federation/legal-hold-source"
|
||||
putCopyChecksumSource(t, apiRouter, credentials, bucketName, srcObject, data, nil)
|
||||
|
||||
remoteBucket, capture, cleanup := setupCopyObjectFederation(t, objectAPI, apiRouter, instanceType, bucketName)
|
||||
defer cleanup()
|
||||
|
||||
// Both roles read bucket metadata from the shared backend in this fixture,
|
||||
// so one configuration covers the proxy's own check and the remote's.
|
||||
enableBucketObjectLock(t, bucketName)
|
||||
enableBucketObjectLock(t, remoteBucket)
|
||||
|
||||
dstObject := "federation/legal-hold-destination"
|
||||
rec := federatedCopyRequest(t, apiRouter, credentials, bucketName, srcObject, remoteBucket, dstObject,
|
||||
map[string]string{xhttp.AmzObjectLockLegalHold: string(objectlock.LegalHoldOn)})
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: federated CopyObject with a legal hold failed: %d %s",
|
||||
instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
|
||||
// The wire is the point: the hold must arrive as the Object Lock header,
|
||||
// never as user metadata. A 200 with the metadata spelling is exactly the
|
||||
// silent loss this test exists for.
|
||||
typed, asMetadata := capture.legalHoldHeaders()
|
||||
if len(asMetadata) != 0 {
|
||||
t.Fatalf("%s: legal hold forwarded as user metadata %v; the destination stores no hold",
|
||||
instanceType, asMetadata)
|
||||
}
|
||||
if len(typed) == 0 {
|
||||
t.Fatalf("%s: no %s header reached the remote deployment", instanceType, xhttp.AmzObjectLockLegalHold)
|
||||
}
|
||||
for _, got := range typed {
|
||||
if !strings.EqualFold(got, string(objectlock.LegalHoldOn)) {
|
||||
t.Fatalf("%s: forwarded legal hold = %q, want %q", instanceType, got, objectlock.LegalHoldOn)
|
||||
}
|
||||
}
|
||||
|
||||
// And it must actually be stored on the destination version.
|
||||
oi, err := objectAPI.GetObjectInfo(t.Context(), remoteBucket, dstObject, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("%s: unable to stat the federated copy destination: %v", instanceType, err)
|
||||
}
|
||||
if hold := objectlock.GetObjectLegalHoldMeta(oi.UserDefined); hold.Status != objectlock.LegalHoldOn {
|
||||
t.Fatalf("%s: destination legal hold = %q, want %q (metadata: %v)",
|
||||
instanceType, hold.Status, objectlock.LegalHoldOn, oi.UserDefined)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,167 @@
|
||||
// Copyright (c) 2026 PGSTY
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/xml"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio/internal/amztime"
|
||||
"github.com/minio/minio/internal/auth"
|
||||
sse "github.com/minio/minio/internal/bucket/encryption"
|
||||
"github.com/minio/minio/internal/event"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
"github.com/minio/minio/internal/kms"
|
||||
"github.com/minio/minio/internal/pubsub"
|
||||
)
|
||||
|
||||
func TestAPIFederatedCopyObjectVersionAndEvent(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
endpoints: []string{"CopyObject", "PutObject", "GetObject", "HeadObject"},
|
||||
objAPITest: func(obj ObjectLayer, instanceType, bucket string, router http.Handler, cred auth.Credentials, t *testing.T) {
|
||||
testKMS, err := kms.NewBuiltin(federationTestKMSKeyID, bytes.Repeat([]byte{0x58}, 32))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
previousKMS := GlobalKMS
|
||||
GlobalKMS = testKMS
|
||||
defer func() { GlobalKMS = previousKMS }()
|
||||
restore := setCopyChecksumCompression(true)
|
||||
defer restore()
|
||||
remoteBucket, _, cleanup := setupCopyObjectFederation(t, obj, router, instanceType, bucket)
|
||||
defer cleanup()
|
||||
enableBucketObjectLock(t, remoteBucket)
|
||||
events := make(chan event.Event, 8)
|
||||
done := make(chan struct{})
|
||||
defer close(done)
|
||||
if err := globalHTTPListen.Subscribe(pubsub.MaskFromMaskable(event.ObjectCreatedCopy), events, done, nil); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, kind := range []string{"plain", "compressed", "encrypted"} {
|
||||
t.Run(instanceType+"/"+kind, func(t *testing.T) {
|
||||
data := []byte("logical object size")
|
||||
source := kind + "-source.bin"
|
||||
var headers map[string]string
|
||||
if kind == "compressed" {
|
||||
data = bytes.Repeat(data, 8192)
|
||||
source = kind + "-source.txt"
|
||||
}
|
||||
if kind == "encrypted" {
|
||||
headers = federationSSEHeaders("s3", 0, false)
|
||||
}
|
||||
putCopyChecksumSource(t, router, cred, bucket, source, data, headers)
|
||||
destination := "result/" + kind + " with space.bin"
|
||||
rec := federatedCopyRequest(t, router, cred, bucket, source, remoteBucket, destination, nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("copy: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
versionID := strings.Join(rec.Header()[xhttp.AmzVersionID], "")
|
||||
if versionID == "" {
|
||||
t.Error("copy response omitted destination version ID")
|
||||
} else {
|
||||
info, err := obj.GetObjectInfo(t.Context(), remoteBucket, destination, ObjectOptions{VersionID: versionID})
|
||||
if err != nil || info.VersionID != versionID {
|
||||
t.Fatalf("response does not name the written version: %v, %q", err, info.VersionID)
|
||||
}
|
||||
var response CopyObjectResponse
|
||||
if err := xml.Unmarshal(rec.Body.Bytes(), &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := amztime.ISO8601Format(info.ModTime.UTC()); response.LastModified != want {
|
||||
t.Errorf("copy time = %q, want written version time %q", response.LastModified, want)
|
||||
}
|
||||
}
|
||||
select {
|
||||
case evt := <-events:
|
||||
key, err := url.QueryUnescape(evt.S3.Object.Key)
|
||||
if err != nil || key != destination || evt.S3.Bucket.Name != remoteBucket || evt.S3.Object.Size != int64(len(data)) || evt.S3.Object.VersionID == "" || evt.S3.Object.VersionID != versionID {
|
||||
t.Errorf("copy event does not describe the written object: %+v", evt.S3)
|
||||
}
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("copy event was not emitted")
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func TestAPIFederatedCopyObjectDestinationSSEDefaults(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
endpoints: []string{"CopyObject", "PutObject", "GetObject", "HeadObject"},
|
||||
objAPITest: func(obj ObjectLayer, instanceType, bucket string, router http.Handler, cred auth.Credentials, t *testing.T) {
|
||||
data := []byte("destination chooses default encryption")
|
||||
putCopyChecksumSource(t, router, cred, bucket, "source", data, nil)
|
||||
testKMS, err := kms.NewBuiltin(federationTestKMSKeyID, bytes.Repeat([]byte{0x58}, 32))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
previousKMS, previousAuto := GlobalKMS, globalAutoEncryption
|
||||
GlobalKMS, globalAutoEncryption = testKMS, true
|
||||
defer func() { GlobalKMS, globalAutoEncryption = previousKMS, previousAuto }()
|
||||
remoteBucket, capture, cleanup := setupCopyObjectFederationRemote(t, obj, router, instanceType, bucket, true)
|
||||
defer cleanup()
|
||||
destinationConfig, err := sse.ParseBucketSSEConfig(strings.NewReader(`<ServerSideEncryptionConfiguration><Rule><ApplyServerSideEncryptionByDefault><SSEAlgorithm>aws:kms</SSEAlgorithm><KMSMasterKeyID>destination-bucket-key</KMSMasterKeyID></ApplyServerSideEncryptionByDefault></Rule></ServerSideEncryptionConfiguration>`))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, kind := range []string{"plain", "s3", "kms", "kms-default", "c"} {
|
||||
t.Run(instanceType+"/"+kind, func(t *testing.T) {
|
||||
var headers map[string]string
|
||||
if kind == "kms-default" {
|
||||
headers = map[string]string{xhttp.AmzServerSideEncryption: xhttp.AmzEncryptionKMS}
|
||||
} else {
|
||||
headers = federationSSEHeaders(kind, 0x22, false)
|
||||
}
|
||||
rec := federatedCopyRequest(t, router, cred, bucket, "source", remoteBucket, kind, headers)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("copy: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
capture.mu.Lock()
|
||||
forwarded := capture.headers[len(capture.headers)-1].Clone()
|
||||
capture.mu.Unlock()
|
||||
if kind == "plain" {
|
||||
if forwarded.Get(xhttp.AmzServerSideEncryption) != "" {
|
||||
t.Errorf("proxy injected SSE %q into a request with no client SSE", forwarded.Get(xhttp.AmzServerSideEncryption))
|
||||
}
|
||||
// With nothing injected, the KMS encryption the destination
|
||||
// stores can only be the remote applying its own defaults.
|
||||
info, err := obj.GetObjectInfo(t.Context(), remoteBucket, kind, ObjectOptions{})
|
||||
if err != nil || federationStoredSSE(info.UserDefined) != "kms" {
|
||||
t.Errorf("remote destination did not apply its own auto-encryption: %v, %v", err, info.UserDefined)
|
||||
}
|
||||
}
|
||||
// Replay the actual inbound headers against an independent bucket
|
||||
// configuration. No handler flips shared globals while serving.
|
||||
destinationConfig.Apply(forwarded, sse.ApplyOptions{})
|
||||
wantKey := headers[xhttp.AmzServerSideEncryptionKmsID]
|
||||
if kind == "plain" {
|
||||
wantKey = "destination-bucket-key"
|
||||
}
|
||||
if got := forwarded.Get(xhttp.AmzServerSideEncryptionKmsID); got != wantKey {
|
||||
t.Errorf("destination selected key %q, want %q", got, wantKey)
|
||||
}
|
||||
})
|
||||
}
|
||||
// A local destination still inherits the server's auto-encryption.
|
||||
rec := federatedCopyRequest(t, router, cred, bucket, "source", bucket, "local-copy", nil)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("local copy: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
info, err := obj.GetObjectInfo(t.Context(), bucket, "local-copy", ObjectOptions{})
|
||||
if err != nil || federationStoredSSE(info.UserDefined) != "kms" {
|
||||
t.Errorf("local copy lost auto-encryption: %v, %v", err, info.UserDefined)
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -20,20 +20,29 @@ package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/md5"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/xml"
|
||||
"io"
|
||||
"maps"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strconv"
|
||||
"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/amztime"
|
||||
"github.com/minio/minio/internal/auth"
|
||||
"github.com/minio/minio/internal/config/dns"
|
||||
"github.com/minio/minio/internal/crypto"
|
||||
"github.com/minio/minio/internal/hash"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
"github.com/minio/minio/internal/kms"
|
||||
)
|
||||
|
||||
// federationRemoteCapture records the exact request headers the remote
|
||||
@@ -91,6 +100,26 @@ func (c *federationRemoteCapture) reservedKeys() []string {
|
||||
// to the default region, exactly as TestAPIFederatedCopyObjectPartChecksum does.
|
||||
func setupCopyObjectFederation(t *testing.T, objectAPI ObjectLayer, apiRouter http.Handler,
|
||||
instanceType, srcBucket string, responseFilters ...func(http.Header),
|
||||
) (remoteBucket string, capture *federationRemoteCapture, cleanup func()) {
|
||||
t.Helper()
|
||||
return setupCopyObjectFederationRemote(t, objectAPI, apiRouter, instanceType, srcBucket, false, responseFilters...)
|
||||
}
|
||||
|
||||
// setupCopyObjectFederationTLS is setupCopyObjectFederation with a TLS remote
|
||||
// endpoint and globalIsTLS set, so an SSE-C copy is accepted on both hops: the
|
||||
// proxy's own SSE-C transport gate and the minio-go client's SSE-C policy. The
|
||||
// proxy client is built exactly as in production, trusting the test
|
||||
// certificate for the duration.
|
||||
func setupCopyObjectFederationTLS(t *testing.T, objectAPI ObjectLayer, apiRouter http.Handler,
|
||||
instanceType, srcBucket string,
|
||||
) (remoteBucket string, cleanup func()) {
|
||||
t.Helper()
|
||||
remoteBucket, _, cleanup = setupCopyObjectFederationRemote(t, objectAPI, apiRouter, instanceType, srcBucket, true)
|
||||
return remoteBucket, cleanup
|
||||
}
|
||||
|
||||
func setupCopyObjectFederationRemote(t *testing.T, objectAPI ObjectLayer, apiRouter http.Handler,
|
||||
instanceType, srcBucket string, secure bool, responseFilters ...func(http.Header),
|
||||
) (remoteBucket string, capture *federationRemoteCapture, cleanup func()) {
|
||||
t.Helper()
|
||||
remoteBucket = getRandomBucketName()
|
||||
@@ -99,13 +128,19 @@ func setupCopyObjectFederation(t *testing.T, objectAPI ObjectLayer, apiRouter ht
|
||||
}
|
||||
|
||||
capture = &federationRemoteCapture{}
|
||||
remote := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
capture.record(r.Header)
|
||||
if len(responseFilters) != 0 && r.Method == http.MethodPut {
|
||||
w = federationResponseFilter{ResponseWriter: w, filter: responseFilters[0]}
|
||||
}
|
||||
apiRouter.ServeHTTP(w, r)
|
||||
}))
|
||||
})
|
||||
var remote *httptest.Server
|
||||
if secure {
|
||||
remote = httptest.NewTLSServer(handler)
|
||||
} else {
|
||||
remote = httptest.NewServer(handler)
|
||||
}
|
||||
host, port, _ := strings.Cut(remote.Listener.Addr().String(), ":")
|
||||
|
||||
globalObjLayerMutex.Lock()
|
||||
@@ -113,6 +148,7 @@ func setupCopyObjectFederation(t *testing.T, objectAPI ObjectLayer, apiRouter ht
|
||||
globalObjectAPI = remoteBucketObjectLayer{ObjectLayer: previousLayer, remoteBucket: remoteBucket}
|
||||
globalObjLayerMutex.Unlock()
|
||||
previousDNS, previousFederation, previousIPs := globalDNSConfig, globalBucketFederation, globalDomainIPs
|
||||
previousTLS, previousClient := globalIsTLS, getRemoteInstanceClient
|
||||
globalDNSConfig = federationTestDNS{records: map[string][]dns.SrvRecord{
|
||||
srcBucket: {{Host: host, Port: json.Number(port)}},
|
||||
remoteBucket: {{Host: host, Port: json.Number(port)}},
|
||||
@@ -121,6 +157,23 @@ func setupCopyObjectFederation(t *testing.T, objectAPI ObjectLayer, apiRouter ht
|
||||
// middleware always serves locally and only the handler proxies.
|
||||
globalDomainIPs = set.CreateStringSet(remote.Listener.Addr().String())
|
||||
globalBucketFederation = true
|
||||
if secure {
|
||||
globalIsTLS = true
|
||||
transport := remote.Client().Transport
|
||||
getRemoteInstanceClient = func(r *http.Request, host string) (*miniogo.Core, error) {
|
||||
cred := getReqAccessCred(r, globalSite.Region())
|
||||
core, err := miniogo.NewCore(host, &miniogo.Options{
|
||||
Creds: miniocredentials.NewStaticV4(cred.AccessKey, cred.SecretKey, ""),
|
||||
Secure: true,
|
||||
Transport: federatedWriteTransport{transport},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
core.SetAppInfo(federatedInternalAppName, ReleaseTag)
|
||||
return core, nil
|
||||
}
|
||||
}
|
||||
|
||||
cleanup = func() {
|
||||
remote.Close()
|
||||
@@ -128,6 +181,7 @@ func setupCopyObjectFederation(t *testing.T, objectAPI ObjectLayer, apiRouter ht
|
||||
globalObjectAPI = previousLayer
|
||||
globalObjLayerMutex.Unlock()
|
||||
globalDNSConfig, globalBucketFederation, globalDomainIPs = previousDNS, previousFederation, previousIPs
|
||||
globalIsTLS, getRemoteInstanceClient = previousTLS, previousClient
|
||||
}
|
||||
return remoteBucket, capture, cleanup
|
||||
}
|
||||
@@ -144,11 +198,62 @@ func federatedCopyRequest(t *testing.T, apiRouter http.Handler, credentials auth
|
||||
t.Fatalf("failed to build federated CopyObject request: %v", err)
|
||||
}
|
||||
req.Header.Set(xhttp.AmzCopySource, SlashSeparator+pathJoin(srcBucket, srcObject))
|
||||
// Re-sign so x-amz-copy-source is covered by the signature, as real S3
|
||||
// clients send it; the verifier rejects unsigned x-amz-* headers.
|
||||
if credentials.AccessKey != "" && credentials.SecretKey != "" {
|
||||
if err := signRequestV4(req, credentials.AccessKey, credentials.SecretKey); err != nil {
|
||||
t.Fatalf("failed to re-sign federated CopyObject request: %v", err)
|
||||
}
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
func TestAPIFederatedCopyObjectRejectsRawSSECReplica(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
endpoints: []string{"CopyObject", "PutObject"},
|
||||
objAPITest: func(obj ObjectLayer, instanceType, bucket string, router http.Handler, cred auth.Credentials, t *testing.T) {
|
||||
remoteBucket, capture, cleanup := setupCopyObjectFederationRemote(t, obj, router, instanceType, bucket, true)
|
||||
defer cleanup()
|
||||
for _, body := range []string{"", "raw SSE-C replica"} {
|
||||
for _, withKey := range []bool{false, true} {
|
||||
t.Run("size="+strconv.Itoa(len(body))+"/key="+strconv.FormatBool(withKey), func(t *testing.T) {
|
||||
putCopyChecksumSource(t, router, cred, bucket, "source", []byte(body), federationSSEHeaders("c", 0x11, false))
|
||||
headers := map[string]string{
|
||||
xhttp.MinIOSourceReplicationRequest: "true",
|
||||
xhttp.AmzBucketReplicationStatus: "REPLICA",
|
||||
}
|
||||
if withKey {
|
||||
maps.Copy(headers, federationSSEHeaders("c", 0x11, true))
|
||||
}
|
||||
destination := "destination-" + strconv.Itoa(len(body)) + "-" + strconv.FormatBool(withKey)
|
||||
rec := federatedCopyRequest(t, router, cred, bucket, "source", remoteBucket, destination, headers)
|
||||
var response APIErrorResponse
|
||||
if err := xml.Unmarshal(rec.Body.Bytes(), &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if rec.Code != http.StatusNotImplemented || response.Code != "NotImplemented" ||
|
||||
!strings.Contains(response.Message, "federated raw SSE-C replica CopyObject") {
|
||||
t.Errorf("copy = %d %s, want explicit 501 rejection", rec.Code, rec.Body.String())
|
||||
}
|
||||
if _, err := obj.GetObjectInfo(t.Context(), remoteBucket, destination, ObjectOptions{}); !isErrObjectNotFound(err) {
|
||||
t.Errorf("rejected copy created a destination: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
capture.mu.Lock()
|
||||
defer capture.mu.Unlock()
|
||||
if len(capture.headers) != 0 {
|
||||
t.Errorf("rejected copies made %d remote requests", len(capture.headers))
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// TestAPIFederatedCopyObjectInlineSource drives the legacy etcd federation
|
||||
// branch of CopyObjectHandler end to end for a source object stored inline.
|
||||
// Such a source carries x-minio-internal-inline-data in its stored metadata,
|
||||
@@ -437,3 +542,415 @@ func testAPIFederatedCopyObjectInheritedChecksum(objectAPI ObjectLayer, instance
|
||||
assertCopyChecksumResponse(t, rec, hash.ChecksumCRC32, data)
|
||||
assertCopyChecksum(t, objectAPI, remoteBucket, dstObject, hash.ChecksumCRC32, data, false, nil)
|
||||
}
|
||||
|
||||
// federationTestKMSKeyID names the single key of the builtin KMS the SSE test
|
||||
// installs; SSE-S3 seals with it implicitly, SSE-KMS names it by ID.
|
||||
const federationTestKMSKeyID = "federation-test-key"
|
||||
|
||||
// federationSSEHeaders returns the request headers that select one server-side
|
||||
// encryption kind: "plain", "s3", "kms", "kms-context" (SSE-KMS with an
|
||||
// explicit encryption context), "kms-empty-context" or "c". SSE-C keys derive from keyByte so a
|
||||
// case can name two distinct customer keys. With copySource the SSE-C key is
|
||||
// returned in its x-amz-copy-source-* form, the only kind a copy has to name
|
||||
// for its source; the other kinds then return nothing.
|
||||
func federationSSEHeaders(kind string, keyByte byte, copySource bool) map[string]string {
|
||||
h := map[string]string{}
|
||||
if copySource && kind != "c" {
|
||||
return h
|
||||
}
|
||||
switch kind {
|
||||
case "plain":
|
||||
case "s3":
|
||||
h[xhttp.AmzServerSideEncryption] = xhttp.AmzEncryptionAES
|
||||
case "kms", "kms-context", "kms-empty-context":
|
||||
h[xhttp.AmzServerSideEncryption] = xhttp.AmzEncryptionKMS
|
||||
h[xhttp.AmzServerSideEncryptionKmsID] = federationTestKMSKeyID
|
||||
switch kind {
|
||||
case "kms-context":
|
||||
h[xhttp.AmzServerSideEncryptionKmsContext] = base64.StdEncoding.EncodeToString([]byte(`{"tenant":"federation"}`))
|
||||
case "kms-empty-context":
|
||||
h[xhttp.AmzServerSideEncryptionKmsContext] = base64.StdEncoding.EncodeToString([]byte(`{}`))
|
||||
}
|
||||
case "c":
|
||||
key := bytes.Repeat([]byte{keyByte}, 32)
|
||||
sum := md5.Sum(key)
|
||||
algorithm, customerKey, keyMD5 := xhttp.AmzServerSideEncryptionCustomerAlgorithm,
|
||||
xhttp.AmzServerSideEncryptionCustomerKey, xhttp.AmzServerSideEncryptionCustomerKeyMD5
|
||||
if copySource {
|
||||
algorithm, customerKey, keyMD5 = xhttp.AmzServerSideEncryptionCopyCustomerAlgorithm,
|
||||
xhttp.AmzServerSideEncryptionCopyCustomerKey, xhttp.AmzServerSideEncryptionCopyCustomerKeyMD5
|
||||
}
|
||||
h[algorithm] = xhttp.AmzEncryptionAES
|
||||
h[customerKey] = base64.StdEncoding.EncodeToString(key)
|
||||
h[keyMD5] = base64.StdEncoding.EncodeToString(sum[:])
|
||||
default:
|
||||
panic("unknown SSE kind " + kind)
|
||||
}
|
||||
return h
|
||||
}
|
||||
|
||||
// federationStoredSSE reports which SSE kind stored object metadata declares.
|
||||
func federationStoredSSE(metadata map[string]string) string {
|
||||
switch {
|
||||
case crypto.SSEC.IsEncrypted(metadata):
|
||||
return "c"
|
||||
case crypto.S3KMS.IsEncrypted(metadata):
|
||||
return "kms"
|
||||
case crypto.S3.IsEncrypted(metadata):
|
||||
return "s3"
|
||||
}
|
||||
return "plain"
|
||||
}
|
||||
|
||||
// federationGetObject reads an object through GetObjectHandler.
|
||||
func federationGetObject(t *testing.T, apiRouter http.Handler, credentials auth.Credentials,
|
||||
bucket, object string, headers map[string]string,
|
||||
) *httptest.ResponseRecorder {
|
||||
t.Helper()
|
||||
req, err := newTestSignedRequestV4(http.MethodGet, getGetObjectURL("", bucket, object),
|
||||
0, nil, credentials.AccessKey, credentials.SecretKey, headers)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to build GetObject request: %v", err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
return rec
|
||||
}
|
||||
|
||||
// assertFederationCopyReadback checks storage and the public GET/HEAD checksum
|
||||
// surface with the destination key, including the committed write's time.
|
||||
func assertFederationCopyReadback(t *testing.T, obj ObjectLayer, router http.Handler, cred auth.Credentials,
|
||||
bucket, object string, rec *httptest.ResponseRecorder, typ hash.ChecksumType, data []byte, compressed bool, keyHeaders map[string]string,
|
||||
) ObjectInfo {
|
||||
t.Helper()
|
||||
assertCopyChecksumResponse(t, rec, typ, data)
|
||||
headers := make(http.Header)
|
||||
for k, v := range keyHeaders {
|
||||
headers.Set(k, v)
|
||||
}
|
||||
info := assertCopyChecksum(t, obj, bucket, object, typ, data, compressed, headers)
|
||||
var response CopyObjectResponse
|
||||
if err := xml.Unmarshal(rec.Body.Bytes(), &response); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if want := amztime.ISO8601Format(info.ModTime.UTC()); info.ModTime.IsZero() || response.LastModified != want {
|
||||
t.Errorf("copy time = %q, want stored time %q", response.LastModified, want)
|
||||
}
|
||||
readHeaders := map[string]string{xhttp.AmzChecksumMode: "ENABLED"}
|
||||
maps.Copy(readHeaders, keyHeaders)
|
||||
for _, method := range []string{http.MethodGet, http.MethodHead} {
|
||||
req, err := newTestSignedRequestV4(method, getGetObjectURL("", bucket, object), 0, nil, cred.AccessKey, cred.SecretKey, readHeaders)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got := httptest.NewRecorder()
|
||||
router.ServeHTTP(got, req)
|
||||
if got.Code != http.StatusOK {
|
||||
t.Fatalf("destination %s = %d %s", method, got.Code, got.Body.String())
|
||||
}
|
||||
if method == http.MethodGet && !bytes.Equal(got.Body.Bytes(), data) {
|
||||
t.Fatalf("destination GET differs from the %d-byte plaintext", len(data))
|
||||
}
|
||||
if got.Header().Get(xhttp.ContentLength) != strconv.Itoa(len(data)) ||
|
||||
got.Header().Get(typ.Key()) != mustChecksum(t, typ, data) ||
|
||||
got.Header().Get(xhttp.AmzChecksumType) != xhttp.AmzChecksumTypeFullObject {
|
||||
t.Fatalf("destination %s length/checksum headers = %v", method, got.Header())
|
||||
}
|
||||
}
|
||||
return info
|
||||
}
|
||||
|
||||
func assertFederationKMSContext(t *testing.T, info ObjectInfo, requested string) {
|
||||
t.Helper()
|
||||
decode := func(encoded string) map[string]string {
|
||||
t.Helper()
|
||||
value, err := base64.StdEncoding.DecodeString(encoded)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var context map[string]string
|
||||
if err := json.Unmarshal(value, &context); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return context
|
||||
}
|
||||
want := map[string]string{}
|
||||
if requested != "" {
|
||||
want = decode(requested)
|
||||
}
|
||||
stored, present := info.UserDefined[crypto.MetaContext]
|
||||
if len(want) == 0 {
|
||||
if present {
|
||||
t.Errorf("absent/empty destination context stored client metadata %q", stored)
|
||||
}
|
||||
} else if !present || !maps.Equal(decode(stored), want) {
|
||||
t.Errorf("stored KMS context = %q, want %v", stored, want)
|
||||
}
|
||||
}
|
||||
|
||||
// TestAPIFederatedCopyObjectSSE guards the legacy etcd federation branch of
|
||||
// CopyObjectHandler for encrypted sources and destinations (#158). The proxy
|
||||
// reads its source through getObjectNInfo, which yields the decrypted and
|
||||
// decompressed bytes, but it used to run the destination encryption locally
|
||||
// as well and then forward that stream with the source's stored size under
|
||||
// the destination SSE option. SSE to plain and plain to SSE failed on the
|
||||
// length mismatch; SSE to SSE matched by coincidence, so the remote encrypted
|
||||
// the ciphertext a second time and a destination GET returned the inner
|
||||
// ciphertext with HTTP 200. The proxy must forward the logical bytes with
|
||||
// their logical size and let the remote encrypt exactly once.
|
||||
func TestAPIFederatedCopyObjectSSE(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: testAPIFederatedCopyObjectSSE,
|
||||
// Register PutObjectPart and CopyObject before the query-less
|
||||
// PutObject PUT route; otherwise PutObject shadows them.
|
||||
endpoints: []string{
|
||||
"NewMultipart", "PutObjectPart", "CompleteMultipart",
|
||||
"CopyObject", "PutObject", "HeadObject", "GetObject",
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
// putFederationMultipartSource uploads parts as one multipart object through
|
||||
// the API router. Headers select the upload's encryption/checksum; SSE-C keys
|
||||
// and checksums are also supplied on the parts and completion as required.
|
||||
func putFederationMultipartSource(t *testing.T, apiRouter http.Handler, credentials auth.Credentials,
|
||||
bucket, object string, parts [][]byte, headers map[string]string,
|
||||
) {
|
||||
t.Helper()
|
||||
do := func(method, url string, body []byte, headers map[string]string) *httptest.ResponseRecorder {
|
||||
req, err := newTestSignedRequestV4(method, url, int64(len(body)), bytes.NewReader(body),
|
||||
credentials.AccessKey, credentials.SecretKey, headers)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to build %s %s request: %v", method, url, err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s %s failed: %d %s", method, url, rec.Code, rec.Body.String())
|
||||
}
|
||||
return rec
|
||||
}
|
||||
var upload InitiateMultipartUploadResponse
|
||||
rec := do(http.MethodPost, getNewMultipartURL("", bucket, object), nil, headers)
|
||||
if err := xml.Unmarshal(rec.Body.Bytes(), &upload); err != nil {
|
||||
t.Fatalf("failed to decode NewMultipartUpload response: %v", err)
|
||||
}
|
||||
completion := CompleteMultipartUpload{}
|
||||
partHeaders := map[string]string{}
|
||||
for _, key := range []string{xhttp.AmzServerSideEncryptionCustomerAlgorithm, xhttp.AmzServerSideEncryptionCustomerKey, xhttp.AmzServerSideEncryptionCustomerKeyMD5} {
|
||||
if value := headers[key]; value != "" {
|
||||
partHeaders[key] = value
|
||||
}
|
||||
}
|
||||
checksumType := hash.NewChecksumType(headers[xhttp.AmzChecksumAlgo], headers[xhttp.AmzChecksumType])
|
||||
for i, part := range parts {
|
||||
if checksumType.IsSet() {
|
||||
partHeaders[checksumType.Key()] = mustChecksum(t, checksumType, part)
|
||||
}
|
||||
rec := do(http.MethodPut, getPutObjectPartURL("", bucket, object, upload.UploadID, strconv.Itoa(i+1)), part, partHeaders)
|
||||
completion.Parts = append(completion.Parts, completePartWithChecksum(checksumType, i+1,
|
||||
canonicalizeETag(rec.Header()[xhttp.ETag][0]), partHeaders[checksumType.Key()]))
|
||||
}
|
||||
body, err := xml.Marshal(completion)
|
||||
if err != nil {
|
||||
t.Fatalf("failed to encode CompleteMultipartUpload: %v", err)
|
||||
}
|
||||
delete(partHeaders, checksumType.Key())
|
||||
do(http.MethodPost, getCompleteMultipartUploadURL("", bucket, object, upload.UploadID), body, partHeaders)
|
||||
}
|
||||
|
||||
func testAPIFederatedCopyObjectSSE(objectAPI ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
testKMS, err := kms.NewBuiltin(federationTestKMSKeyID, bytes.Repeat([]byte{0x58}, 32))
|
||||
if err != nil {
|
||||
t.Fatalf("unable to create the test KMS: %v", err)
|
||||
}
|
||||
previousKMS := GlobalKMS
|
||||
GlobalKMS = testKMS
|
||||
defer func() { GlobalKMS = previousKMS }()
|
||||
// .txt sources are stored compressed, SSE-S3 and SSE-KMS ones included;
|
||||
// SSE-C data is never compressed.
|
||||
restoreCompression := setCopyChecksumCompression(true)
|
||||
defer restoreCompression()
|
||||
|
||||
remoteBucket, cleanup := setupCopyObjectFederationTLS(t, objectAPI, apiRouter, instanceType, bucketName)
|
||||
defer cleanup()
|
||||
|
||||
// A DARE package holds 64 KiB of plaintext, so the larger bodies span two
|
||||
// packages and catch a size that accounts for only one.
|
||||
large := bytes.Repeat([]byte("federated sse copy body "), 64*1024/24+1)[:64*1024+1]
|
||||
bodies := []struct {
|
||||
name, ext string
|
||||
data []byte
|
||||
requested, inherited hash.ChecksumType
|
||||
}{
|
||||
{name: "empty", ext: ".bin"},
|
||||
{name: "empty-explicit", ext: ".bin", requested: hash.ChecksumSHA256},
|
||||
{name: "inherited", ext: ".bin", data: []byte("stored encrypted checksum"), inherited: hash.ChecksumCRC32},
|
||||
{name: "small", ext: ".bin", data: []byte("abc")},
|
||||
{name: "two-packages", ext: ".bin", data: large},
|
||||
{name: "compressed", ext: ".txt", data: large},
|
||||
}
|
||||
pairs := []struct{ src, dst string }{
|
||||
{"plain", "s3"},
|
||||
{"s3", "plain"},
|
||||
{"s3", "s3"},
|
||||
{"plain", "c"},
|
||||
{"c", "plain"},
|
||||
{"c", "c"},
|
||||
{"s3", "c"},
|
||||
{"plain", "kms"},
|
||||
{"kms", "plain"},
|
||||
{"kms", "kms"},
|
||||
{"plain", "kms-context"},
|
||||
{"kms-context", "kms-context"},
|
||||
{"kms-context", "kms"},
|
||||
{"kms-context", "kms-empty-context"},
|
||||
}
|
||||
const srcKeyByte, dstKeyByte = 0x11, 0x22
|
||||
|
||||
for _, body := range bodies {
|
||||
for _, pair := range pairs {
|
||||
// Focus empty and inherited-checksum cases on each encrypted kind.
|
||||
if body.name == "empty" || body.name == "empty-explicit" || body.name == "inherited" {
|
||||
if pair.src != pair.dst || pair.src == "kms-context" {
|
||||
continue
|
||||
}
|
||||
}
|
||||
t.Run(body.name+"/"+pair.src+"-to-"+pair.dst, func(t *testing.T) {
|
||||
prefix := "federation/sse-" + body.name + "-" + pair.src + "-to-" + pair.dst
|
||||
srcObject, dstObject := prefix+"-source"+body.ext, prefix+"-destination"+body.ext
|
||||
|
||||
sourceHeaders := federationSSEHeaders(pair.src, srcKeyByte, false)
|
||||
if pair.src == "kms-context" {
|
||||
sourceHeaders[xhttp.AmzServerSideEncryptionKmsContext] = base64.StdEncoding.EncodeToString([]byte(`{"tenant":"source"}`))
|
||||
}
|
||||
if body.inherited.IsSet() {
|
||||
sourceHeaders[body.inherited.Key()] = mustChecksum(t, body.inherited, body.data)
|
||||
}
|
||||
putCopyChecksumSource(t, apiRouter, credentials, bucketName, srcObject, body.data, sourceHeaders)
|
||||
before, err := objectAPI.GetObjectInfo(t.Context(), bucketName, srcObject, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("%s: GetObjectInfo(source) failed: %v", instanceType, err)
|
||||
}
|
||||
if got, want := federationStoredSSE(before.UserDefined), strings.Split(pair.src, "-")[0]; got != want {
|
||||
t.Fatalf("%s: source stored as %s, want %s", instanceType, got, want)
|
||||
}
|
||||
if compressed := body.ext == ".txt" && pair.src != "c"; before.IsCompressed() != compressed {
|
||||
t.Fatalf("%s: source compressed=%v, want %v", instanceType, before.IsCompressed(), compressed)
|
||||
}
|
||||
assertFederationKMSContext(t, before, sourceHeaders[xhttp.AmzServerSideEncryptionKmsContext])
|
||||
|
||||
if body.inherited.IsSet() {
|
||||
sourceKeys := make(http.Header)
|
||||
for k, v := range federationSSEHeaders(pair.src, srcKeyByte, true) {
|
||||
sourceKeys.Set(k, v)
|
||||
}
|
||||
assertCopyChecksum(t, objectAPI, bucketName, srcObject, body.inherited, body.data, false, sourceKeys)
|
||||
}
|
||||
headers := federationSSEHeaders(pair.dst, dstKeyByte, false)
|
||||
if body.requested.IsSet() {
|
||||
headers[xhttp.AmzChecksumAlgo] = body.requested.String()
|
||||
}
|
||||
maps.Copy(headers, federationSSEHeaders(pair.src, srcKeyByte, true))
|
||||
rec := federatedCopyRequest(t, apiRouter, credentials, bucketName, srcObject, remoteBucket, dstObject, headers)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: federated CopyObject failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
wantChecksum := hash.ChecksumCRC64NVME
|
||||
if body.requested.IsSet() {
|
||||
wantChecksum = body.requested
|
||||
} else if body.inherited.IsSet() {
|
||||
wantChecksum = body.inherited
|
||||
}
|
||||
var getHeaders map[string]string
|
||||
if pair.dst == "c" {
|
||||
getHeaders = federationSSEHeaders("c", dstKeyByte, false)
|
||||
}
|
||||
after := assertFederationCopyReadback(t, objectAPI, apiRouter, credentials, remoteBucket, dstObject,
|
||||
rec, wantChecksum, body.data, body.ext == ".txt" && pair.dst != "c", getHeaders)
|
||||
assertFederationKMSContext(t, after, headers[xhttp.AmzServerSideEncryptionKmsContext])
|
||||
// A second encryption layer would add its own DARE overhead.
|
||||
if got, want := federationStoredSSE(after.UserDefined), strings.Split(pair.dst, "-")[0]; got != want {
|
||||
t.Fatalf("%s: destination stored as %s, want %s", instanceType, got, want)
|
||||
}
|
||||
if pair.dst != "plain" && !after.IsCompressed() {
|
||||
once := ObjectInfo{Size: int64(len(body.data))}
|
||||
if want := once.EncryptedSize(); after.Size != want {
|
||||
t.Fatalf("%s: destination stored %d bytes, want %d for %d bytes encrypted once",
|
||||
instanceType, after.Size, want, len(body.data))
|
||||
}
|
||||
}
|
||||
|
||||
// The source must be untouched.
|
||||
source, err := objectAPI.GetObjectInfo(t.Context(), bucketName, srcObject, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatalf("%s: GetObjectInfo(source) after the copy failed: %v", instanceType, err)
|
||||
}
|
||||
if source.Size != before.Size || source.ETag != before.ETag || !source.ModTime.Equal(before.ModTime) {
|
||||
t.Fatalf("%s: federated copy modified its source: size %d->%d etag %s->%s",
|
||||
instanceType, before.Size, source.Size, before.ETag, source.ETag)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// Multipart sources cross an encryption boundary per part. SHA256 also
|
||||
// exercises promotion from a stored composite to a full-object checksum.
|
||||
parts := [][]byte{bytes.Repeat([]byte("p"), globalMinPartSize+1), []byte("q!")}
|
||||
data := bytes.Join(parts, nil)
|
||||
for _, pair := range []struct {
|
||||
src, dst string
|
||||
composite bool
|
||||
}{
|
||||
{src: "s3", dst: "plain"},
|
||||
{src: "s3", dst: "s3"},
|
||||
{src: "c", dst: "c"},
|
||||
{src: "kms", dst: "kms", composite: true},
|
||||
} {
|
||||
t.Run("multipart/"+pair.src+"-to-"+pair.dst, func(t *testing.T) {
|
||||
srcObject, dstObject := "federation/multipart-source-"+pair.src+"-"+pair.dst+".bin", "federation/multipart-destination-"+pair.src+"-"+pair.dst+".bin"
|
||||
sourceHeaders := federationSSEHeaders(pair.src, srcKeyByte, false)
|
||||
wantChecksum := hash.ChecksumCRC64NVME
|
||||
if pair.composite {
|
||||
wantChecksum = hash.ChecksumSHA256
|
||||
sourceHeaders[xhttp.AmzChecksumAlgo] = wantChecksum.String()
|
||||
sourceHeaders[xhttp.AmzChecksumType] = xhttp.AmzChecksumTypeComposite
|
||||
}
|
||||
putFederationMultipartSource(t, apiRouter, credentials, bucketName, srcObject, parts, sourceHeaders)
|
||||
before, err := objectAPI.GetObjectInfo(t.Context(), bucketName, srcObject, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(before.Parts) != len(parts) || federationStoredSSE(before.UserDefined) != pair.src {
|
||||
t.Fatalf("source has %d parts stored as %s, want %d parts as %s", len(before.Parts), federationStoredSSE(before.UserDefined), len(parts), pair.src)
|
||||
}
|
||||
if pair.composite {
|
||||
checksums, _ := before.decryptChecksums(0, nil)
|
||||
if checksums[xhttp.AmzChecksumType] != xhttp.AmzChecksumTypeComposite || !strings.HasSuffix(checksums[wantChecksum.String()], "-2") {
|
||||
t.Fatalf("source did not persist a two-part composite checksum: %v", checksums)
|
||||
}
|
||||
}
|
||||
headers := federationSSEHeaders(pair.dst, dstKeyByte, false)
|
||||
maps.Copy(headers, federationSSEHeaders(pair.src, srcKeyByte, true))
|
||||
rec := federatedCopyRequest(t, apiRouter, credentials, bucketName, srcObject, remoteBucket, dstObject, headers)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("%s: federated CopyObject failed: %d %s", instanceType, rec.Code, rec.Body.String())
|
||||
}
|
||||
var getHeaders map[string]string
|
||||
if pair.dst == "c" {
|
||||
getHeaders = federationSSEHeaders("c", dstKeyByte, false)
|
||||
}
|
||||
after := assertFederationCopyReadback(t, objectAPI, apiRouter, credentials, remoteBucket, dstObject, rec, wantChecksum, data, false, getHeaders)
|
||||
if got := federationStoredSSE(after.UserDefined); got != pair.dst {
|
||||
t.Fatalf("destination stored as %s, want %s", got, pair.dst)
|
||||
}
|
||||
if once := (ObjectInfo{Size: int64(len(data))}); pair.dst != "plain" && after.Size != once.EncryptedSize() {
|
||||
t.Fatalf("destination stored %d bytes, want %d for %d bytes encrypted once", after.Size, once.EncryptedSize(), len(data))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,243 @@
|
||||
// Copyright (c) 2026 PGSTY
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"io"
|
||||
"maps"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
miniogo "github.com/minio/minio-go/v7"
|
||||
"github.com/minio/minio-go/v7/pkg/credentials"
|
||||
"github.com/minio/minio/internal/amztime"
|
||||
"github.com/minio/minio/internal/auth"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
"github.com/minio/minio/internal/kms"
|
||||
)
|
||||
|
||||
// Exercise the selected SDK's actual retry loop and concurrent calls sharing a
|
||||
// transport. Timestamps must follow the final PUT response, never a location
|
||||
// probe, another operation, a failed attempt, or the HTTP Date header.
|
||||
func TestFederatedWriteTimeTransport(t *testing.T) {
|
||||
var mu sync.Mutex
|
||||
attempts := make(map[string]int)
|
||||
written := time.Date(2001, 2, 3, 4, 5, 6, 123456789, time.UTC)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = io.Copy(io.Discard, r.Body)
|
||||
w.Header().Set(federatedLastModified, written.Add(-time.Hour).Format(time.RFC3339Nano))
|
||||
if r.Method == http.MethodGet && r.URL.Query().Has("location") {
|
||||
_, _ = io.WriteString(w, `<LocationConstraint>us-east-1</LocationConstraint>`)
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodPut {
|
||||
t.Errorf("unexpected follow-up read: %s %s", r.Method, r.URL)
|
||||
w.WriteHeader(http.StatusForbidden)
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
attempts[r.URL.Path]++
|
||||
attempt := attempts[r.URL.Path]
|
||||
mu.Unlock()
|
||||
if strings.Contains(r.URL.Path, "retry-") && attempt == 1 {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
_, _ = io.WriteString(w, `<Error><Code>SlowDown</Code></Error>`)
|
||||
return
|
||||
}
|
||||
stamp := written.Add(time.Duration(len(r.URL.Path)) * time.Nanosecond)
|
||||
if r.URL.Query().Has("partNumber") {
|
||||
stamp = stamp.Add(time.Second)
|
||||
}
|
||||
w.Header().Set(federatedLastModified, stamp.Format(time.RFC3339Nano))
|
||||
switch {
|
||||
case strings.HasSuffix(r.URL.Path, "missing"):
|
||||
w.Header().Del(federatedLastModified)
|
||||
case strings.HasSuffix(r.URL.Path, "malformed"):
|
||||
w.Header().Set(federatedLastModified, "invalid-time")
|
||||
}
|
||||
w.Header().Set("ETag", `"`+r.URL.Path+`"`)
|
||||
}))
|
||||
t.Cleanup(server.Close)
|
||||
core, err := miniogo.NewCore(server.Listener.Addr().String(), &miniogo.Options{
|
||||
Creds: credentials.NewStaticV4("federation", "federation-secret", ""),
|
||||
Transport: federatedWriteTransport{server.Client().Transport},
|
||||
BucketLookup: miniogo.BucketLookupPath,
|
||||
MaxRetries: 2,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for _, part := range []bool{false, true} {
|
||||
for _, scenario := range []string{"present", "missing", "malformed", "retry-present", "retry-missing", "retry-malformed"} {
|
||||
t.Run(fmt.Sprintf("part=%v/%s", part, scenario), func(t *testing.T) {
|
||||
t.Parallel()
|
||||
ctx, modified := withFederatedWriteTime(t.Context())
|
||||
object := fmt.Sprintf("part-%v/%s", part, scenario)
|
||||
var etag string
|
||||
if part {
|
||||
info, err := core.PutObjectPart(ctx, "bucket", object, "upload-id", 1, bytes.NewReader([]byte("abc")), 3, miniogo.PutObjectPartOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
etag = info.ETag
|
||||
} else {
|
||||
info, err := core.PutObject(ctx, "bucket", object, bytes.NewReader([]byte("abc")), 3, "", "", miniogo.PutObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
etag = info.ETag
|
||||
}
|
||||
want := time.Time{}
|
||||
if strings.HasSuffix(scenario, "present") {
|
||||
want = written.Add(time.Duration(len("/bucket/"+object)) * time.Nanosecond)
|
||||
if part {
|
||||
want = want.Add(time.Second)
|
||||
}
|
||||
}
|
||||
if !modified.Equal(want) || etag != "/bucket/"+object {
|
||||
t.Errorf("write result: time=%s ETag=%s, want time=%s ETag=/bucket/%s", modified, etag, want, object)
|
||||
}
|
||||
mu.Lock()
|
||||
count := attempts["/bucket/"+object]
|
||||
mu.Unlock()
|
||||
wantAttempts := 1
|
||||
if strings.HasPrefix(scenario, "retry-") {
|
||||
wantAttempts = 2
|
||||
}
|
||||
if count != wantAttempts {
|
||||
t.Errorf("PUT attempts = %d, want %d", count, wantAttempts)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIFederatedCopyWriteTimeSSEAndCompatibility(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
endpoints: []string{"CopyObjectPart", "NewMultipart", "PutObjectPart", "ListObjectParts", "CompleteMultipart", "CopyObject", "PutObject", "GetObject"},
|
||||
objAPITest: func(obj ObjectLayer, instanceType, bucket string, router http.Handler, cred auth.Credentials, t *testing.T) {
|
||||
testKMS, err := kms.NewBuiltin(federationTestKMSKeyID, bytes.Repeat([]byte{0x58}, 32))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
previous := GlobalKMS
|
||||
GlobalKMS = testKMS
|
||||
defer func() { GlobalKMS = previous }()
|
||||
for _, mode := range []string{"current", "missing", "malformed"} {
|
||||
t.Run(mode, func(t *testing.T) {
|
||||
remote, _, cleanup := setupCopyObjectFederationRemote(t, obj, router, instanceType, bucket, true, func(h http.Header) {
|
||||
switch mode {
|
||||
case "missing":
|
||||
h.Del(federatedLastModified)
|
||||
case "malformed":
|
||||
h.Set(federatedLastModified, "invalid-time")
|
||||
}
|
||||
})
|
||||
defer cleanup()
|
||||
for _, kind := range []string{"plain", "s3", "c", "kms"} {
|
||||
if mode != "current" && kind != "plain" && kind != "c" {
|
||||
continue
|
||||
}
|
||||
t.Run(kind, func(t *testing.T) {
|
||||
data := []byte("federated write timestamp")
|
||||
putCopyChecksumSource(t, router, cred, bucket, "source", data, federationSSEHeaders(kind, 0x11, false))
|
||||
headers := federationSSEHeaders(kind, 0x22, false)
|
||||
maps.Copy(headers, federationSSEHeaders(kind, 0x11, true))
|
||||
rec := federatedCopyRequest(t, router, cred, bucket, "source", remote, kind+"-copy", headers)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("CopyObject: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
info, err := obj.GetObjectInfo(t.Context(), remote, kind+"-copy", ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
var copied CopyObjectResponse
|
||||
if err := xml.Unmarshal(rec.Body.Bytes(), &copied); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
assertTime := func(got string, stored time.Time) {
|
||||
t.Helper()
|
||||
if stored.IsZero() {
|
||||
t.Fatal("storage returned a zero timestamp")
|
||||
}
|
||||
if mode != "current" {
|
||||
stored = time.Time{}
|
||||
}
|
||||
if got != amztime.ISO8601Format(stored.UTC()) {
|
||||
t.Errorf("copy time = %q, want %q", got, amztime.ISO8601Format(stored.UTC()))
|
||||
}
|
||||
}
|
||||
assertTime(copied.LastModified, info.ModTime)
|
||||
|
||||
object := kind + "-multipart"
|
||||
req, err := newTestSignedRequestV4(http.MethodPost, getNewMultipartURL("", remote, object), 0, nil,
|
||||
cred.AccessKey, cred.SecretKey, federationSSEHeaders(kind, 0x22, false))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec = httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("NewMultipartUpload: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var upload InitiateMultipartUploadResponse
|
||||
if err := xml.Unmarshal(rec.Body.Bytes(), &upload); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
// UploadPartCopy selects KMS/S3 encryption from the upload;
|
||||
// only SSE-C keys accompany the part request. The replica
|
||||
// markers must still take the ordinary decrypting copy path.
|
||||
headers = federationSSEHeaders(kind, 0x11, true)
|
||||
var keys map[string]string
|
||||
if kind == "c" {
|
||||
keys = federationSSEHeaders("c", 0x22, false)
|
||||
maps.Copy(headers, keys)
|
||||
}
|
||||
headers[xhttp.AmzCopySource] = SlashSeparator + pathJoin(bucket, "source")
|
||||
headers[xhttp.MinIOSourceReplicationRequest] = "true"
|
||||
headers[xhttp.AmzBucketReplicationStatus] = "REPLICA"
|
||||
req, err = newTestSignedRequestV4(http.MethodPut, getCopyObjectPartURL("", remote, object, upload.UploadID, "1"), 0, nil, cred.AccessKey, cred.SecretKey, headers)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec = httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("UploadPartCopy: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
var part CopyObjectPartResponse
|
||||
if err := xml.Unmarshal(rec.Body.Bytes(), &part); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
parts, err := obj.ListObjectParts(t.Context(), remote, object, upload.UploadID, 0, 100, ObjectOptions{})
|
||||
if err != nil || len(parts.Parts) != 1 {
|
||||
t.Fatalf("stored part: %v, %v", parts, err)
|
||||
}
|
||||
assertTime(part.LastModified, parts.Parts[0].LastModified)
|
||||
rec = completePartsHTTP(t, router, cred, remote, object, upload.UploadID, []CompletePart{{PartNumber: 1, ETag: canonicalizeETag(part.ETag)}}, keys)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("CompleteMultipartUpload: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
for _, name := range []string{kind + "-copy", object} {
|
||||
got := federationGetObject(t, router, cred, remote, name, keys)
|
||||
if got.Code != http.StatusOK || !bytes.Equal(got.Body.Bytes(), data) {
|
||||
t.Fatalf("readback %s: %d %s", name, got.Code, got.Body.String())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -36,6 +36,44 @@ import (
|
||||
|
||||
var etagRegex = regexp.MustCompile("\"*?([^\"]*?)\"*?$")
|
||||
|
||||
// federatedLastModified carries the committed object/part time on the write
|
||||
// response. HTTP Date is a response time and Last-Modified loses subsecond
|
||||
// precision, so neither can supply CopyObject/UploadPartCopy's timestamp.
|
||||
const federatedLastModified = "X-Minio-Last-Modified"
|
||||
|
||||
type federatedWriteTimeKey struct{}
|
||||
|
||||
// withFederatedWriteTime allocates one result per SDK operation. SDK retries
|
||||
// run sequentially with this context; concurrent copies never share the result.
|
||||
func withFederatedWriteTime(ctx context.Context) (context.Context, *time.Time) {
|
||||
modified := new(time.Time)
|
||||
return context.WithValue(ctx, federatedWriteTimeKey{}, modified), modified
|
||||
}
|
||||
|
||||
type federatedWriteTransport struct {
|
||||
http.RoundTripper
|
||||
}
|
||||
|
||||
func (t federatedWriteTransport) RoundTrip(r *http.Request) (*http.Response, error) {
|
||||
resp, err := t.RoundTripper.RoundTrip(r)
|
||||
if modified, ok := r.Context().Value(federatedWriteTimeKey{}).(*time.Time); ok && r.Method == http.MethodPut {
|
||||
// Replace on every attempt, including a success from an older target
|
||||
// without the header. Never retain a failed attempt's timestamp or fail
|
||||
// a committed write just because its timestamp is unavailable.
|
||||
*modified = time.Time{}
|
||||
if err == nil && resp != nil && resp.StatusCode == http.StatusOK {
|
||||
*modified, _ = time.Parse(time.RFC3339Nano, resp.Header.Get(federatedLastModified))
|
||||
}
|
||||
}
|
||||
return resp, err
|
||||
}
|
||||
|
||||
func setFederatedWriteTime(w http.ResponseWriter, r *http.Request, modified time.Time) {
|
||||
if isFederatedInternalRequest(r.UserAgent()) && !modified.IsZero() {
|
||||
w.Header().Set(federatedLastModified, modified.UTC().Format(time.RFC3339Nano))
|
||||
}
|
||||
}
|
||||
|
||||
// Validates the preconditions for CopyObjectPart, returns true if CopyObjectPart
|
||||
// operation should not proceed. Preconditions supported are:
|
||||
//
|
||||
|
||||
+86
-29
@@ -1205,12 +1205,20 @@ const federatedInternalAppName = "minio-federated"
|
||||
// Applicable only in a federated deployment
|
||||
var getRemoteInstanceClient = func(r *http.Request, host string) (*miniogo.Core, error) {
|
||||
cred := getReqAccessCred(r, globalSite.Region())
|
||||
transport := getRemoteInstanceTransport()
|
||||
if transport == nil {
|
||||
var err error
|
||||
transport, err = miniogo.DefaultTransport(globalIsTLS)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
// In a federated deployment, all the instances share config files
|
||||
// and hence expected to have same credentials.
|
||||
core, err := miniogo.NewCore(host, &miniogo.Options{
|
||||
Creds: credentials.NewStaticV4(cred.AccessKey, cred.SecretKey, ""),
|
||||
Secure: globalIsTLS,
|
||||
Transport: getRemoteInstanceTransport(),
|
||||
Transport: federatedWriteTransport{transport},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
@@ -1404,11 +1412,27 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
}
|
||||
allowReplicationMetadata := replicaTrusted
|
||||
|
||||
// Check if bucket encryption is enabled
|
||||
sseConfig, _ := globalBucketSSEConfigSys.Get(dstBucket)
|
||||
sseConfig.Apply(r.Header, sse.ApplyOptions{
|
||||
AutoEncrypt: globalAutoEncryption,
|
||||
})
|
||||
// Federation only: the destination bucket lives on another deployment and
|
||||
// the copy is forwarded to it as a PutObject. That remote write owns the
|
||||
// destination's storage transformations, so this handler hands it the
|
||||
// logical (decompressed, decrypted) bytes at their logical size and lets
|
||||
// the remote compress and encrypt once. Encrypting here as well would
|
||||
// forward ciphertext under the destination's own SSE option, which either
|
||||
// fails the length check or, for SSE to SSE, has the remote encrypt the
|
||||
// ciphertext a second time and store an unreadable object (#158).
|
||||
remoteCallRequired := isRemoteCopyRequired(ctx, srcBucket, dstBucket, objectAPI)
|
||||
|
||||
// Apply the destination bucket's default encryption only when this
|
||||
// deployment writes the destination. For a remote destination the proxy
|
||||
// has no authority over that bucket's defaults: applying its own here
|
||||
// would forward an explicit SSE header that the remote then honors in
|
||||
// place of the destination's configuration (#167).
|
||||
if !remoteCallRequired {
|
||||
sseConfig, _ := globalBucketSSEConfigSys.Get(dstBucket)
|
||||
sseConfig.Apply(r.Header, sse.ApplyOptions{
|
||||
AutoEncrypt: globalAutoEncryption,
|
||||
})
|
||||
}
|
||||
var srcOpts, dstOpts ObjectOptions
|
||||
srcOpts, err = copySrcOpts(ctx, r, srcBucket, srcObject)
|
||||
if err != nil {
|
||||
@@ -1473,6 +1497,12 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
}
|
||||
defer gr.Close()
|
||||
srcInfo := gr.ObjInfo
|
||||
// A trusted SSE-C replica reads raw ciphertext. Federation's ordinary PUT
|
||||
// expects plaintext and does not forward the replica's sealed-key metadata.
|
||||
if remoteCallRequired && replicaTrusted && crypto.SSEC.IsEncrypted(srcInfo.UserDefined) {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, NotImplemented{Message: "federated raw SSE-C replica CopyObject is not supported"}), r.URL)
|
||||
return
|
||||
}
|
||||
|
||||
// maximum Upload size for object in a single CopyObject operation.
|
||||
if isMaxObjectSize(srcInfo.Size) {
|
||||
@@ -1523,7 +1553,7 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
// Pass the decompressed stream to such calls.
|
||||
isDstCompressed := isCompressible(r.Header, dstObject) &&
|
||||
length > minCompressibleSize &&
|
||||
!isRemoteCopyRequired(ctx, srcBucket, dstBucket, objectAPI)
|
||||
!remoteCallRequired
|
||||
if isDstCompressed {
|
||||
compressMetadata = make(map[string]string, 2)
|
||||
// Preserving the compression metadata.
|
||||
@@ -1652,6 +1682,9 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
var targetSize int64
|
||||
|
||||
switch {
|
||||
case remoteCallRequired:
|
||||
// The remote receives the logical bytes, see above.
|
||||
targetSize = actualSize
|
||||
case isDstCompressed:
|
||||
targetSize = -1
|
||||
case !isSourceEncrypted && !isTargetEncrypted:
|
||||
@@ -1722,7 +1755,7 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
pReader.setChecksumReader(checksumReader)
|
||||
}
|
||||
|
||||
if isTargetEncrypted {
|
||||
if isTargetEncrypted && !remoteCallRequired {
|
||||
var encReader io.Reader
|
||||
kind, _ := crypto.IsRequested(r.Header)
|
||||
encReader, objEncKey, err = newEncryptReader(ctx, srcInfo.Reader, kind, newKeyID, newKey, dstBucket, dstObject, encMetadata, kmsCtx)
|
||||
@@ -1746,7 +1779,7 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
return
|
||||
}
|
||||
|
||||
if isTargetEncrypted {
|
||||
if isTargetEncrypted && !remoteCallRequired {
|
||||
pReader, err = pReader.WithEncryption(srcInfo.Reader, &objEncKey)
|
||||
if err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
@@ -1813,6 +1846,7 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
applyReplicatedObjectLock(srcInfo.UserDefined, storedLock, replicaTrusted,
|
||||
retentionMode, retentionDate, legalHold,
|
||||
dstOpts.ReplicationSourceRetentionTimestamp, dstOpts.ReplicationSourceLegalholdTimestamp)
|
||||
dstOpts.ReplicaLockReconcile = replicaTrusted && dstOpts.VersionID != ""
|
||||
|
||||
if replicaTrusted {
|
||||
// An SSE-C key rotation snapshots every stored reserved key into
|
||||
@@ -1899,9 +1933,6 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
srcInfo.metadataOnly = false
|
||||
}
|
||||
|
||||
// Federation only.
|
||||
remoteCallRequired := isRemoteCopyRequired(ctx, srcBucket, dstBucket, objectAPI)
|
||||
|
||||
var objInfo ObjectInfo
|
||||
var os *objSweeper
|
||||
if remoteCallRequired {
|
||||
@@ -1935,10 +1966,23 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
delete(srcInfo.UserDefined, k)
|
||||
}
|
||||
}
|
||||
// Forward a clone: request-only keys are removed or added below and
|
||||
// srcInfo.UserDefined stays the resolved record for the response.
|
||||
forwardedMeta := cloneMSS(srcInfo.UserDefined)
|
||||
// minio-go prefixes any UserMetadata key it does not recognize with
|
||||
// x-amz-meta-, and it recognizes the retention headers but not
|
||||
// x-amz-object-lock-legal-hold, so a hold left in the map reaches the
|
||||
// remote as user metadata and is silently dropped (#166). Carry it on
|
||||
// the typed option instead. Retention stays in the map: the typed
|
||||
// RetainUntilDate would truncate the date to whole seconds.
|
||||
legalHoldKey := strings.ToLower(xhttp.AmzObjectLockLegalHold)
|
||||
forwardedLegalHold := forwardedMeta[legalHoldKey]
|
||||
delete(forwardedMeta, legalHoldKey)
|
||||
opts := miniogo.PutObjectOptions{
|
||||
UserMetadata: srcInfo.UserDefined,
|
||||
UserMetadata: forwardedMeta,
|
||||
ServerSideEncryption: dstOpts.ServerSideEncryption,
|
||||
UserTags: tag.ToMap(),
|
||||
LegalHold: miniogo.LegalHoldStatus(forwardedLegalHold),
|
||||
}
|
||||
// The destination must carry the same checksum the local path would
|
||||
// produce; the federated path has the remote compute, validate, persist
|
||||
@@ -1948,7 +1992,7 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
var checksumHeaderValue string
|
||||
switch {
|
||||
case wantChecksumType.IsSet():
|
||||
if srcInfo.Size == 0 {
|
||||
if actualSize == 0 {
|
||||
// minio-go streams no trailing checksum for an empty body, so the
|
||||
// remote would compute none, the bind below would fail, and every
|
||||
// empty-object federated copy would 500. Forward the empty-content
|
||||
@@ -1977,19 +2021,30 @@ func (api objectAPIHandlers) CopyObjectHandler(w http.ResponseWriter, r *http.Re
|
||||
if checksumHeaderValue != "" {
|
||||
opts.UserMetadata[wantChecksumType.Key()] = checksumHeaderValue
|
||||
}
|
||||
remoteObjInfo, rerr := core.PutObject(ctx, dstBucket, dstObject, srcInfo.Reader,
|
||||
srcInfo.Size, "", "", opts)
|
||||
// For an ordinary federated copy, actualSize is the logical plaintext
|
||||
// length to declare. srcInfo.Size is not a reliable wire length because
|
||||
// the read path may already have adjusted it.
|
||||
writeCtx, modified := withFederatedWriteTime(ctx)
|
||||
remoteObjInfo, rerr := core.PutObject(writeCtx, dstBucket, dstObject, srcInfo.Reader,
|
||||
actualSize, "", "", opts)
|
||||
if rerr != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, rerr), r.URL)
|
||||
return
|
||||
}
|
||||
objInfo.UserDefined = cloneMSS(opts.UserMetadata)
|
||||
// A forwarded checksum header is a request detail, not object metadata.
|
||||
if checksumHeaderValue != "" {
|
||||
delete(objInfo.UserDefined, wantChecksumType.Key())
|
||||
}
|
||||
// Keep the resolved legal hold in response and event metadata; the
|
||||
// request-only checksum header exists only in the forwarding map.
|
||||
objInfo.UserDefined = cloneMSS(srcInfo.UserDefined)
|
||||
// The response headers and the ObjectCreated:Copy event describe the
|
||||
// object this handler wrote, so name it: without these the response
|
||||
// carries no x-amz-version-id and the event has an empty key and zero
|
||||
// size (#170). Size is the logical size the remote was handed, which is
|
||||
// what it reports back.
|
||||
objInfo.Bucket = dstBucket
|
||||
objInfo.Name = dstObject
|
||||
objInfo.Size = actualSize
|
||||
objInfo.VersionID = remoteObjInfo.VersionID
|
||||
objInfo.ETag = remoteObjInfo.ETag
|
||||
objInfo.ModTime = remoteObjInfo.LastModified
|
||||
objInfo.ModTime = *modified
|
||||
// Bind the checksum the remote computed for this exact write. A single
|
||||
// forwarded PutObject must yield a full-object digest, so reject a
|
||||
// missing, malformed, or multipart-marked ("-N") value rather than
|
||||
@@ -2375,10 +2430,8 @@ func (api objectAPIHandlers) PutObjectHandler(w http.ResponseWriter, r *http.Req
|
||||
// The decision above orders against the version as read here; let the
|
||||
// object layer re-run it against the version read under the write lock
|
||||
// that guards the replacement, so a newer hold or retention committed in
|
||||
// between is not rolled back (issue #120). Scoped to the SSE-C replica
|
||||
// retransmit this issue enables, keyed on the incoming write's restored
|
||||
// SSE-C seal, the same predicate as the duplicate-version exemption.
|
||||
opts.ReplicaLockReconcile = isReplicaTrusted(ctx) && opts.VersionID != "" && crypto.SSEC.IsEncrypted(metadata)
|
||||
// between is not rolled back, across all pools and encryption modes.
|
||||
opts.ReplicaLockReconcile = isReplicaTrusted(ctx) && opts.VersionID != ""
|
||||
}
|
||||
if s3Err != ErrNone {
|
||||
writeErrorResponse(ctx, w, errorCodes.ToAPIErr(s3Err), r.URL)
|
||||
@@ -2493,6 +2546,7 @@ func (api objectAPIHandlers) PutObjectHandler(w http.ResponseWriter, r *http.Req
|
||||
}
|
||||
|
||||
setPutObjHeaders(w, objInfo, false, r.Header)
|
||||
setFederatedWriteTime(w, r, objInfo.ModTime)
|
||||
|
||||
// Notify object created event.
|
||||
evt := eventArgs{
|
||||
@@ -3645,9 +3699,6 @@ func (api objectAPIHandlers) PutObjectTaggingHandler(w http.ResponseWriter, r *h
|
||||
}
|
||||
tagsStr := tags.String()
|
||||
|
||||
// Set this such that authorization policies can be applied on the object tags.
|
||||
r.Header.Set(xhttp.AmzObjectTagging, tagsStr)
|
||||
|
||||
logger.GetReqInfo(ctx).BucketName = bucket
|
||||
logger.GetReqInfo(ctx).ObjectName = object
|
||||
if s3Error := authenticateRequest(ctx, r, policy.PutObjectTaggingAction); s3Error != ErrNone {
|
||||
@@ -3655,6 +3706,12 @@ func (api objectAPIHandlers) PutObjectTaggingHandler(w http.ResponseWriter, r *h
|
||||
return
|
||||
}
|
||||
|
||||
// Set this such that authorization policies can be applied on the object
|
||||
// tags. This is derived from the request body, so it must be injected only
|
||||
// after signature verification: the SigV4 verifier now rejects unsigned
|
||||
// x-amz-* request headers, and this synthesized header is never signed.
|
||||
r.Header.Set(xhttp.AmzObjectTagging, tagsStr)
|
||||
|
||||
opts, err := getOpts(ctx, r, bucket, object)
|
||||
if err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
|
||||
@@ -1799,6 +1799,12 @@ func testAPICopyObjectPartHandlerSanity(obj ObjectLayer, instanceType, bucketNam
|
||||
req.Header.Set("X-Amz-Copy-Source", url.QueryEscape(pathJoin(bucketName, objectName)))
|
||||
req.Header.Set("X-Amz-Copy-Source-Range", fmt.Sprintf("bytes=%d-%d", a, b))
|
||||
|
||||
// Re-sign so the copy-source x-amz-* headers are covered by the
|
||||
// signature, as real clients do; the verifier rejects unsigned x-amz-*.
|
||||
if err = signRequestV4(req, credentials.AccessKey, credentials.SecretKey); err != nil {
|
||||
t.Fatalf("Test failed to re-sign HTTP request for copy object part: <ERROR> %v", err)
|
||||
}
|
||||
|
||||
// Since `apiRouter` satisfies `http.Handler` it has a ServeHTTP to execute the logic of the handler.
|
||||
// Call the ServeHTTP to execute the handler, `func (api objectAPIHandlers) CopyObjectHandler` handles the request.
|
||||
a = globalMinPartSize + 1
|
||||
@@ -2200,6 +2206,15 @@ func testAPICopyObjectPartHandler(obj ObjectLayer, instanceType, bucketName stri
|
||||
}
|
||||
}
|
||||
|
||||
// Re-sign so the copy-source x-amz-* headers set above are covered by
|
||||
// the signature, as real clients do; the verifier rejects unsigned
|
||||
// x-amz-* headers.
|
||||
if testCase.accessKey != "" && testCase.secretKey != "" {
|
||||
if err = signRequestV4(req, testCase.accessKey, testCase.secretKey); err != nil {
|
||||
t.Fatalf("Test %d: Failed to re-sign HTTP request for copy Object: <ERROR> %v", i+1, err)
|
||||
}
|
||||
}
|
||||
|
||||
// Since `apiRouter` satisfies `http.Handler` it has a ServeHTTP to execute the logic of the handler.
|
||||
// Call the ServeHTTP to execute the handler, `func (api objectAPIHandlers) CopyObjectHandler` handles the request.
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
@@ -2626,6 +2641,16 @@ func testAPICopyObjectHandler(obj ObjectLayer, instanceType, bucketName string,
|
||||
if testCase.metadataGarbage {
|
||||
req.Header.Set("X-Amz-Metadata-Directive", "Unknown")
|
||||
}
|
||||
// The x-amz-copy-source and related x-amz-* headers set above must be
|
||||
// part of the SigV4 signature, exactly as real S3 clients send them.
|
||||
// Re-sign now that they are present; the verifier rejects unsigned
|
||||
// x-amz-* headers (an unsigned x-amz-copy-source could otherwise turn a
|
||||
// PUT grant into a server-side copy).
|
||||
if testCase.accessKey != "" && testCase.secretKey != "" {
|
||||
if err = signRequestV4(req, testCase.accessKey, testCase.secretKey); err != nil {
|
||||
t.Fatalf("Test %d: Failed to re-sign HTTP request for copy Object: <ERROR> %v", i, err)
|
||||
}
|
||||
}
|
||||
// Since `apiRouter` satisfies `http.Handler` it has a ServeHTTP to execute the logic of the handler.
|
||||
// Call the ServeHTTP to execute the handler, `func (api objectAPIHandlers) CopyObjectHandler` handles the request.
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
|
||||
@@ -0,0 +1,140 @@
|
||||
// Copyright (c) 2026 PGSTY
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio/internal/auth"
|
||||
objectlock "github.com/minio/minio/internal/bucket/object/lock"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
)
|
||||
|
||||
func setTestBucketDefaultRetention(t *testing.T, bucket, mode string) {
|
||||
t.Helper()
|
||||
enableBucketObjectLock(t, bucket)
|
||||
if mode == "" {
|
||||
return
|
||||
}
|
||||
meta, err := globalBucketMetadataSys.Get(bucket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
meta.ObjectLockConfigXML = fmt.Appendf(nil, `<ObjectLockConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"><ObjectLockEnabled>Enabled</ObjectLockEnabled><Rule><DefaultRetention><Mode>%s</Mode><Days>2</Days></DefaultRetention></Rule></ObjectLockConfiguration>`, mode)
|
||||
if err := meta.parseAllConfigs(t.Context(), newObjectLayerFn()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
globalBucketMetadataSys.Set(bucket, meta)
|
||||
}
|
||||
|
||||
func TestAPIObjectLockDefaultRetentionWithLegalHold(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
endpoints: []string{"NewMultipart", "PutObjectPart", "CompleteMultipart", "CopyObject", "PutObject", "DeleteObject"},
|
||||
objAPITest: func(obj ObjectLayer, instanceType, bucket string, router http.Handler, cred auth.Credentials, t *testing.T) {
|
||||
data := []byte("default retention and legal hold are independent")
|
||||
putCopyChecksumSource(t, router, cred, bucket, "source", data, nil)
|
||||
for _, mode := range []string{"GOVERNANCE", "COMPLIANCE", ""} {
|
||||
setTestBucketDefaultRetention(t, bucket, mode)
|
||||
for _, hold := range []string{"ON", "OFF"} {
|
||||
for _, operation := range []string{"put", "copy", "multipart"} {
|
||||
t.Run(instanceType+"/"+mode+"/"+hold+"/"+operation, func(t *testing.T) {
|
||||
object := mode + "-" + hold + "-" + operation
|
||||
headers := map[string]string{xhttp.AmzObjectLockLegalHold: hold}
|
||||
// The stored retention date carries millisecond precision.
|
||||
before := UTCNow().Truncate(time.Millisecond)
|
||||
switch operation {
|
||||
case "put":
|
||||
putCopyChecksumSource(t, router, cred, bucket, object, data, headers)
|
||||
case "copy":
|
||||
rec := federatedCopyRequest(t, router, cred, bucket, "source", bucket, object, headers)
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("copy: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
case "multipart":
|
||||
putFederationMultipartSource(t, router, cred, bucket, object, [][]byte{data}, headers)
|
||||
}
|
||||
info, err := obj.GetObjectInfo(t.Context(), bucket, object, ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
ret := objectlock.GetObjectRetentionMeta(info.UserDefined)
|
||||
if string(ret.Mode) != mode {
|
||||
t.Errorf("stored retention mode = %q, want %q", ret.Mode, mode)
|
||||
}
|
||||
if mode != "" && (ret.RetainUntilDate.Before(before.Add(48*time.Hour)) || ret.RetainUntilDate.After(UTCNow().Add(48*time.Hour))) {
|
||||
t.Errorf("default retention date = %s, want write time + 2 days", ret.RetainUntilDate)
|
||||
}
|
||||
if got := objectlock.GetObjectLegalHoldMeta(info.UserDefined).Status; string(got) != hold {
|
||||
t.Errorf("stored legal hold = %q, want %q", got, hold)
|
||||
}
|
||||
if mode == "COMPLIANCE" && hold == "OFF" {
|
||||
req, err := newTestSignedRequestV4(http.MethodDelete, getPutObjectURL("", bucket, object)+"?versionId="+info.VersionID, 0, nil, cred.AccessKey, cred.SecretKey, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusBadRequest || !strings.Contains(rec.Body.String(), "InvalidRequest") {
|
||||
t.Errorf("version DELETE must enforce retention: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func TestObjectLockDefaultRetentionBoundaries(t *testing.T) {
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: func(obj ObjectLayer, instanceType, bucket string, _ http.Handler, _ auth.Credentials, t *testing.T) {
|
||||
setTestBucketDefaultRetention(t, bucket, "COMPLIANCE")
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
replica, marker, explicit bool
|
||||
retentionErr, holdErr APIErrorCode
|
||||
wantMode objectlock.RetMode
|
||||
wantErr APIErrorCode
|
||||
}{
|
||||
{name: "trusted replica", replica: true},
|
||||
{name: "marker-only ordinary write", marker: true, wantMode: objectlock.RetCompliance},
|
||||
{name: "explicit retention", explicit: true, wantMode: objectlock.RetGovernance},
|
||||
{name: "retention permission denied", retentionErr: ErrAccessDenied, wantErr: ErrAccessDenied},
|
||||
{name: "legal hold permission denied", holdErr: ErrAccessDenied, wantErr: ErrAccessDenied},
|
||||
} {
|
||||
t.Run(instanceType+"/"+tc.name, func(t *testing.T) {
|
||||
r := httptest.NewRequest(http.MethodPut, "http://minio.local/"+bucket+"/object", nil)
|
||||
r.Header.Set(xhttp.AmzObjectLockLegalHold, "OFF")
|
||||
if tc.marker {
|
||||
r.Header.Set(xhttp.MinIOSourceReplicationRequest, "true")
|
||||
}
|
||||
until := UTCNow().Add(24 * time.Hour).Truncate(time.Second).Add(789 * time.Millisecond)
|
||||
if tc.explicit {
|
||||
r.Header.Set(xhttp.AmzObjectLockMode, "GOVERNANCE")
|
||||
r.Header.Set(xhttp.AmzObjectLockRetainUntilDate, until.Format(time.RFC3339Nano))
|
||||
}
|
||||
mode, date, _, code := checkPutObjectLockAllowed(t.Context(), r, bucket, "object", obj.GetObjectInfo, tc.retentionErr, tc.holdErr, tc.replica)
|
||||
if code != tc.wantErr || mode != tc.wantMode {
|
||||
t.Fatalf("got mode %s error %s, want mode %s error %s", mode, niceError(code), tc.wantMode, niceError(tc.wantErr))
|
||||
}
|
||||
if tc.explicit && !date.Equal(until) {
|
||||
t.Errorf("explicit retention lost precision: %s != %s", date, until)
|
||||
}
|
||||
if tc.replica && !date.IsZero() {
|
||||
t.Errorf("replica acquired a destination default: %s", date)
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -30,6 +30,7 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
miniogo "github.com/minio/minio-go/v7"
|
||||
miniocredentials "github.com/minio/minio-go/v7/pkg/credentials"
|
||||
@@ -51,7 +52,7 @@ func TestAPIFederatedUploadPartChecksumResponse(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func testAPIFederatedUploadPartChecksumResponse(_ ObjectLayer, instanceType, bucketName string,
|
||||
func testAPIFederatedUploadPartChecksumResponse(objectAPI ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
algorithms := []struct {
|
||||
@@ -101,6 +102,18 @@ func testAPIFederatedUploadPartChecksumResponse(_ ObjectLayer, instanceType, buc
|
||||
if got := rec.Header().Get(xhttp.AmzChecksumType); got != "" {
|
||||
t.Fatalf("%s: UploadPart returned checksum type %q", instanceType, got)
|
||||
}
|
||||
modified := rec.Header().Get(federatedLastModified)
|
||||
if userAgent.want {
|
||||
parts, err := objectAPI.ListObjectParts(t.Context(), bucketName, object, uploadID, 0, 100, ObjectOptions{})
|
||||
if err != nil || len(parts.Parts) != 1 {
|
||||
t.Fatalf("stored part: %v, %v", parts, err)
|
||||
}
|
||||
if modified != parts.Parts[0].LastModified.UTC().Format(time.RFC3339Nano) {
|
||||
t.Errorf("response time %q does not match committed part time %s", modified, parts.Parts[0].LastModified)
|
||||
}
|
||||
} else if modified != "" {
|
||||
t.Errorf("ordinary UploadPart exposed federation timestamp %q", modified)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -158,7 +171,7 @@ func TestAPIFederatedUploadPartChecksumConcurrentOverwrite(t *testing.T) {
|
||||
})
|
||||
}
|
||||
|
||||
func testAPIFederatedUploadPartChecksumConcurrentOverwrite(_ ObjectLayer, instanceType, bucketName string,
|
||||
func testAPIFederatedUploadPartChecksumConcurrentOverwrite(objectAPI ObjectLayer, instanceType, bucketName string,
|
||||
apiRouter http.Handler, credentials auth.Credentials, t *testing.T,
|
||||
) {
|
||||
object := "federation/concurrent-overwrite"
|
||||
@@ -194,6 +207,10 @@ func testAPIFederatedUploadPartChecksumConcurrentOverwrite(_ ObjectLayer, instan
|
||||
}
|
||||
close(start)
|
||||
wg.Wait()
|
||||
parts, err := objectAPI.ListObjectParts(t.Context(), bucketName, object, uploadID, 0, 100, ObjectOptions{})
|
||||
if err != nil || len(parts.Parts) != 1 {
|
||||
t.Fatalf("stored part: %v, %v", parts, err)
|
||||
}
|
||||
|
||||
for i, rec := range recorders {
|
||||
if rec.Code != http.StatusOK {
|
||||
@@ -213,6 +230,13 @@ func testAPIFederatedUploadPartChecksumConcurrentOverwrite(_ ObjectLayer, instan
|
||||
if want := hex.EncodeToString(md5sum[:]); canonicalizeETag(etags[0]) != want {
|
||||
t.Fatalf("%s: concurrent request %d ETag %q, want %q", instanceType, i, etags[0], want)
|
||||
}
|
||||
modified, err := time.Parse(time.RFC3339Nano, rec.Header().Get(federatedLastModified))
|
||||
if err != nil || modified.IsZero() {
|
||||
t.Fatalf("concurrent request %d returned invalid time %v: %v", i, modified, err)
|
||||
}
|
||||
if canonicalizeETag(etags[0]) == parts.Parts[0].ETag && !modified.Equal(parts.Parts[0].LastModified) {
|
||||
t.Errorf("surviving part has time %s, its writer returned %s", parts.Parts[0].LastModified, modified)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -352,6 +376,9 @@ func testAPIFederatedCopyObjectPartChecksum(objectAPI ObjectLayer, instanceType,
|
||||
if len(parts.Parts) != 1 {
|
||||
t.Fatalf("%s: ListParts returned %d parts, want 1", instanceType, len(parts.Parts))
|
||||
}
|
||||
if response.LastModified != parts.Parts[0].LastModified {
|
||||
t.Errorf("CopyPartResult time = %q, want stored part time %q", response.LastModified, parts.Parts[0].LastModified)
|
||||
}
|
||||
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)
|
||||
}
|
||||
|
||||
@@ -59,8 +59,8 @@ import (
|
||||
//
|
||||
// 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.
|
||||
// safe here because the only effect is returning the checksum and modification
|
||||
// time 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, "/")
|
||||
@@ -572,7 +572,8 @@ func (api objectAPIHandlers) CopyObjectPartHandler(w http.ResponseWriter, r *htt
|
||||
SSE: dstOpts.ServerSideEncryption,
|
||||
}
|
||||
|
||||
partInfo, err := core.PutObjectPart(ctx, dstBucket, dstObject, uploadID, partID, gr, length, popts)
|
||||
writeCtx, modified := withFederatedWriteTime(ctx)
|
||||
partInfo, err := core.PutObjectPart(writeCtx, dstBucket, dstObject, uploadID, partID, gr, length, popts)
|
||||
if err != nil {
|
||||
writeErrorResponse(ctx, w, toAPIError(ctx, err), r.URL)
|
||||
return
|
||||
@@ -580,7 +581,7 @@ func (api objectAPIHandlers) CopyObjectPartHandler(w http.ResponseWriter, r *htt
|
||||
|
||||
response := generateCopyObjectPartResponse(PartInfo{
|
||||
ETag: partInfo.ETag,
|
||||
LastModified: partInfo.LastModified,
|
||||
LastModified: *modified,
|
||||
ChecksumCRC32: partInfo.ChecksumCRC32,
|
||||
ChecksumCRC32C: partInfo.ChecksumCRC32C,
|
||||
ChecksumSHA1: partInfo.ChecksumSHA1,
|
||||
@@ -1082,6 +1083,7 @@ func (api objectAPIHandlers) PutObjectPartHandler(w http.ResponseWriter, r *http
|
||||
// checksum cannot be mixed with a concurrent overwrite.
|
||||
hash.AddChecksumHeader(w, partChecksumMap(partInfo))
|
||||
}
|
||||
setFederatedWriteTime(w, r, partInfo.LastModified)
|
||||
|
||||
writeSuccessResponseHeadersOnly(w)
|
||||
}
|
||||
|
||||
@@ -165,6 +165,11 @@ func testAPIZeroByteSSECAuthenticatesKey(obj ObjectLayer, instanceType, bucketNa
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set(xhttp.AmzCopySource, SlashSeparator+pathJoin(bucketName, object))
|
||||
// Re-sign so x-amz-copy-source is covered by the signature, as real S3
|
||||
// clients send it; the verifier rejects unsigned x-amz-* headers.
|
||||
if err = signRequestV4(req, credentials.AccessKey, credentials.SecretKey); err != nil {
|
||||
t.Fatalf("%s: failed to re-sign UploadPartCopy request: %v", instanceType, err)
|
||||
}
|
||||
rec = httptest.NewRecorder()
|
||||
apiRouter.ServeHTTP(rec, req)
|
||||
if rec.Code != http.StatusForbidden {
|
||||
|
||||
+20
-2
@@ -544,8 +544,26 @@ func (s *peerRESTServer) LoadBucketMetadataHandler(mss *grid.MSS) (np grid.NoPay
|
||||
return np, grid.NewRemoteErr(err)
|
||||
}
|
||||
|
||||
// Publish the metadata and derived registries from the same current revision.
|
||||
globalBucketMetadataSys.setReloaded(bucketName, meta)
|
||||
// Publish the reloaded metadata unconditionally. Overlapping peer reloads
|
||||
// may briefly leave the resident cache a revision behind, or momentarily
|
||||
// apply an older reload's derived registries. The resident cache may lag
|
||||
// until another authoritative update advances it; the periodic metadata
|
||||
// refresh is only best-effort here and cannot repair a divergence whose
|
||||
// maximum per-config timestamp already equals the resident record's (its
|
||||
// staleness check compares the same lastUpdate() and would see no change).
|
||||
// This acceptable-until-refresh behavior is deliberate: lastUpdate() is the
|
||||
// max of per-config timestamps and cannot order whole-record revisions, so a
|
||||
// publication guard keyed on it would wrongly reject legitimately newer
|
||||
// records (issue #105 follow-up dropped that guard).
|
||||
globalBucketMetadataSys.Set(bucketName, meta)
|
||||
|
||||
if meta.notificationConfig != nil {
|
||||
globalEventNotifier.AddRulesMap(bucketName, meta.notificationConfig.ToRulesMap())
|
||||
}
|
||||
|
||||
if meta.bucketTargetConfig != nil {
|
||||
globalBucketTargetSys.UpdateAllTargets(bucketName, meta.bucketTargetConfig)
|
||||
}
|
||||
|
||||
return np, nerr
|
||||
}
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
// Copyright (c) 2026 PGSTY
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio/internal/auth"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
)
|
||||
|
||||
func TestPresignedHeaderPayloadHashIsEnforced(t *testing.T) {
|
||||
setupSignatureBoundaryTest(t)
|
||||
digest := getSHA256Hash([]byte("expected"))
|
||||
for _, tc := range []struct {
|
||||
name, query, header string
|
||||
unsigned bool
|
||||
}{
|
||||
{name: "header only", header: digest},
|
||||
{name: "query only", query: digest},
|
||||
{name: "query wins", query: digest, header: getSHA256Hash([]byte("different"))},
|
||||
{name: "unsigned query wins", query: unsignedPayload, header: digest, unsigned: true},
|
||||
{name: "unsigned header", header: unsignedPayload, unsigned: true},
|
||||
{name: "absent", unsigned: true},
|
||||
} {
|
||||
for _, body := range []string{"expected", "modified"} {
|
||||
t.Run(tc.name+"/"+body, func(t *testing.T) {
|
||||
r := httptest.NewRequest(http.MethodPut, "http://minio.local/bucket/object", strings.NewReader(body))
|
||||
if tc.header != "" {
|
||||
r.Header.Set(xhttp.AmzContentSha256, tc.header)
|
||||
}
|
||||
if tc.query != "" {
|
||||
query := r.URL.Query()
|
||||
query.Set(xhttp.AmzContentSha256, tc.query)
|
||||
r.URL.RawQuery = query.Encode()
|
||||
}
|
||||
presignBoundaryRequest(t, r, UTCNow(), []string{"host"}, globalActiveCred)
|
||||
if code := isReqAuthenticated(t.Context(), r, globalSite.Region(), serviceS3); code != ErrNone {
|
||||
t.Fatal(niceError(code))
|
||||
}
|
||||
_, err := io.ReadAll(r.Body)
|
||||
wantMismatch := body == "modified" && !tc.unsigned
|
||||
if wantMismatch {
|
||||
if toAPIErrorCode(t.Context(), err) != ErrContentSHA256Mismatch {
|
||||
t.Errorf("modified signed payload: got %v, want SHA-256 mismatch", err)
|
||||
}
|
||||
} else if err != nil {
|
||||
t.Errorf("valid payload: %v", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestAPIPresignedBucketPolicyPayloadHash(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: func(objectAPI ObjectLayer, instanceType, bucket string, apiRouter http.Handler, credentials auth.Credentials, t *testing.T) {
|
||||
server := httptest.NewServer(apiRouter)
|
||||
defer server.Close()
|
||||
client := server.Client()
|
||||
client.Timeout = 10 * time.Second
|
||||
expected := fmt.Sprintf(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Principal":{"AWS":["*"]},"Action":["s3:GetObject"],"Resource":["arn:aws:s3:::%s/*"]}]}`, bucket)
|
||||
modified := strings.Replace(expected, "s3:GetObject", "s3:PutObject", 1)
|
||||
for _, tc := range []struct {
|
||||
name, body string
|
||||
status int
|
||||
}{
|
||||
{"original", expected, http.StatusNoContent},
|
||||
{"modified", modified, http.StatusBadRequest},
|
||||
} {
|
||||
t.Run(instanceType+"/"+tc.name, func(t *testing.T) {
|
||||
r, err := http.NewRequestWithContext(t.Context(), http.MethodPut, server.URL+"/"+bucket+"?policy=", strings.NewReader(tc.body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.Header.Set(xhttp.AmzContentSha256, getSHA256Hash([]byte(expected)))
|
||||
presignBoundaryRequest(t, r, UTCNow(), []string{"host"}, credentials)
|
||||
response, err := client.Do(r)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer response.Body.Close()
|
||||
body, err := io.ReadAll(response.Body)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if response.StatusCode != tc.status {
|
||||
t.Fatalf("PutBucketPolicy: got %d %s, want %d", response.StatusCode, body, tc.status)
|
||||
}
|
||||
if tc.status == http.StatusBadRequest && !strings.Contains(string(body), "XAmzContentSHA256Mismatch") {
|
||||
t.Fatalf("expected payload checksum rejection, got %s", body)
|
||||
}
|
||||
})
|
||||
}
|
||||
meta, err := globalBucketMetadataSys.Get(bucket)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(string(meta.PolicyConfigJSON), "s3:PutObject") {
|
||||
t.Fatal("tampered presigned request replaced the bucket policy")
|
||||
}
|
||||
},
|
||||
endpoints: []string{"PutBucketPolicy"},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
// Copyright (c) 2026 Feng Ruohang
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/sha256"
|
||||
"hash"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/minio/minio-go/v7/pkg/signer"
|
||||
"github.com/minio/minio/internal/auth"
|
||||
)
|
||||
|
||||
type sdkStreamingHasher struct{ hash.Hash }
|
||||
|
||||
func (sdkStreamingHasher) Close() {}
|
||||
|
||||
func TestAPIUpstreamSDKStreamingContentType(t *testing.T) {
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
objAPITest: func(obj ObjectLayer, instanceType, bucketName string, router http.Handler, cred auth.Credentials, t *testing.T) {
|
||||
payload := bytes.Repeat([]byte("sdk-streaming-"), 8192)
|
||||
for _, tamper := range []bool{false, true} {
|
||||
req, err := http.NewRequest(http.MethodPut, getPutObjectURL("http://localhost", bucketName, "sdk-streaming"), bytes.NewReader(payload))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/x-silo-test")
|
||||
hasher := sdkStreamingHasher{sha256.New()}
|
||||
req = signer.StreamingSignV4(req, cred.AccessKey, cred.SecretKey, "", globalSite.Region(), int64(len(payload)), UTCNow(), hasher)
|
||||
_, signedHeaders, _ := strings.Cut(req.Header.Get("Authorization"), "SignedHeaders=")
|
||||
signedHeaders, _, _ = strings.Cut(signedHeaders, ",")
|
||||
if !slices.Contains(strings.Split(signedHeaders, ";"), "content-type") {
|
||||
t.Fatal("upstream SDK did not sign Content-Type")
|
||||
}
|
||||
if tamper {
|
||||
req.Header.Set("Content-Type", "application/x-tampered")
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, req)
|
||||
want := http.StatusOK
|
||||
if tamper {
|
||||
want = http.StatusForbidden
|
||||
}
|
||||
if rec.Code != want {
|
||||
t.Fatalf("%s tamper=%v: status %d, want %d: %s", instanceType, tamper, rec.Code, want, rec.Body.String())
|
||||
}
|
||||
}
|
||||
info, err := obj.GetObjectInfo(t.Context(), bucketName, "sdk-streaming", ObjectOptions{})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if info.Size != int64(len(payload)) || info.ContentType != "application/x-silo-test" {
|
||||
t.Fatalf("stored size/type = %d/%q", info.Size, info.ContentType)
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,324 @@
|
||||
// Copyright (c) 2026 PGSTY
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/xml"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"slices"
|
||||
"strconv"
|
||||
"strings"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/minio/madmin-go/v3"
|
||||
"github.com/minio/minio/internal/auth"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
"github.com/pgsty/silo-pkg/v3/policy"
|
||||
)
|
||||
|
||||
// forgedSignatureAgeHeader is the name of the scratch header the presigned
|
||||
// verifier once wrote s3:signatureAge through. Production code no longer knows
|
||||
// it; a client that sends it is sending an ordinary unsigned x-amz-* header.
|
||||
const forgedSignatureAgeHeader = "X-Amz-Signature-Age"
|
||||
|
||||
// Presign at a chosen time, including exactly the supplied operation headers.
|
||||
func presignBoundaryRequest(t *testing.T, r *http.Request, date time.Time, signedHeaders []string, cred auth.Credentials) {
|
||||
t.Helper()
|
||||
query := r.URL.Query()
|
||||
query.Del(xhttp.AmzSignature)
|
||||
query.Set(xhttp.AmzAlgorithm, signV4Algorithm)
|
||||
query.Set(xhttp.AmzDate, date.Format(iso8601Format))
|
||||
query.Set(xhttp.AmzExpires, "3600")
|
||||
query.Set(xhttp.AmzSignedHeaders, strings.Join(signedHeaders, ";"))
|
||||
query.Set(xhttp.AmzCredential, cred.AccessKey+"/"+getScope(date, globalSite.Region()))
|
||||
r.Form = query
|
||||
headers, code := extractSignedHeaders(signedHeaders, r)
|
||||
if code != ErrNone {
|
||||
t.Fatal(niceError(code))
|
||||
}
|
||||
canonical := getCanonicalRequest(headers, getContentSha256Cksum(r, serviceS3), query.Encode(), r.URL.Path, r.Method)
|
||||
key := getSigningKey(cred.SecretKey, date, globalSite.Region(), serviceS3)
|
||||
query.Set(xhttp.AmzSignature, getSignature(key, getStringToSign(canonical, date, getScope(date, globalSite.Region()))))
|
||||
r.URL.RawQuery = query.Encode()
|
||||
r.Form = query
|
||||
}
|
||||
|
||||
func setupSignatureBoundaryTest(t *testing.T) {
|
||||
t.Helper()
|
||||
obj, fsDir, err := prepareFS(t.Context())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { os.RemoveAll(fsDir) })
|
||||
if err = newTestConfig(globalMinioDefaultRegion, obj); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
// Canonicalization comma-joins repeated header fields, so a signature over one
|
||||
// x-amz-copy-source value containing a comma also covers the same text split
|
||||
// into two fields, while the copy handlers act on Header.Get alone. A single
|
||||
// value may contain a literal or percent-encoded comma; a repeated header is
|
||||
// rejected at the shared SigV4 boundary for both signed and presigned requests.
|
||||
func TestV4CopySourceMultiplicity(t *testing.T) {
|
||||
setupSignatureBoundaryTest(t)
|
||||
for _, presigned := range []bool{false, true} {
|
||||
for _, source := range []string{"/source/allowed,tail", "/source/allowed%2Ctail"} {
|
||||
t.Run(fmt.Sprintf("presigned=%v/%s", presigned, source), func(t *testing.T) {
|
||||
r := httptest.NewRequest(http.MethodPut, "http://minio.local/destination/object", nil)
|
||||
r.Header.Set(xhttp.AmzContentSha256, emptySHA256)
|
||||
r.Header.Set(xhttp.AmzCopySource, source)
|
||||
if presigned {
|
||||
presignBoundaryRequest(t, r, UTCNow(), []string{"host", "x-amz-copy-source"}, globalActiveCred)
|
||||
} else {
|
||||
if err := signRequestV4(r, globalActiveCred.AccessKey, globalActiveCred.SecretKey); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.Form = r.URL.Query()
|
||||
}
|
||||
if code := reqSignatureV4Verify(r, globalSite.Region(), serviceS3); code != ErrNone {
|
||||
t.Fatalf("a single source key containing a comma must remain valid: %s", niceError(code))
|
||||
}
|
||||
if source != "/source/allowed,tail" {
|
||||
return
|
||||
}
|
||||
r.Header[xhttp.AmzCopySource] = []string{"/source/allowed", "tail"}
|
||||
if code := reqSignatureV4Verify(r, globalSite.Region(), serviceS3); code != ErrInvalidCopySource {
|
||||
t.Fatalf("split copy source: got %s, want %s; handler would copy %q",
|
||||
niceError(code), niceError(ErrInvalidCopySource), r.Header.Get(xhttp.AmzCopySource))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// PutObject and UploadPart authorize before they verify the signature, so
|
||||
// s3:signatureAge must come from the signed X-Amz-Date on the first policy
|
||||
// evaluation. A client header under the former scratch name must neither
|
||||
// supply the value nor survive verification, and verifying the same request
|
||||
// twice must give the same answer.
|
||||
func TestGetConditionValuesPresignedAgeFromDate(t *testing.T) {
|
||||
setupSignatureBoundaryTest(t)
|
||||
for _, tc := range []struct {
|
||||
name, header string
|
||||
age time.Duration
|
||||
wantVerify APIErrorCode
|
||||
}{
|
||||
{name: "old", age: 10 * time.Minute},
|
||||
{name: "old forged 0", age: 10 * time.Minute, header: "0", wantVerify: ErrUnsignedHeaders},
|
||||
{name: "old forged 1", age: 10 * time.Minute, header: "1", wantVerify: ErrUnsignedHeaders},
|
||||
// A signer slightly ahead of the server stays within globalMaxSkewTime.
|
||||
{name: "future within skew", age: -2 * time.Minute},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
r := httptest.NewRequest(http.MethodPut, "http://minio.local/bucket/object", nil)
|
||||
presignBoundaryRequest(t, r, UTCNow().Add(-tc.age), []string{"host"}, globalActiveCred)
|
||||
if tc.header != "" {
|
||||
r.Header.Set(forgedSignatureAgeHeader, tc.header)
|
||||
}
|
||||
values := getConditionValues(r, "", globalActiveCred)
|
||||
age, err := strconv.ParseInt(strings.Join(values["signatureAge"], ""), 10, 64)
|
||||
lo, hi := (tc.age - time.Minute).Milliseconds(), (tc.age + time.Minute).Milliseconds()
|
||||
if err != nil || age < lo || age > hi {
|
||||
t.Errorf("pre-verification policy got age %v; want the age of the signed date (about %d ms)", values["signatureAge"], tc.age.Milliseconds())
|
||||
}
|
||||
code := reqSignatureV4Verify(r, globalSite.Region(), serviceS3)
|
||||
if code != tc.wantVerify {
|
||||
t.Fatalf("verification: got %s, want %s", niceError(code), niceError(tc.wantVerify))
|
||||
}
|
||||
if again := reqSignatureV4Verify(r, globalSite.Region(), serviceS3); again != code {
|
||||
t.Fatalf("second verification changed the outcome: %s -> %s", niceError(code), niceError(again))
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// The s3:x-amz-content-sha256 policy value must be the single payload hash the
|
||||
// request is verified and enforced against. Header presence decides whether the
|
||||
// key exists at all; the value is the one getContentSha256Cksum selects, so a
|
||||
// presigned query value wins over the header and a repeated header contributes
|
||||
// only its first value. None of these requests is rejected at the protocol
|
||||
// level; the policy simply sees what verification bound.
|
||||
func TestGetConditionValuesPayloadHashMatchesVerifiedValue(t *testing.T) {
|
||||
setupSignatureBoundaryTest(t)
|
||||
hashA, hashB := getSHA256Hash([]byte("a")), getSHA256Hash([]byte("b"))
|
||||
for _, tc := range []struct {
|
||||
name string
|
||||
presigned bool
|
||||
query string
|
||||
header []string
|
||||
want []string
|
||||
}{
|
||||
{name: "signed header", header: []string{hashA}, want: []string{hashA}},
|
||||
{name: "signed absent"},
|
||||
{name: "signed present empty", header: []string{""}, want: []string{""}},
|
||||
{name: "signed duplicate header", header: []string{hashA, hashB}, want: []string{hashA}},
|
||||
{name: "signed streaming with second value", header: []string{streamingContentSHA256, hashA}, want: []string{streamingContentSHA256}},
|
||||
{name: "presigned query only", presigned: true, query: hashA},
|
||||
{name: "presigned header only", presigned: true, header: []string{hashA}, want: []string{hashA}},
|
||||
{name: "presigned matching query and header", presigned: true, query: hashA, header: []string{hashA}, want: []string{hashA}},
|
||||
{name: "presigned unsigned query with forged header", presigned: true, query: unsignedPayload, header: []string{hashA}, want: []string{unsignedPayload}},
|
||||
{name: "presigned duplicate header", presigned: true, header: []string{hashA, hashB}, want: []string{hashA}},
|
||||
{name: "presigned query with empty header", presigned: true, query: hashA, header: []string{""}, want: []string{hashA}},
|
||||
} {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
target := "http://minio.local/bucket/object"
|
||||
if tc.query != "" {
|
||||
target += "?" + xhttp.AmzContentSha256 + "=" + tc.query
|
||||
}
|
||||
r := httptest.NewRequest(http.MethodPut, target, nil)
|
||||
if tc.header != nil {
|
||||
r.Header[xhttp.AmzContentSha256] = tc.header
|
||||
}
|
||||
if tc.presigned {
|
||||
presignBoundaryRequest(t, r, UTCNow(), []string{"host"}, globalActiveCred)
|
||||
} else {
|
||||
r.Header.Set(xhttp.Authorization, signV4Algorithm+" Credential=x/20260910/us-east-1/s3/aws4_request, SignedHeaders=host, Signature=x")
|
||||
r.Form = r.URL.Query()
|
||||
}
|
||||
got, ok := getConditionValues(r, "", globalActiveCred)[xhttp.AmzContentSha256]
|
||||
if ok != (tc.want != nil) || !slices.Equal(got, tc.want) {
|
||||
t.Fatalf("policy value = %v (present=%v), want %v (present=%v)", got, ok, tc.want, tc.want != nil)
|
||||
}
|
||||
if tc.presigned {
|
||||
if code := reqSignatureV4Verify(r, globalSite.Region(), serviceS3); code != ErrNone {
|
||||
t.Fatalf("the presigned request must still verify: %s", niceError(code))
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func newSignatureBoundaryUser(t *testing.T, bucket, statements string) auth.Credentials {
|
||||
t.Helper()
|
||||
cred, err := auth.GetNewCredentials()
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := globalIAMSys.CreateUser(t.Context(), cred.AccessKey, madmin.AddOrUpdateUserReq{SecretKey: cred.SecretKey, Status: madmin.AccountEnabled}); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
p, err := policy.ParseConfig(strings.NewReader(fmt.Sprintf(`{"Version":"2012-10-17","Statement":[{"Effect":"Allow","Action":"s3:PutObject","Resource":"arn:aws:s3:::%s/*"},%s]}`, bucket, statements)))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
name := "signature-boundary-" + mustGetUUID()
|
||||
if _, err := globalIAMSys.SetPolicy(t.Context(), name, *p); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if _, err := globalIAMSys.PolicyDBSet(t.Context(), cred.AccessKey, name, regUser, false); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return cred
|
||||
}
|
||||
|
||||
func TestAPIPresignedSignatureAgeBeforeAuthorization(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
endpoints: []string{"NewMultipart", "PutObjectPart", "PutObject"},
|
||||
objAPITest: func(obj ObjectLayer, instanceType, bucket string, router http.Handler, root auth.Credentials, t *testing.T) {
|
||||
user := newSignatureBoundaryUser(t, bucket, fmt.Sprintf(`{"Effect":"Deny","Action":"s3:PutObject","Resource":"arn:aws:s3:::%s/*","Condition":{"NumericGreaterThan":{"s3:signatureAge":"60000"}}}`, bucket))
|
||||
initReq, err := newTestSignedRequestV4(http.MethodPost, getNewMultipartURL("", bucket, "multipart"), 0, nil, root.AccessKey, root.SecretKey, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
initRec := httptest.NewRecorder()
|
||||
router.ServeHTTP(initRec, initReq)
|
||||
var upload InitiateMultipartUploadResponse
|
||||
if initRec.Code != http.StatusOK || xml.Unmarshal(initRec.Body.Bytes(), &upload) != nil {
|
||||
t.Fatalf("multipart initiation: %d %s", initRec.Code, initRec.Body.String())
|
||||
}
|
||||
for _, operation := range []string{"put", "part"} {
|
||||
for _, tc := range []struct {
|
||||
name, header string
|
||||
age time.Duration
|
||||
want int
|
||||
}{
|
||||
{name: "fresh", want: http.StatusOK},
|
||||
{name: "old without header", age: 10 * time.Minute, want: http.StatusForbidden},
|
||||
{name: "old forged header", age: 10 * time.Minute, header: "0", want: http.StatusForbidden},
|
||||
// Policy allows a fresh signature; the unsigned header then fails
|
||||
// verification with the existing ErrUnsignedHeaders (HTTP 400).
|
||||
{name: "fresh with unsigned header", header: "0", want: http.StatusBadRequest},
|
||||
} {
|
||||
t.Run(instanceType+"/"+operation+"/"+tc.name, func(t *testing.T) {
|
||||
target := getPutObjectURL("", bucket, "put-"+strings.ReplaceAll(tc.name, " ", "-"))
|
||||
if operation == "part" {
|
||||
target = getPutObjectPartURL("", bucket, "multipart", upload.UploadID, "1")
|
||||
}
|
||||
r, err := newTestRequest(http.MethodPut, target, 4, bytes.NewReader([]byte("body")))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
r.Header.Del(xhttp.AmzContentSha256)
|
||||
presignBoundaryRequest(t, r, UTCNow().Add(-tc.age), []string{"host"}, user)
|
||||
if tc.header != "" {
|
||||
r.Header.Set(forgedSignatureAgeHeader, tc.header)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, r)
|
||||
if rec.Code != tc.want {
|
||||
t.Errorf("got %d %s, want %d", rec.Code, rec.Body.String(), tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
func TestAPIPayloadHashPolicyMatchesVerifiedValue(t *testing.T) {
|
||||
defer DetectTestLeak(t)()
|
||||
ExecObjectLayerAPITest(ExecObjectLayerAPITestArgs{
|
||||
t: t,
|
||||
endpoints: []string{"PutObject"},
|
||||
objAPITest: func(_ ObjectLayer, instanceType, bucket string, router http.Handler, _ auth.Credentials, t *testing.T) {
|
||||
allowedHash := getSHA256Hash([]byte("expected"))
|
||||
user := newSignatureBoundaryUser(t, bucket, fmt.Sprintf(`{"Effect":"Deny","Action":"s3:PutObject","Resource":"arn:aws:s3:::%s/*","Condition":{"StringNotEquals":{"s3:x-amz-content-sha256":"%s"}}}`, bucket, allowedHash))
|
||||
for _, kind := range []string{"signed control", "presigned control", "unsigned query forged header", "signed duplicate header", "presigned duplicate header"} {
|
||||
t.Run(instanceType+"/"+kind, func(t *testing.T) {
|
||||
control := strings.HasSuffix(kind, "control")
|
||||
body := "modified"
|
||||
if control {
|
||||
body = "expected"
|
||||
}
|
||||
r, err := newTestRequest(http.MethodPut, getPutObjectURL("", bucket, strings.ReplaceAll(kind, " ", "-")), int64(len(body)), strings.NewReader(body))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if strings.Contains(kind, "duplicate") {
|
||||
r.Header.Add(xhttp.AmzContentSha256, allowedHash)
|
||||
}
|
||||
if kind == "unsigned query forged header" {
|
||||
q := r.URL.Query()
|
||||
q.Set(xhttp.AmzContentSha256, unsignedPayload)
|
||||
r.URL.RawQuery = q.Encode()
|
||||
r.Header.Set(xhttp.AmzContentSha256, allowedHash)
|
||||
}
|
||||
if strings.HasPrefix(kind, "signed") {
|
||||
if err := signRequestV4(r, user.AccessKey, user.SecretKey); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
} else {
|
||||
presignBoundaryRequest(t, r, UTCNow(), []string{"host"}, user)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
router.ServeHTTP(rec, r)
|
||||
if control && rec.Code != http.StatusOK {
|
||||
t.Errorf("control rejected: %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
if !control && rec.Code < http.StatusBadRequest {
|
||||
t.Errorf("payload-hash policy bypass returned %d %s", rec.Code, rec.Body.String())
|
||||
}
|
||||
})
|
||||
}
|
||||
},
|
||||
})
|
||||
}
|
||||
@@ -211,7 +211,16 @@ func extractSignedHeaders(signedHeaders []string, r *http.Request) (http.Header,
|
||||
// `host` will not be found in the headers, can be found in r.Host.
|
||||
// but its always necessary that the list of signed headers containing host in it.
|
||||
val, ok := reqHeaders[http.CanonicalHeaderKey(header)]
|
||||
if !ok {
|
||||
if ok {
|
||||
// Canonicalization comma-joins repeated header fields, so a signature
|
||||
// over the single value "/src/a,tail" also verifies a request carrying
|
||||
// ["/src/a", "tail"]. The copy handlers read only Header.Get, so that
|
||||
// rewrite would copy a different source than the one signed. Reject a
|
||||
// repeated x-amz-copy-source; a single value may still contain commas.
|
||||
if len(val) > 1 && strings.EqualFold(header, strings.ToLower(xhttp.AmzCopySource)) {
|
||||
return nil, ErrInvalidCopySource
|
||||
}
|
||||
} else {
|
||||
// try to set headers from Query String
|
||||
val, ok = reqQueries[header]
|
||||
}
|
||||
@@ -264,14 +273,40 @@ func signV4TrimAll(input string) string {
|
||||
return strings.Join(strings.Fields(input), " ")
|
||||
}
|
||||
|
||||
// checkMetaHeaders will check if the metadata from header/url is the same with the one from signed headers
|
||||
func checkMetaHeaders(signedHeadersMap http.Header, r *http.Request) APIErrorCode {
|
||||
// check values from http header
|
||||
for k, val := range r.Header {
|
||||
if stringsHasPrefixFold(k, "X-Amz-Meta-") {
|
||||
if signedHeadersMap.Get(k) == val[0] {
|
||||
continue
|
||||
}
|
||||
// checkUnsignedHeaders rejects any x-amz-* request header that is not covered by
|
||||
// the SigV4 signed-headers list. AWS S3 requires every x-amz-* header to be
|
||||
// signed and returns AccessDenied ("There were headers present in the request
|
||||
// which were not signed") otherwise. Enforcing the same here prevents an
|
||||
// unsigned x-amz-* header (for example x-amz-copy-source) from changing the
|
||||
// semantics of an already-signed or presigned request: without this check a
|
||||
// presigned PUT grant could be turned into a server-side copy that reads any
|
||||
// object the signing key can reach.
|
||||
//
|
||||
// Only headers actually sent by the client are inspected. Server-synthesized
|
||||
// x-amz-* headers (e.g. x-amz-tagging derived from a request body) are set
|
||||
// after signature verification and therefore never reach this walk.
|
||||
func checkUnsignedHeaders(signedHeadersMap http.Header, r *http.Request) APIErrorCode {
|
||||
// check headers that arrived on the request
|
||||
for k := range r.Header {
|
||||
if !stringsHasPrefixFold(k, "X-Amz-") {
|
||||
continue
|
||||
}
|
||||
// X-Amz-Content-Sha256 carries the payload hash, not an operation or
|
||||
// authorization input, and is handled specially: for presigned requests
|
||||
// it is read from the query string (getContentSha256Cksum) and any
|
||||
// header copy is ignored, while for signed requests it is bound into the
|
||||
// string-to-sign as the payload hash, so a tampered value fails
|
||||
// signature verification regardless of the signed-headers list. Some
|
||||
// clients send it as an unsigned header, so exempt it to preserve
|
||||
// compatibility without weakening the operation-header protection.
|
||||
if strings.EqualFold(k, xhttp.AmzContentSha256) {
|
||||
continue
|
||||
}
|
||||
// The header must be a member of the signed-headers list. Testing
|
||||
// membership (not value equality) is essential: an unsigned header whose
|
||||
// first value is empty would otherwise compare equal to the empty string
|
||||
// returned for an absent key and slip through.
|
||||
if _, ok := signedHeadersMap[http.CanonicalHeaderKey(k)]; !ok {
|
||||
return ErrUnsignedHeaders
|
||||
}
|
||||
}
|
||||
|
||||
@@ -363,8 +363,8 @@ func TestGetContentSha256Cksum(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
// Test TestCheckMetaHeaders tests the logic of checkMetaHeaders() function
|
||||
func TestCheckMetaHeaders(t *testing.T) {
|
||||
// Test TestCheckUnsignedHeaders tests the logic of checkUnsignedHeaders() function
|
||||
func TestCheckUnsignedHeaders(t *testing.T) {
|
||||
signedHeadersMap := map[string][]string{
|
||||
"X-Amz-Meta-Test": {"test"},
|
||||
"X-Amz-Meta-Extension": {"png"},
|
||||
@@ -384,7 +384,7 @@ func TestCheckMetaHeaders(t *testing.T) {
|
||||
inputHeader.Set("X-Amz-Meta-Extension", expectedMetaExtension)
|
||||
inputHeader.Set("X-Amz-Meta-Name", expectedMetaName)
|
||||
// calling the function being tested.
|
||||
errCode := checkMetaHeaders(signedHeadersMap, r)
|
||||
errCode := checkUnsignedHeaders(signedHeadersMap, r)
|
||||
if errCode != ErrNone {
|
||||
t.Fatalf("Expected the APIErrorCode to be %d, but got %d", ErrNone, errCode)
|
||||
}
|
||||
@@ -392,7 +392,7 @@ func TestCheckMetaHeaders(t *testing.T) {
|
||||
// Add new metadata in inputHeader
|
||||
inputHeader.Set("X-Amz-Meta-Clone", "fail")
|
||||
// calling the function being tested.
|
||||
errCode = checkMetaHeaders(signedHeadersMap, r)
|
||||
errCode = checkUnsignedHeaders(signedHeadersMap, r)
|
||||
if errCode != ErrUnsignedHeaders {
|
||||
t.Fatalf("Expected the APIErrorCode to be %d, but got %d", ErrUnsignedHeaders, errCode)
|
||||
}
|
||||
@@ -400,7 +400,7 @@ func TestCheckMetaHeaders(t *testing.T) {
|
||||
// Delete extra metadata from header to don't affect other test
|
||||
inputHeader.Del("X-Amz-Meta-Clone")
|
||||
// calling the function being tested.
|
||||
errCode = checkMetaHeaders(signedHeadersMap, r)
|
||||
errCode = checkUnsignedHeaders(signedHeadersMap, r)
|
||||
if errCode != ErrNone {
|
||||
t.Fatalf("Expected the APIErrorCode to be %d, but got %d", ErrNone, errCode)
|
||||
}
|
||||
@@ -413,8 +413,72 @@ func TestCheckMetaHeaders(t *testing.T) {
|
||||
|
||||
r.ParseForm()
|
||||
// calling the function being tested.
|
||||
errCode = checkMetaHeaders(signedHeadersMap, r)
|
||||
errCode = checkUnsignedHeaders(signedHeadersMap, r)
|
||||
if errCode != ErrNone {
|
||||
t.Fatalf("Expected the APIErrorCode to be %d, but got %d", ErrNone, errCode)
|
||||
}
|
||||
|
||||
// Regression for the unsigned x-amz-copy-source coverage gap: an x-amz-*
|
||||
// header outside the signed-headers list (here x-amz-copy-source, which the
|
||||
// router uses to select CopyObjectHandler) must be rejected. Previously only
|
||||
// x-amz-meta-* headers were inspected, so this header slipped through and a
|
||||
// presigned/authorized PUT could be turned into a server-side copy.
|
||||
r, err = http.NewRequest(http.MethodPut, "http://play.min.io:9000", nil)
|
||||
if err != nil {
|
||||
t.Fatal("Unable to create http.Request :", err)
|
||||
}
|
||||
r.Header.Set("X-Amz-Copy-Source", "/src/secret.txt")
|
||||
if errCode = checkUnsignedHeaders(signedHeadersMap, r); errCode != ErrUnsignedHeaders {
|
||||
t.Fatalf("unsigned x-amz-copy-source: expected %d, got %d", ErrUnsignedHeaders, errCode)
|
||||
}
|
||||
|
||||
// When the same header is part of the signed-headers list with a matching
|
||||
// value it is allowed through, exactly as for x-amz-meta-*.
|
||||
signedWithCopy := http.Header{}
|
||||
for k, v := range signedHeadersMap {
|
||||
signedWithCopy[k] = v
|
||||
}
|
||||
signedWithCopy.Set("X-Amz-Copy-Source", "/src/secret.txt")
|
||||
if errCode = checkUnsignedHeaders(signedWithCopy, r); errCode != ErrNone {
|
||||
t.Fatalf("signed x-amz-copy-source: expected %d, got %d", ErrNone, errCode)
|
||||
}
|
||||
|
||||
// Membership, not value equality: an unsigned x-amz-* header whose first
|
||||
// value is empty must still be rejected. A value-equality check would
|
||||
// compare "" against the empty string returned for an absent signed header
|
||||
// and wrongly let it through, so a multi-value header like
|
||||
// {"", "/src/secret.txt"} could smuggle an unsigned copy-source.
|
||||
r, err = http.NewRequest(http.MethodPut, "http://play.min.io:9000", nil)
|
||||
if err != nil {
|
||||
t.Fatal("Unable to create http.Request :", err)
|
||||
}
|
||||
r.Header["X-Amz-Copy-Source"] = []string{"", "/src/secret.txt"}
|
||||
if errCode = checkUnsignedHeaders(signedHeadersMap, r); errCode != ErrUnsignedHeaders {
|
||||
t.Fatalf("empty-first unsigned x-amz-copy-source: expected %d, got %d", ErrUnsignedHeaders, errCode)
|
||||
}
|
||||
|
||||
// X-Amz-Content-Sha256 is exempt: it carries the payload hash (handled from
|
||||
// the query for presigned and bound into the string-to-sign for signed
|
||||
// requests), so it is allowed even when it is not in the signed-headers map.
|
||||
r, err = http.NewRequest(http.MethodPut, "http://play.min.io:9000", nil)
|
||||
if err != nil {
|
||||
t.Fatal("Unable to create http.Request :", err)
|
||||
}
|
||||
r.Header.Set(xhttp.AmzContentSha256, unsignedPayload)
|
||||
if errCode = checkUnsignedHeaders(signedHeadersMap, r); errCode != ErrNone {
|
||||
t.Fatalf("unsigned x-amz-content-sha256 must be exempt: expected %d, got %d", ErrNone, errCode)
|
||||
}
|
||||
|
||||
// X-Amz-Signature-Age was once a scratch header the presigned verifier wrote
|
||||
// back and this check exempted. s3:signatureAge is now derived from the
|
||||
// signed date, so a client that sends the header is sending an ordinary
|
||||
// unsigned x-amz-* header and must be rejected like any other.
|
||||
r, err = http.NewRequest(http.MethodPut, "http://play.min.io:9000", nil)
|
||||
if err != nil {
|
||||
t.Fatal("Unable to create http.Request :", err)
|
||||
}
|
||||
r.Header.Set("X-Amz-Signature-Age", "1234")
|
||||
if errCode = checkUnsignedHeaders(signedHeadersMap, r); errCode != ErrUnsignedHeaders {
|
||||
t.Fatalf("unsigned x-amz-signature-age must be rejected: expected %d, got %d", ErrUnsignedHeaders, errCode)
|
||||
}
|
||||
}
|
||||
|
||||
+13
-6
@@ -229,10 +229,11 @@ func doesPresignedSignatureMatch(hashedPayload string, r *http.Request, region s
|
||||
return errCode
|
||||
}
|
||||
|
||||
// Check if the metadata headers are equal with signedheaders
|
||||
errMetaCode := checkMetaHeaders(extractedSignedHeaders, r)
|
||||
if errMetaCode != ErrNone {
|
||||
return errMetaCode
|
||||
// Reject any x-amz-* header that the client did not sign. Without this an
|
||||
// unsigned header (e.g. x-amz-copy-source) could alter the request that the
|
||||
// presigned URL actually authorized.
|
||||
if errUnsigned := checkUnsignedHeaders(extractedSignedHeaders, r); errUnsigned != ErrNone {
|
||||
return errUnsigned
|
||||
}
|
||||
|
||||
// If the host which signed the request is slightly ahead in time (by less than globalMaxSkewTime) the
|
||||
@@ -335,8 +336,6 @@ func doesPresignedSignatureMatch(hashedPayload string, r *http.Request, region s
|
||||
return ErrSignatureDoesNotMatch
|
||||
}
|
||||
|
||||
r.Header.Set("x-amz-signature-age", strconv.FormatInt(UTCNow().Sub(pSignValues.Date).Milliseconds(), 10))
|
||||
|
||||
return ErrNone
|
||||
}
|
||||
|
||||
@@ -363,6 +362,14 @@ func doesSignatureMatch(hashedPayload string, r *http.Request, region string, st
|
||||
return errCode
|
||||
}
|
||||
|
||||
// Reject any x-amz-* header that the client did not sign. The Authorization
|
||||
// header path shares extractSignedHeaders with the presigned path but, prior
|
||||
// to this, never inspected the headers that actually arrived, so an unsigned
|
||||
// x-amz-copy-source could redirect a signed PUT into a server-side copy.
|
||||
if errUnsigned := checkUnsignedHeaders(extractedSignedHeaders, r); errUnsigned != ErrNone {
|
||||
return errUnsigned
|
||||
}
|
||||
|
||||
cred, _, s3Err := checkKeyValid(r, signV4Values.Credential.accessKey)
|
||||
if s3Err != ErrNone {
|
||||
return s3Err
|
||||
|
||||
@@ -313,3 +313,44 @@ func TestDoesPresignedSignatureMatch(t *testing.T) {
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// TestPresignedVerifyIdempotent guards against a regression where verifying the
|
||||
// same presigned request twice began to fail. The verifier must not write
|
||||
// anything back to the request (it once recorded an internal
|
||||
// x-amz-signature-age header that the unsigned-header check then had to
|
||||
// exempt), and an unsigned x-amz-content-sha256 the client may carry stays
|
||||
// exempt, so a second verification of the same *http.Request still succeeds.
|
||||
func TestPresignedVerifyIdempotent(t *testing.T) {
|
||||
ctx, cancel := context.WithCancel(t.Context())
|
||||
defer cancel()
|
||||
|
||||
obj, fsDir, err := prepareFS(ctx)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer os.RemoveAll(fsDir)
|
||||
if err = newTestConfig(globalMinioDefaultRegion, obj); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
req, err := newTestRequest(http.MethodGet, "http://127.0.0.1:9000/bucket/object", 0, nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = preSignV4(req, globalActiveCred.AccessKey, globalActiveCred.SecretKey, int64(10*60)); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if err = req.ParseForm(); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if got := reqSignatureV4Verify(req, globalSite.Region(), serviceS3); got != ErrNone {
|
||||
t.Fatalf("first verification: expected ErrNone, got %s", niceError(got))
|
||||
}
|
||||
if got := reqSignatureV4Verify(req, globalSite.Region(), serviceS3); got != ErrNone {
|
||||
t.Fatalf("second verification of the same request: expected ErrNone, got %s", niceError(got))
|
||||
}
|
||||
if _, ok := req.Header["X-Amz-Signature-Age"]; ok {
|
||||
t.Fatal("the verifier wrote a scratch header back to the request")
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,133 @@
|
||||
// Copyright (c) 2026 Pigsty
|
||||
// SPDX-License-Identifier: AGPL-3.0-or-later
|
||||
|
||||
package cmd
|
||||
|
||||
import (
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"encoding/pem"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio/internal/config/etcd"
|
||||
)
|
||||
|
||||
func TestOutboundTLSKeyExchangeDefaults(t *testing.T) {
|
||||
for _, debug := range []string{"tlsmlkem=0", "tlsmlkem=1"} {
|
||||
t.Run(debug, func(t *testing.T) {
|
||||
t.Setenv("GODEBUG", debug)
|
||||
for _, version := range []uint16{tls.VersionTLS12, tls.VersionTLS13} {
|
||||
t.Run(tls.VersionName(version), func(t *testing.T) {
|
||||
hellos := make(chan []tls.CurveID, 1)
|
||||
server := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
_, _ = io.WriteString(w, "ok")
|
||||
}))
|
||||
server.TLS = &tls.Config{
|
||||
MinVersion: version, MaxVersion: version,
|
||||
GetConfigForClient: func(hello *tls.ClientHelloInfo) (*tls.Config, error) {
|
||||
select {
|
||||
case hellos <- slices.Clone(hello.SupportedCurves):
|
||||
default:
|
||||
}
|
||||
return nil, nil
|
||||
},
|
||||
}
|
||||
server.StartTLS()
|
||||
t.Cleanup(server.Close)
|
||||
roots := x509.NewCertPool()
|
||||
roots.AddCert(server.Certificate())
|
||||
|
||||
dir := t.TempDir()
|
||||
certFile, keyFile := filepath.Join(dir, "public.crt"), filepath.Join(dir, "private.key")
|
||||
cert := server.TLS.Certificates[0]
|
||||
key, err := x509.MarshalPKCS8PrivateKey(cert.PrivateKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for path, block := range map[string]*pem.Block{
|
||||
certFile: {Type: "CERTIFICATE", Bytes: cert.Certificate[0]},
|
||||
keyFile: {Type: "PRIVATE KEY", Bytes: key},
|
||||
} {
|
||||
if err := os.WriteFile(path, pem.EncodeToMemory(block), 0o600); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
t.Setenv(etcd.EnvEtcdEndpoints, server.URL)
|
||||
t.Setenv(etcd.EnvEtcdClientCert, "")
|
||||
t.Setenv(etcd.EnvEtcdClientCertKey, "")
|
||||
etcdConfig, err := etcd.LookupConfig(etcd.DefaultKVS, roots)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
for name, transport := range map[string]*http.Transport{
|
||||
"external": NewHTTPTransport(),
|
||||
"internode": NewInternodeHTTPTransport(1)().(*http.Transport),
|
||||
"replication": NewRemoteTargetHTTPTransport(false)(),
|
||||
"cloud-client-cert": NewHTTPTransportWithClientCerts(certFile, keyFile).(*http.Transport),
|
||||
"etcd": {TLSClientConfig: etcdConfig.TLS},
|
||||
} {
|
||||
t.Run(name, func(t *testing.T) {
|
||||
defer transport.CloseIdleConnections()
|
||||
transport.Proxy = nil
|
||||
transport.TLSClientConfig.RootCAs = roots
|
||||
client := &http.Client{Transport: transport, Timeout: 5 * time.Second}
|
||||
resp, err := client.Get(server.URL)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK || resp.TLS.Version != version {
|
||||
t.Fatalf("status %d, TLS %s", resp.StatusCode, tls.VersionName(resp.TLS.Version))
|
||||
}
|
||||
curves := <-hellos
|
||||
if got, want := slices.Contains(curves, tls.X25519MLKEM768), debug == "tlsmlkem=1"; got != want {
|
||||
t.Errorf("ML-KEM offered = %v, want %v; curves %v", got, want, curves)
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestServerTLSKeyExchangeDefaults(t *testing.T) {
|
||||
for _, debug := range []string{"tlsmlkem=0", "tlsmlkem=1"} {
|
||||
t.Run(debug, func(t *testing.T) {
|
||||
t.Setenv("GODEBUG", debug)
|
||||
// Reuse httptest's certificate with the actual Server TLS constructor.
|
||||
seed := httptest.NewTLSServer(http.NotFoundHandler())
|
||||
cert := seed.TLS.Certificates[0]
|
||||
seed.Close()
|
||||
server := httptest.NewUnstartedServer(http.NotFoundHandler())
|
||||
server.TLS = newTLSConfig(func(*tls.ClientHelloInfo) (*tls.Certificate, error) { return &cert, nil })
|
||||
server.StartTLS()
|
||||
defer server.Close()
|
||||
roots := x509.NewCertPool()
|
||||
leaf, err := x509.ParseCertificate(cert.Certificate[0])
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
roots.AddCert(leaf)
|
||||
for _, curve := range []tls.CurveID{tls.X25519MLKEM768, tls.CurveP256} {
|
||||
conn, err := tls.Dial("tcp", server.Listener.Addr().String(), &tls.Config{
|
||||
RootCAs: roots, MinVersion: tls.VersionTLS13, CurvePreferences: []tls.CurveID{curve},
|
||||
})
|
||||
wantSuccess := curve == tls.CurveP256 || debug == "tlsmlkem=1"
|
||||
if (err == nil) != wantSuccess {
|
||||
t.Errorf("curve %v: error %v, want success %v", curve, err, wantSuccess)
|
||||
}
|
||||
if conn != nil {
|
||||
_ = conn.Close()
|
||||
}
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
+23
-28
@@ -608,13 +608,12 @@ func GetDefaultConnSettings() xhttp.ConnSettings {
|
||||
// connections.
|
||||
func NewInternodeHTTPTransport(maxIdleConnsPerHost int) func() http.RoundTripper {
|
||||
return xhttp.ConnSettings{
|
||||
LookupHost: globalDNSCache.LookupHost,
|
||||
DialTimeout: rest.DefaultTimeout,
|
||||
RootCAs: globalRootCAs,
|
||||
CipherSuites: crypto.TLSCiphers(),
|
||||
CurvePreferences: crypto.TLSCurveIDs(),
|
||||
EnableHTTP2: false,
|
||||
TCPOptions: globalTCPOptions,
|
||||
LookupHost: globalDNSCache.LookupHost,
|
||||
DialTimeout: rest.DefaultTimeout,
|
||||
RootCAs: globalRootCAs,
|
||||
CipherSuites: crypto.TLSCiphers(),
|
||||
EnableHTTP2: false,
|
||||
TCPOptions: globalTCPOptions,
|
||||
}.NewInternodeHTTPTransport(maxIdleConnsPerHost)
|
||||
}
|
||||
|
||||
@@ -622,13 +621,12 @@ func NewInternodeHTTPTransport(maxIdleConnsPerHost int) func() http.RoundTripper
|
||||
// used while communicating with the cloud backends.
|
||||
func NewHTTPTransportWithClientCerts(clientCert, clientKey string) http.RoundTripper {
|
||||
s := xhttp.ConnSettings{
|
||||
LookupHost: globalDNSCache.LookupHost,
|
||||
DialTimeout: defaultDialTimeout,
|
||||
RootCAs: globalRootCAs,
|
||||
CipherSuites: crypto.TLSCiphersBackwardCompatible(),
|
||||
CurvePreferences: crypto.TLSCurveIDs(),
|
||||
TCPOptions: globalTCPOptions,
|
||||
EnableHTTP2: false,
|
||||
LookupHost: globalDNSCache.LookupHost,
|
||||
DialTimeout: defaultDialTimeout,
|
||||
RootCAs: globalRootCAs,
|
||||
CipherSuites: crypto.TLSCiphersBackwardCompatible(),
|
||||
TCPOptions: globalTCPOptions,
|
||||
EnableHTTP2: false,
|
||||
}
|
||||
|
||||
if clientCert != "" && clientKey != "" {
|
||||
@@ -660,13 +658,12 @@ const defaultDialTimeout = 5 * time.Second
|
||||
// NewHTTPTransportWithTimeout allows setting a timeout.
|
||||
func NewHTTPTransportWithTimeout(timeout time.Duration) *http.Transport {
|
||||
return xhttp.ConnSettings{
|
||||
LookupHost: globalDNSCache.LookupHost,
|
||||
DialTimeout: defaultDialTimeout,
|
||||
RootCAs: globalRootCAs,
|
||||
TCPOptions: globalTCPOptions,
|
||||
CipherSuites: crypto.TLSCiphersBackwardCompatible(),
|
||||
CurvePreferences: crypto.TLSCurveIDs(),
|
||||
EnableHTTP2: false,
|
||||
LookupHost: globalDNSCache.LookupHost,
|
||||
DialTimeout: defaultDialTimeout,
|
||||
RootCAs: globalRootCAs,
|
||||
TCPOptions: globalTCPOptions,
|
||||
CipherSuites: crypto.TLSCiphersBackwardCompatible(),
|
||||
EnableHTTP2: false,
|
||||
}.NewHTTPTransportWithTimeout(timeout)
|
||||
}
|
||||
|
||||
@@ -674,12 +671,11 @@ func NewHTTPTransportWithTimeout(timeout time.Duration) *http.Transport {
|
||||
// used while communicating with the remote replication targets.
|
||||
func NewRemoteTargetHTTPTransport(insecure bool) func() *http.Transport {
|
||||
return xhttp.ConnSettings{
|
||||
LookupHost: globalDNSCache.LookupHost,
|
||||
RootCAs: globalRootCAs,
|
||||
CipherSuites: crypto.TLSCiphersBackwardCompatible(),
|
||||
CurvePreferences: crypto.TLSCurveIDs(),
|
||||
TCPOptions: globalTCPOptions,
|
||||
EnableHTTP2: false,
|
||||
LookupHost: globalDNSCache.LookupHost,
|
||||
RootCAs: globalRootCAs,
|
||||
CipherSuites: crypto.TLSCiphersBackwardCompatible(),
|
||||
TCPOptions: globalTCPOptions,
|
||||
EnableHTTP2: false,
|
||||
}.NewRemoteTargetHTTPTransport(insecure)
|
||||
}
|
||||
|
||||
@@ -986,7 +982,6 @@ func newTLSConfig(getCert certs.GetCertificateFunc) *tls.Config {
|
||||
} else {
|
||||
tlsConfig.CipherSuites = crypto.TLSCiphersBackwardCompatible()
|
||||
}
|
||||
tlsConfig.CurvePreferences = crypto.TLSCurveIDs()
|
||||
return tlsConfig
|
||||
}
|
||||
|
||||
|
||||
@@ -2,6 +2,32 @@
|
||||
|
||||
This document explains how to configure Silo with `Bucket lookup from DNS` style federation.
|
||||
|
||||
## Cross-deployment copy behavior
|
||||
|
||||
Federated `CopyObject` and `UploadPartCopy` forward the write to the destination
|
||||
deployment. Updated Silo destinations return the modification time of that
|
||||
committed object or part in `X-Minio-Last-Modified` (UTC RFC 3339 with nanosecond
|
||||
precision), alongside its ETag and checksums. The proxy uses that write response
|
||||
to populate the copy result, whose XML retains millisecond precision. This works
|
||||
for unversioned and versioned objects and encrypted writes, without an additional
|
||||
HEAD or ListParts request or additional read permissions at the destination.
|
||||
|
||||
Both deployments need this change for accurate copy timestamps. If an older
|
||||
destination omits the header, or an intermediary removes or corrupts it, the copy
|
||||
still succeeds and retains the historical zero `LastModified` value
|
||||
(`0001-01-01T00:00:00.000Z`). The proxy neither substitutes its own clock or HTTP
|
||||
`Date` nor reports a committed write as failed because its timestamp is missing.
|
||||
The header is a response hint for the existing federation User-Agent token; it
|
||||
does not grant replication privileges.
|
||||
|
||||
A replica-authorized `CopyObject` of a raw SSE-C source across deployments is
|
||||
unsupported and returns HTTP 501 `NotImplemented` before forwarding any request.
|
||||
This includes empty objects, which previously succeeded accidentally, and applies
|
||||
whether or not a copy-source key is supplied. Ordinary federated SSE-C copies
|
||||
with the source key, local SSE-C key rotation, bucket replication via PUT or
|
||||
multipart upload, and the separate `UploadPartCopy` operation retain their
|
||||
existing behavior.
|
||||
|
||||
## Get started
|
||||
|
||||
### 1. Prerequisites
|
||||
|
||||
@@ -0,0 +1,142 @@
|
||||
# Password and user-management permissions
|
||||
|
||||
**Breaking change: the password-permission split changes the meaning of
|
||||
existing IAM policies.** The same stored policy can authorize a request after
|
||||
this update that it denied before, or deny a request it previously authorized.
|
||||
This is a deliberate authorization change from adopting
|
||||
[minio/pkg #262](https://github.com/minio/pkg/pull/262), independent of the
|
||||
minio-go SDK update. It must be called out as a breaking change in the release
|
||||
that first includes it; it is not a transparent dependency refresh.
|
||||
|
||||
SILO separates a user's own password change from creating users or resetting
|
||||
another user's password. The same `add-user` administration endpoint and mcli
|
||||
commands continue to work; the authenticated caller and target access key
|
||||
determine which permission is checked.
|
||||
|
||||
| Request | Permission | Evaluation |
|
||||
| --- | --- | --- |
|
||||
| Change the caller's own password | `admin:ChangeMyPassword` | Allowed for an internal user with an attached policy unless explicitly denied. |
|
||||
| Create another user or reset another user's password | `admin:CreateUser` | Requires an explicit Allow; an explicit Deny wins. |
|
||||
|
||||
The Console's Change Password button uses `admin:ChangeMyPassword`.
|
||||
`admin:CreateUser` continues to control user administration. The password change
|
||||
still requires the current password. STS and service-account credentials cannot
|
||||
change their parent user's password; root credentials and external identity
|
||||
provider passwords remain outside this endpoint.
|
||||
|
||||
## What changes and why
|
||||
|
||||
Previously, both operations checked `admin:CreateUser`. Changing one's own
|
||||
password used an implicit grant unless that action was explicitly denied;
|
||||
managing other users required an explicit Allow. The split retains these two
|
||||
evaluation rules but checks `admin:ChangeMyPassword` for the caller's password.
|
||||
It lets an operator independently control password changes and user
|
||||
administration. This is a policy-design choice, not a required mitigation for
|
||||
the SDK signing or region-compatibility fixes.
|
||||
|
||||
The following cases assume an internal user with an attached policy, matching
|
||||
statement conditions, and no other applicable grants or denies:
|
||||
|
||||
| Existing policy | Own password before | Own password after | Create/reset another user, before and after |
|
||||
| --- | --- | --- | --- |
|
||||
| S3 read grant only | Allowed | Allowed | Denied |
|
||||
| `Deny admin:CreateUser` | Denied | **Allowed** | Denied |
|
||||
| `Deny admin:ChangeMyPassword` | Allowed | **Denied** | Denied |
|
||||
| `Allow admin:CreateUser` | Allowed | Allowed | Allowed |
|
||||
| `Allow admin:CreateUser` plus `Deny admin:ChangeMyPassword` | Allowed | **Denied** | Allowed |
|
||||
| Deny both actions, or `Deny admin:*` | Denied | Denied | Denied |
|
||||
|
||||
Wildcard denies that match `admin:CreateUser` but do not match
|
||||
`admin:ChangeMyPassword`, such as `admin:Create*`, have the same password
|
||||
compatibility change as the explicit CreateUser deny. An Allow never overrides
|
||||
a matching Deny. Granting only `admin:ChangeMyPassword` does not grant user
|
||||
administration.
|
||||
|
||||
The policy JSON format, stored documents and endpoint are retained, but that
|
||||
does not preserve their authorization semantics. This update does not rewrite
|
||||
saved policies or provide a switch that restores the old action mapping.
|
||||
|
||||
## Preserve the behavior of existing policies
|
||||
|
||||
A saved `Deny admin:CreateUser` still prevents user creation and password resets
|
||||
for other users. It no longer prevents the caller from changing their own
|
||||
password. If an existing policy used that deny to lock the caller's password,
|
||||
add `admin:ChangeMyPassword` to the **same Deny statement before upgrading**.
|
||||
For example, change that statement's action list to:
|
||||
|
||||
```json
|
||||
{
|
||||
"Effect": "Deny",
|
||||
"Action": ["admin:CreateUser", "admin:ChangeMyPassword"]
|
||||
}
|
||||
```
|
||||
|
||||
This is a statement fragment, not a replacement for the entire policy.
|
||||
Preserve its other actions, resource scope and conditions, and all other
|
||||
statements. Check policies attached through groups as well as directly to users.
|
||||
The preceding SILO package version already recognizes both action names, so
|
||||
this dual deny can be prepared before the Server upgrade. Saved policy files
|
||||
are not migrated automatically; the operator must apply this change where the
|
||||
old password restriction is intended.
|
||||
|
||||
To adopt the new split and lock only the caller's password while allowing
|
||||
separately granted user administration, deny only `admin:ChangeMyPassword`.
|
||||
That finer distinction is enforced only by Servers containing this change.
|
||||
|
||||
## Built-in read-only policies
|
||||
|
||||
The built-in `readonly` policy now grants its original S3 read operations
|
||||
without its previous CreateUser deny. This has two compatibility effects:
|
||||
|
||||
- A user of the old `readonly` policy could not change their own password; with
|
||||
the split they can, unless another applicable statement denies
|
||||
`admin:ChangeMyPassword`.
|
||||
- The old built-in `readonly` deny overrode a separate CreateUser Allow. The
|
||||
new built-in definition allows that independently granted user administration.
|
||||
This can broaden effective permissions for users with both policies attached.
|
||||
|
||||
The added `consolereadonly` policy also grants ListBucket for Console browsing
|
||||
and follows the new split. Neither read-only policy grants user administration
|
||||
or S3 writes on its own. Their S3 permissions do not implicitly lock passwords.
|
||||
|
||||
Saved policies and user overrides of canned policies are preserved on upgrade.
|
||||
A saved copy of the old read-only policy retains its CreateUser deny and still
|
||||
blocks a separate CreateUser Allow, even though it no longer blocks self-service
|
||||
password changes. Where no saved override exists, Server uses the updated
|
||||
built-in definition. Review the effective policy documents rather than assuming
|
||||
every policy named `readonly` has the same contents. To retain both old
|
||||
restrictions, attach a policy denying both actions or retain the saved readonly
|
||||
override and add ChangeMyPassword to its existing deny.
|
||||
|
||||
## Console and package callers
|
||||
|
||||
`silo-pkg`'s `Policy.IsAllowedActions` now reports `admin:ChangeMyPassword` as
|
||||
implicit unless denied, and reports `admin:CreateUser` only when explicitly
|
||||
allowed. Its Go signature and the Go compatibility floor are unchanged, but
|
||||
its returned capabilities change. Console and other consumers must stop using
|
||||
the CreateUser capability as a proxy for permission to change one's own password.
|
||||
|
||||
## Coordinated upgrade and rollback
|
||||
|
||||
Upgrade SILO Server, silo-pkg and Console together, including the Console
|
||||
embedded in Server. Update mcli's shared package and SDK pins as part of the
|
||||
same maintained stack. Mixed versions disagree about the self-service action
|
||||
and may show a button the Server refuses, hide an allowed operation, or fail to
|
||||
enforce a new password-specific deny on an old Server.
|
||||
|
||||
Before upgrading, export the affected user/group policy documents, review the
|
||||
cases above, and apply both denies wherever the old combined restriction must
|
||||
survive. Keep both denies throughout a rolling upgrade and any rollback window.
|
||||
Verify self-service password changes and other-user creation/password resets
|
||||
with the affected accounts. Complete the Server rollout and update Console
|
||||
before relying on the new independent permissions.
|
||||
|
||||
Rolling back the binaries does not convert policies. An old Server ignores
|
||||
`Deny admin:ChangeMyPassword` for this endpoint, so that deny alone cannot lock
|
||||
the password after rollback. Restore or retain the CreateUser deny when the
|
||||
password must remain locked; on the old Server it will also deny management of
|
||||
other users. The old Server cannot represent the new combination of allowing
|
||||
user administration while denying only self-service password changes.
|
||||
|
||||
Upstream MinIO compatibility remains best effort; the supported integration
|
||||
target is `pgsty/silo`.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,184 @@
|
||||
# SILO stack: Go 1.27 compatibility audit
|
||||
|
||||
2026-09-09. Scope: the maintained Server, silo-pkg, mcli, and Console. This extends
|
||||
the [OIDC #154 investigation](issue-154.md) to other paths using the same TLS
|
||||
configuration and to adjacent standard-library changes. It records local
|
||||
validation performed before commit. No pushes, issue comments, releases, or
|
||||
production changes were made during the audit.
|
||||
|
||||
## Findings and changes
|
||||
|
||||
| Component | Finding | Change |
|
||||
| --- | --- | --- |
|
||||
| Server, baseline `d1105bbb3d4a0afa33b3a4ac11b821235038ed0e` | Eight TLS configuration sites explicitly use the same ML-KEM-containing curve list, overriding `tlsmlkem=0` in Go 1.27. | Remove the eight assignments and obsolete `TLSCurveIDs` helper. Retain Go defaults in HTTP clients, replication, cloud client-certificate transport, both grid links, etcd, and the S3 listener. Add wire-level regression tests. |
|
||||
| silo-pkg, baseline `a92c54d` | No built-in explicit PQ curve list. Web environment transport uses defaults; LDAP/OIDC accept caller configuration. | Add a real web-environment TLS regression test and document runtime-default selection. Keep the Go 1.26 library floor. |
|
||||
| mcli, baseline `fcd5cad8` | S3/Admin transport and alias/TOFU dialer use default curves. No instance of the Server's override bug found. | Add real S3/Admin transport and alias-dialer handshake tests; update Go/TLS upgrade notes. |
|
||||
| Console, baseline `c103d08ec` | IdP, SILO/STS, Prometheus, and webhook clients share a transport using defaults. The HTTPS listener explicitly uses only P-256. | Add real IdP/SILO-client handshake tests; update Go/TLS upgrade notes. Retain the existing listener policy. |
|
||||
|
||||
The Server's general external HTTP transport is also used by OpenID discovery
|
||||
and JWKS, identity plugins, notification/lambda checks, audit/log webhooks, and
|
||||
S3 cloud backends. Fixing only the two OIDC callers would leave those other paths
|
||||
affected. The broader correction supersedes the earlier OIDC-only candidate.
|
||||
|
||||
The retained defaults follow Go's implementation rather than duplicating its
|
||||
`GODEBUG` parser. Go 1.27 explicitly changed the interaction between manually
|
||||
selected curves and the `tlsmlkem`/`tlssecpmlkem` default controls. See the
|
||||
[Go TLS release notes](https://go.dev/doc/go1.27#crypto/tls).
|
||||
|
||||
With no opt-out, default curves additionally include SecP256r1MLKEM768 and
|
||||
SecP384r1MLKEM1024. With `GODEBUG=tlsmlkem=0`, hybrid exchanges are disabled for
|
||||
default-configured TLS throughout the process. This is an intentional change
|
||||
from the old fixed subset. `GODEBUG=tlssecpmlkem=0` disables just the SecP
|
||||
hybrids while retaining X25519MLKEM768. TLS versions, cipher-suite policy,
|
||||
certificate and hostname checks, client certificates, proxies, and HTTP/2 choices are not
|
||||
relaxed by this patch. No automatic fallback after a TLS error is introduced.
|
||||
|
||||
## Reproduction and regression evidence
|
||||
|
||||
Before changing product code, the new Server test failed for all five tested
|
||||
outbound constructors with `tlsmlkem=0`: general external HTTP, internode HTTP,
|
||||
replication, cloud client certificates, and etcd. The server observed
|
||||
`[X25519MLKEM768 X25519 P256 P384 P521]` in every case. Both TLS 1.2 and TLS 1.3
|
||||
peers reproduced the problem. The inbound Server also accepted a PQ-only client
|
||||
despite the same opt-out.
|
||||
|
||||
After the change, those tests pass on darwin/arm64 and linux/arm64. They exercise
|
||||
20 outbound combinations (five constructors, two peer TLS versions, two debug
|
||||
settings), plus inbound classical/PQ-only peers with the opt-out enabled and
|
||||
disabled. The inbound opt-out case rejects a PQ-only peer while continuing to
|
||||
accept P-256. The etcd test exercises its actual TLS configuration, not an etcd
|
||||
cluster; the client-certificate test exercises construction/loading, not a full
|
||||
mutual-authentication service.
|
||||
|
||||
The mc, Console, and silo-pkg handshake tests pass without product code changes.
|
||||
All use a trusted synthetic certificate and inspect a real ClientHello. They
|
||||
check both disabling and retaining ML-KEM. Console also retains its existing
|
||||
unknown-CA, hostname, and endpoint-scoping regression checks.
|
||||
|
||||
A freshly source-built complete Linux Server then passed three isolated
|
||||
integration scenarios using the existing synthetic IdP fixture:
|
||||
|
||||
| Scenario | Result |
|
||||
| --- | --- |
|
||||
| ML-KEM-intolerant IdP + `tlsmlkem=0` | Discovery/JWKS, IAM, Console, and authenticated Admin calls succeed; login 204 and bucket list 200. |
|
||||
| Normal TLS 1.3 IdP, no opt-out | Same successful login, token exchange, STS, session, and bucket-list chain. |
|
||||
| Add OIDC to a running Server | Actual Admin API accepts the provider under the compatibility setting. |
|
||||
|
||||
Both login scenarios reject modified JWT signatures and a wrong audience: no
|
||||
session cookie is issued and authenticated bucket access returns 403. Login
|
||||
currently reports these authentication failures as 500; that existing error
|
||||
mapping is outside this TLS change. Curl in the same namespace returns HTTP/2
|
||||
200. The containers use a pre-existing generic Debian image, `--network none`,
|
||||
and no published ports; no Server or Console image was downloaded or used.
|
||||
|
||||
The fixture drives real Console HTTP APIs, not rendered browser interaction.
|
||||
This is a conditional interoperability reproduction, not proof of the actual
|
||||
customer ingress behavior. Grid's existing tests pass, but a production-style
|
||||
distributed TLS cluster, external cloud providers, and real etcd/LDAP/Keycloak
|
||||
deployments were not exercised. Disabling ML-KEM does not disable new ML-DSA
|
||||
signature offers and does not repair an ingress that rejects those offers.
|
||||
|
||||
## Other Go changes checked
|
||||
|
||||
### macOS root certificates: a confirmed upgrade-visible change
|
||||
|
||||
Using the same public synthetic CA and `certs.GetRootCAs`, fresh-process probes
|
||||
produce the following results when `SSL_CERT_FILE` points at that CA and
|
||||
`SSL_CERT_DIR` points at an empty directory:
|
||||
|
||||
| Compiler / main module | CA from environment trusted? | Explicit CA argument trusted? |
|
||||
| --- | --- | --- |
|
||||
| Go 1.26.5 / `go 1.26.0` | No | Yes |
|
||||
| Go 1.27.1 / `go 1.26.0` | No | Yes |
|
||||
| Go 1.27.1 / `go 1.27.1` | Yes | Yes |
|
||||
|
||||
The Go 1.26 module built by Go 1.27 carries
|
||||
`DefaultGODEBUG=...x509sslcertoverrideplatform=0`; explicitly setting that option
|
||||
to `1` enables the new behavior. A Go 1.27 application can explicitly set it to
|
||||
`0` to recover the previous platform behavior. The diagnostic source is
|
||||
[cert-roots.go](issue-154/cert-roots.go). The consuming application's defaults
|
||||
apply to library calls as well, so silo-pkg's older `go` directive does not
|
||||
prevent the behavior in Server, mc, or Console.
|
||||
|
||||
This is expected standard-library behavior, not a reason to silently discard
|
||||
configured CA variables or skip verification. Setting either variable replaces
|
||||
Keychain trust with on-disk roots and Go's verifier; stale or incomplete paths
|
||||
can break previously trusted connections. Unset inherited variables to restore
|
||||
Keychain trust; explicit additional CAs still work. The three application
|
||||
READMEs and the package README now document this. The package's Windows loader enumerates
|
||||
the native ROOT store directly and does not call `SystemCertPool`; it does not
|
||||
inherit this particular new setting. Windows behavior was reviewed in source,
|
||||
not runtime-tested.
|
||||
|
||||
### JSON, HTTP, timers, and other compatibility controls
|
||||
|
||||
- **JSON:** checked owned JSON error handling and exercised policy/condition,
|
||||
config, and authentication tests. `quick` uses typed `SyntaxError` and
|
||||
`UnmarshalTypeError`; no owned decision depending on changed standard JSON
|
||||
error text was found. silo-pkg's full suite passes with both Go compilers;
|
||||
mc's command and Console's API/auth suites pass under Go 1.27. No broad
|
||||
`nojsonv2` opt-out or serialization rewrite is justified by these results.
|
||||
- **HTTP response closing:** Go 1.27's standard-library drain is bounded at
|
||||
256 KiB and 50 ms. mc's actual early-close/cancel regression passes, including
|
||||
the compressed S3 Select stream. Existing owned drain helpers can still have
|
||||
independent timeout concerns; those are not newly caused by this Go change.
|
||||
- **ALPN and custom connections:** mc's TLS dialer returns a real `*tls.Conn`;
|
||||
its deadline wrapper is on the TCP dial path. No new accidental HTTP/2 opt-in
|
||||
from the expanded `ConnectionState` interface support was identified in
|
||||
these transports. Console keeps its existing transport policy.
|
||||
- **Removed switches:** no maintained runtime/config reliance on `tlsrsakex`,
|
||||
`tls3des`, `tls10server`, `x509keypairleaf`, or `asynctimerchan` was found.
|
||||
Existing explicit cipher policies continue to be explicit. Timer uses in
|
||||
package certificate reload and license refresh do not depend on buffered
|
||||
timer-channel length/capacity. Unix EOF error changes do not expose a matching
|
||||
owned error-type assumption on the reviewed Unix-socket paths.
|
||||
- **Platform floor:** application READMEs now identify macOS 13 as the minimum
|
||||
for Go 1.27 binaries. No Windows, old macOS, or PowerPC runtime claim is made.
|
||||
|
||||
## Validation and delivery
|
||||
|
||||
- Server: focused TLS tests on macOS and Linux; macOS race run; crypto, HTTP,
|
||||
grid, and all `internal/config/...` tests; full Linux Server build and the
|
||||
three integration scenarios above.
|
||||
- silo-pkg: `make test` (lint and full race suite) on Go 1.27.1; full suite on
|
||||
Go 1.26.5, preserving the library floor.
|
||||
- mc: complete `./cmd` suite, including the new TLS test and existing S3 Select
|
||||
early-cancel test.
|
||||
- Console: complete `./api/... ./pkg/...` suites, including identity and STS
|
||||
validation and the new handshake tests.
|
||||
|
||||
Go lint reports zero issues in all four repositories. Server's optional spelling
|
||||
check is skipped because `typos` is not installed. Its lint target used the
|
||||
already-installed matching golangci-lint v2.13.1 after a redundant download was
|
||||
stopped; mc's lint was rerun serially after the global linter lock prevented the
|
||||
first concurrent attempt. These tooling retries did not require source changes.
|
||||
|
||||
An independent Fable 5.1 Max review reproduced the old-code failures and ran the
|
||||
new TLS tests with the race detector. Its shuffled mc and Console suites passed.
|
||||
One shuffled silo-pkg run failed the untouched `certs.TestValidPairAfterWrite`;
|
||||
that test passed three plain reruns, the same shuffle seed, and the full certs
|
||||
package rerun. The certs package runs in a separate test binary from the changed
|
||||
env tests; this was classified as an existing timing flake.
|
||||
|
||||
The review also found that committing the diagnostic fixture made rebrand CI
|
||||
count synthetic IdP paths as product routes. The guard now excludes
|
||||
`docs/investigations/`; the product compatibility baseline is unchanged.
|
||||
The full proposed file set passes the guard, and a negative control adding a
|
||||
product route still fails. After the review corrections, a fresh Linux Server
|
||||
build passed all three integration scenarios again; the new binary identity and
|
||||
rerun results are recorded in the evidence file's `post_review_validation`.
|
||||
|
||||
All source and dependency choices remain those of the maintained PGSTY stack.
|
||||
`go.mod` and `go.sum` are unchanged in every repository. The Server uses its
|
||||
existing pinned Console/pkg/mc modules; the companion changes are tests and
|
||||
documentation, so no replacement graph or unpublished dependency version is
|
||||
needed to build the runtime fix.
|
||||
|
||||
Validation used separate worktrees for Server, silo-pkg, mc, and Console, leaving
|
||||
the original repositories and their `main` branches untouched. Build identities,
|
||||
fixture results, and command outcomes are recorded in
|
||||
[go127-stack-evidence.json](go127-stack-evidence.json). Absolute paths and branch
|
||||
names in the captured evidence identify the environment at recording time.
|
||||
The recorded module graph identifies the dependencies selected for those
|
||||
builds; `go.sum` also retains checksums for unselected versions. Local image IDs
|
||||
and temporary paths are historical evidence, not portable setup instructions.
|
||||
@@ -0,0 +1,534 @@
|
||||
{
|
||||
"date": "2026-09-11",
|
||||
"runs": [
|
||||
{
|
||||
"runid": "silo-v1-0806-9c53f14c",
|
||||
"version": "0806",
|
||||
"image": "sha256:29a498b24669cae1fed11c1a2fb2b3d73c68829a0a9c0b14e71b386671d38fac",
|
||||
"nodes": 4,
|
||||
"drives": 4,
|
||||
"filesystem": "Linux tmpfs named volumes, held mounted across server restarts",
|
||||
"drive_bytes": 268435456,
|
||||
"status": "PASS",
|
||||
"phases": [
|
||||
{
|
||||
"phase": "startup-admin",
|
||||
"seconds_from_start": 4.157,
|
||||
"first_online_by_coordinator": [
|
||||
4.037,
|
||||
4.078,
|
||||
4.118,
|
||||
3.737
|
||||
]
|
||||
},
|
||||
{
|
||||
"phase": "startup-canary",
|
||||
"attempts": 1,
|
||||
"puts": 4,
|
||||
"gets": 16,
|
||||
"hard_deadline_seconds": 60,
|
||||
"gate_seconds": 0.239,
|
||||
"seconds_from_start": 4.396,
|
||||
"first_put_seconds_after_admin_by_coordinator": [
|
||||
0.096,
|
||||
0.116,
|
||||
0.127,
|
||||
0.138
|
||||
],
|
||||
"first_four_reads_seconds_after_admin_by_coordinator": [
|
||||
0.162,
|
||||
0.194,
|
||||
0.217,
|
||||
0.239
|
||||
],
|
||||
"transient_error_count": 0,
|
||||
"first_transient_errors": []
|
||||
},
|
||||
{
|
||||
"phase": "full-restart-admin",
|
||||
"seconds_from_start": 2.084,
|
||||
"first_online_by_coordinator": [
|
||||
1.937,
|
||||
1.976,
|
||||
2.016,
|
||||
1.643
|
||||
]
|
||||
},
|
||||
{
|
||||
"phase": "full-restart-canary",
|
||||
"attempts": 45,
|
||||
"puts": 4,
|
||||
"gets": 16,
|
||||
"hard_deadline_seconds": 60,
|
||||
"gate_seconds": 14.449,
|
||||
"seconds_from_start": 16.534,
|
||||
"first_put_seconds_after_admin_by_coordinator": [
|
||||
14.315,
|
||||
13.573,
|
||||
13.953,
|
||||
0.05
|
||||
],
|
||||
"first_four_reads_seconds_after_admin_by_coordinator": [
|
||||
14.373,
|
||||
14.396,
|
||||
14.426,
|
||||
14.449
|
||||
],
|
||||
"transient_error_count": 129,
|
||||
"first_transient_errors": [
|
||||
{
|
||||
"attempt": 1,
|
||||
"operation": "put",
|
||||
"node": 0,
|
||||
"error": "An error occurred (SlowDownWrite) when calling the PutObject operation (reached max retries: 0): Resource requested is unwritable, please reduce your request rate"
|
||||
},
|
||||
{
|
||||
"attempt": 1,
|
||||
"operation": "put",
|
||||
"node": 1,
|
||||
"error": "An error occurred (SlowDownWrite) when calling the PutObject operation (reached max retries: 0): Resource requested is unwritable, please reduce your request rate"
|
||||
},
|
||||
{
|
||||
"attempt": 1,
|
||||
"operation": "put",
|
||||
"node": 2,
|
||||
"error": "An error occurred (SlowDownWrite) when calling the PutObject operation (reached max retries: 0): Resource requested is unwritable, please reduce your request rate"
|
||||
},
|
||||
{
|
||||
"attempt": 2,
|
||||
"operation": "put",
|
||||
"node": 0,
|
||||
"error": "An error occurred (SlowDownWrite) when calling the PutObject operation (reached max retries: 0): Resource requested is unwritable, please reduce your request rate"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"phase": "readback-15s",
|
||||
"seconds_after_canary": 17.596,
|
||||
"objects": 55,
|
||||
"reads": 220,
|
||||
"errors": []
|
||||
},
|
||||
{
|
||||
"phase": "readback-30s",
|
||||
"seconds_after_canary": 31.357,
|
||||
"objects": 55,
|
||||
"reads": 220,
|
||||
"errors": []
|
||||
},
|
||||
{
|
||||
"phase": "readback-60s",
|
||||
"seconds_after_canary": 61.566,
|
||||
"objects": 55,
|
||||
"reads": 220,
|
||||
"errors": []
|
||||
},
|
||||
{
|
||||
"phase": "one-node-outage",
|
||||
"existing_read": true,
|
||||
"put": true,
|
||||
"readers": 3
|
||||
},
|
||||
{
|
||||
"phase": "rejoin-admin",
|
||||
"seconds_from_start": 1.382,
|
||||
"first_online_by_coordinator": [
|
||||
1.27,
|
||||
1.307,
|
||||
1.343,
|
||||
1.382
|
||||
]
|
||||
},
|
||||
{
|
||||
"phase": "rejoin-canary",
|
||||
"attempts": 1,
|
||||
"puts": 4,
|
||||
"gets": 16,
|
||||
"hard_deadline_seconds": 60,
|
||||
"gate_seconds": 0.158,
|
||||
"seconds_from_start": 1.541,
|
||||
"first_put_seconds_after_admin_by_coordinator": [
|
||||
0.013,
|
||||
0.029,
|
||||
0.039,
|
||||
0.05
|
||||
],
|
||||
"first_four_reads_seconds_after_admin_by_coordinator": [
|
||||
0.077,
|
||||
0.102,
|
||||
0.132,
|
||||
0.158
|
||||
],
|
||||
"transient_error_count": 0,
|
||||
"first_transient_errors": []
|
||||
},
|
||||
{
|
||||
"phase": "final-readback",
|
||||
"seconds_after_canary": 1.71,
|
||||
"objects": 60,
|
||||
"reads": 240,
|
||||
"errors": []
|
||||
}
|
||||
],
|
||||
"acknowledged_objects": 60,
|
||||
"version_ids_recorded": true,
|
||||
"sha256_recorded": true
|
||||
},
|
||||
{
|
||||
"runid": "silo-v1-0903-a457573c",
|
||||
"version": "0903",
|
||||
"image": "sha256:b616a0cf8cb281e7e6bb3c9b1fb53875b4016a2878223925541c18f82d6c5ca3",
|
||||
"nodes": 4,
|
||||
"drives": 4,
|
||||
"filesystem": "Linux tmpfs named volumes, held mounted across server restarts",
|
||||
"drive_bytes": 268435456,
|
||||
"status": "PASS",
|
||||
"phases": [
|
||||
{
|
||||
"phase": "startup-admin",
|
||||
"seconds_from_start": 4.271,
|
||||
"first_online_by_coordinator": [
|
||||
4.158,
|
||||
4.194,
|
||||
3.827,
|
||||
3.867
|
||||
]
|
||||
},
|
||||
{
|
||||
"phase": "startup-canary",
|
||||
"attempts": 1,
|
||||
"puts": 4,
|
||||
"gets": 16,
|
||||
"hard_deadline_seconds": 60,
|
||||
"gate_seconds": 0.2,
|
||||
"seconds_from_start": 4.471,
|
||||
"first_put_seconds_after_admin_by_coordinator": [
|
||||
0.054,
|
||||
0.068,
|
||||
0.081,
|
||||
0.092
|
||||
],
|
||||
"first_four_reads_seconds_after_admin_by_coordinator": [
|
||||
0.118,
|
||||
0.146,
|
||||
0.167,
|
||||
0.2
|
||||
],
|
||||
"transient_error_count": 0,
|
||||
"first_transient_errors": []
|
||||
},
|
||||
{
|
||||
"phase": "full-restart-admin",
|
||||
"seconds_from_start": 2.284,
|
||||
"first_online_by_coordinator": [
|
||||
2.143,
|
||||
2.193,
|
||||
0.849,
|
||||
0.902
|
||||
]
|
||||
},
|
||||
{
|
||||
"phase": "full-restart-canary",
|
||||
"attempts": 1,
|
||||
"puts": 4,
|
||||
"gets": 16,
|
||||
"hard_deadline_seconds": 60,
|
||||
"gate_seconds": 0.191,
|
||||
"seconds_from_start": 2.476,
|
||||
"first_put_seconds_after_admin_by_coordinator": [
|
||||
0.016,
|
||||
0.029,
|
||||
0.044,
|
||||
0.057
|
||||
],
|
||||
"first_four_reads_seconds_after_admin_by_coordinator": [
|
||||
0.093,
|
||||
0.124,
|
||||
0.158,
|
||||
0.192
|
||||
],
|
||||
"transient_error_count": 0,
|
||||
"first_transient_errors": []
|
||||
},
|
||||
{
|
||||
"phase": "readback-15s",
|
||||
"seconds_after_canary": 15.235,
|
||||
"objects": 8,
|
||||
"reads": 32,
|
||||
"errors": []
|
||||
},
|
||||
{
|
||||
"phase": "readback-30s",
|
||||
"seconds_after_canary": 30.356,
|
||||
"objects": 8,
|
||||
"reads": 32,
|
||||
"errors": []
|
||||
},
|
||||
{
|
||||
"phase": "readback-60s",
|
||||
"seconds_after_canary": 60.192,
|
||||
"objects": 8,
|
||||
"reads": 32,
|
||||
"errors": []
|
||||
},
|
||||
{
|
||||
"phase": "one-node-outage",
|
||||
"existing_read": true,
|
||||
"put": true,
|
||||
"readers": 3
|
||||
},
|
||||
{
|
||||
"phase": "rejoin-admin",
|
||||
"seconds_from_start": 0.903,
|
||||
"first_online_by_coordinator": [
|
||||
0.791,
|
||||
0.829,
|
||||
0.865,
|
||||
0.903
|
||||
]
|
||||
},
|
||||
{
|
||||
"phase": "rejoin-canary",
|
||||
"attempts": 1,
|
||||
"puts": 4,
|
||||
"gets": 16,
|
||||
"hard_deadline_seconds": 60,
|
||||
"gate_seconds": 0.141,
|
||||
"seconds_from_start": 1.044,
|
||||
"first_put_seconds_after_admin_by_coordinator": [
|
||||
0.012,
|
||||
0.022,
|
||||
0.035,
|
||||
0.045
|
||||
],
|
||||
"first_four_reads_seconds_after_admin_by_coordinator": [
|
||||
0.069,
|
||||
0.096,
|
||||
0.12,
|
||||
0.141
|
||||
],
|
||||
"transient_error_count": 0,
|
||||
"first_transient_errors": []
|
||||
},
|
||||
{
|
||||
"phase": "final-readback",
|
||||
"seconds_after_canary": 0.301,
|
||||
"objects": 13,
|
||||
"reads": 52,
|
||||
"errors": []
|
||||
}
|
||||
],
|
||||
"acknowledged_objects": 13,
|
||||
"version_ids_recorded": true,
|
||||
"sha256_recorded": true
|
||||
},
|
||||
{
|
||||
"runid": "silo-v1-current-6a14eb18",
|
||||
"version": "current",
|
||||
"image": "pgsty/d12a:build",
|
||||
"image_id": "sha256:307af7711e2e04ab75759cb42a1eef45c43c4404894c0e30dd19f742b107b922",
|
||||
"platform": "linux/arm64",
|
||||
"nodes": 4,
|
||||
"drives": 4,
|
||||
"filesystem": "Linux tmpfs named volumes, held mounted across server restarts",
|
||||
"drive_bytes": 268435456,
|
||||
"status": "PASS",
|
||||
"binary_sha256": "1e4cd7b78ecfa1b0cf28f1961d48a220a712c6be1fd3a01b60ee99aec62f04a4",
|
||||
"source_revision": "b32f2d9dd01a383a9991d34ffe248063463a031d+pool-consistency",
|
||||
"phases": [
|
||||
{
|
||||
"phase": "startup-admin",
|
||||
"seconds_from_start": 7.374,
|
||||
"first_online_by_coordinator": [
|
||||
7.207,
|
||||
6.677,
|
||||
6.74,
|
||||
6.8
|
||||
]
|
||||
},
|
||||
{
|
||||
"phase": "startup-canary",
|
||||
"attempts": 1,
|
||||
"puts": 4,
|
||||
"gets": 16,
|
||||
"hard_deadline_seconds": 60,
|
||||
"gate_seconds": 0.479,
|
||||
"seconds_from_start": 7.854,
|
||||
"first_put_seconds_after_admin_by_coordinator": [
|
||||
0.266,
|
||||
0.279,
|
||||
0.292,
|
||||
0.305
|
||||
],
|
||||
"first_four_reads_seconds_after_admin_by_coordinator": [
|
||||
0.336,
|
||||
0.378,
|
||||
0.431,
|
||||
0.479
|
||||
],
|
||||
"transient_error_count": 0,
|
||||
"first_transient_errors": []
|
||||
},
|
||||
{
|
||||
"phase": "full-restart-admin",
|
||||
"seconds_from_start": 2.461,
|
||||
"first_online_by_coordinator": [
|
||||
2.264,
|
||||
1.414,
|
||||
2.396,
|
||||
2.461
|
||||
]
|
||||
},
|
||||
{
|
||||
"phase": "full-restart-canary",
|
||||
"attempts": 36,
|
||||
"puts": 4,
|
||||
"gets": 16,
|
||||
"hard_deadline_seconds": 60,
|
||||
"gate_seconds": 14.489,
|
||||
"seconds_from_start": 16.951,
|
||||
"first_put_seconds_after_admin_by_coordinator": [
|
||||
0.013,
|
||||
0.025,
|
||||
14.301,
|
||||
0.046
|
||||
],
|
||||
"first_four_reads_seconds_after_admin_by_coordinator": [
|
||||
14.358,
|
||||
14.394,
|
||||
14.435,
|
||||
14.489
|
||||
],
|
||||
"transient_error_count": 104,
|
||||
"first_transient_errors": [
|
||||
{
|
||||
"attempt": 1,
|
||||
"operation": "put",
|
||||
"node": 2,
|
||||
"error": "An error occurred (SlowDownWrite) when calling the PutObject operation (reached max retries: 0): Resource requested is unwritable, please reduce your request rate"
|
||||
},
|
||||
{
|
||||
"attempt": 1,
|
||||
"operation": "get",
|
||||
"node": 2,
|
||||
"key": "full-restart-attempt-1-node-0",
|
||||
"error": "An error occurred (SlowDownRead) when calling the GetObject operation (reached max retries: 0): Resource requested is unreadable, please reduce your request rate"
|
||||
},
|
||||
{
|
||||
"attempt": 1,
|
||||
"operation": "get",
|
||||
"node": 2,
|
||||
"key": "full-restart-attempt-1-node-3",
|
||||
"error": "An error occurred (SlowDownRead) when calling the GetObject operation (reached max retries: 0): Resource requested is unreadable, please reduce your request rate"
|
||||
},
|
||||
{
|
||||
"attempt": 2,
|
||||
"operation": "put",
|
||||
"node": 2,
|
||||
"error": "An error occurred (SlowDownWrite) when calling the PutObject operation (reached max retries: 0): Resource requested is unwritable, please reduce your request rate"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"phase": "readback-15s",
|
||||
"started_seconds_after_canary": 15.0,
|
||||
"seconds_after_canary": 22.006,
|
||||
"objects": 113,
|
||||
"reads": 452,
|
||||
"errors": []
|
||||
},
|
||||
{
|
||||
"phase": "readback-30s",
|
||||
"started_seconds_after_canary": 30.003,
|
||||
"seconds_after_canary": 36.571,
|
||||
"objects": 113,
|
||||
"reads": 452,
|
||||
"errors": []
|
||||
},
|
||||
{
|
||||
"phase": "readback-60s",
|
||||
"started_seconds_after_canary": 60.0,
|
||||
"seconds_after_canary": 65.743,
|
||||
"objects": 113,
|
||||
"reads": 452,
|
||||
"errors": []
|
||||
},
|
||||
{
|
||||
"phase": "one-node-outage",
|
||||
"existing_read": true,
|
||||
"put": true,
|
||||
"readers": 3
|
||||
},
|
||||
{
|
||||
"phase": "rejoin-admin",
|
||||
"seconds_from_start": 2.49,
|
||||
"first_online_by_coordinator": [
|
||||
1.165,
|
||||
2.417,
|
||||
1.646,
|
||||
2.087
|
||||
]
|
||||
},
|
||||
{
|
||||
"phase": "rejoin-canary",
|
||||
"attempts": 37,
|
||||
"puts": 4,
|
||||
"gets": 16,
|
||||
"hard_deadline_seconds": 60,
|
||||
"gate_seconds": 13.977,
|
||||
"seconds_from_start": 16.468,
|
||||
"first_put_seconds_after_admin_by_coordinator": [
|
||||
0.013,
|
||||
0.024,
|
||||
0.035,
|
||||
13.889
|
||||
],
|
||||
"first_four_reads_seconds_after_admin_by_coordinator": [
|
||||
13.909,
|
||||
13.927,
|
||||
13.953,
|
||||
13.977
|
||||
],
|
||||
"transient_error_count": 36,
|
||||
"first_transient_errors": [
|
||||
{
|
||||
"attempt": 1,
|
||||
"operation": "put",
|
||||
"node": 3,
|
||||
"error": "An error occurred (SlowDownWrite) when calling the PutObject operation (reached max retries: 0): Resource requested is unwritable, please reduce your request rate"
|
||||
},
|
||||
{
|
||||
"attempt": 2,
|
||||
"operation": "put",
|
||||
"node": 3,
|
||||
"error": "An error occurred (SlowDownWrite) when calling the PutObject operation (reached max retries: 0): Resource requested is unwritable, please reduce your request rate"
|
||||
},
|
||||
{
|
||||
"attempt": 3,
|
||||
"operation": "put",
|
||||
"node": 3,
|
||||
"error": "An error occurred (SlowDownWrite) when calling the PutObject operation (reached max retries: 0): Resource requested is unwritable, please reduce your request rate"
|
||||
},
|
||||
{
|
||||
"attempt": 4,
|
||||
"operation": "put",
|
||||
"node": 3,
|
||||
"error": "An error occurred (SlowDownWrite) when calling the PutObject operation (reached max retries: 0): Resource requested is unwritable, please reduce your request rate"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"phase": "final-readback",
|
||||
"started_seconds_after_canary": 0.0,
|
||||
"seconds_after_canary": 6.507,
|
||||
"objects": 226,
|
||||
"reads": 904,
|
||||
"errors": []
|
||||
}
|
||||
],
|
||||
"acknowledged_objects": 226,
|
||||
"version_ids_recorded": true,
|
||||
"sha256_recorded": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,327 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Bounded four-container restart/readback acceptance for pgsty/silo#116."""
|
||||
import argparse
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import shutil
|
||||
import signal
|
||||
import socket
|
||||
import subprocess
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
|
||||
ROOT = None
|
||||
MCLI = None
|
||||
CURRENT_BINARY = None
|
||||
SOURCE_REVISION = None
|
||||
IMAGES = {
|
||||
'0806': 'pgsty/silo:RELEASE.2026-08-06T00-00-00Z',
|
||||
'0903': 'pgsty/silo:RELEASE.2026-09-03T13-18-01Z',
|
||||
'current': 'pgsty/d12a:build',
|
||||
}
|
||||
|
||||
|
||||
def docker(*args, timeout=40, check=True):
|
||||
return subprocess.run(['docker', *args], check=check, capture_output=True, text=True, timeout=timeout)
|
||||
|
||||
|
||||
class Deadline(BaseException):
|
||||
pass
|
||||
|
||||
|
||||
def bounded(seconds, operation):
|
||||
def expired(*_):
|
||||
raise Deadline(f'hard deadline of {seconds}s exceeded')
|
||||
old = signal.signal(signal.SIGALRM, expired)
|
||||
signal.setitimer(signal.ITIMER_REAL, seconds)
|
||||
try:
|
||||
return operation(time.monotonic() + seconds)
|
||||
finally:
|
||||
signal.setitimer(signal.ITIMER_REAL, 0)
|
||||
signal.signal(signal.SIGALRM, old)
|
||||
|
||||
|
||||
def remaining(deadline):
|
||||
value = deadline - time.monotonic()
|
||||
if value <= 0:
|
||||
raise Deadline('absolute deadline exceeded')
|
||||
return value
|
||||
|
||||
|
||||
def run(version):
|
||||
image_info = json.loads(docker('image', 'inspect', IMAGES[version]).stdout)[0]
|
||||
runid = f'silo-v1-{version}-{uuid.uuid4().hex[:8]}'
|
||||
out = ROOT / runid
|
||||
out.mkdir(mode=0o700)
|
||||
user, password = 'local116', secrets.token_urlsafe(24)
|
||||
envfile = out / 'credentials.env'
|
||||
envfile.write_text(f'MINIO_ROOT_USER={user}\nMINIO_ROOT_PASSWORD={password}\nMINIO_CI_CD=1\nMINIO_BROWSER=off\nGOMAXPROCS=2\n')
|
||||
envfile.chmod(0o600)
|
||||
env = {k: v for k, v in os.environ.items() if not k.startswith(('MINIO_', 'SILO_', 'MC_'))
|
||||
and k.lower() not in {'http_proxy', 'https_proxy', 'all_proxy', 'no_proxy'}}
|
||||
nodes = [f'{runid}-n{i}' for i in range(4)]
|
||||
sockets = [socket.socket() for _ in nodes]
|
||||
for sock in sockets:
|
||||
sock.bind(('127.0.0.1', 0))
|
||||
ports = [sock.getsockname()[1] for sock in sockets]
|
||||
for sock in sockets:
|
||||
sock.close()
|
||||
volumes = [n + '-data' for n in nodes]
|
||||
endpoints, ledger = [], []
|
||||
result = {'runid': runid, 'version': version, 'image': IMAGES[version],
|
||||
'image_id': image_info['Id'], 'platform': image_info['Os']+'/'+image_info['Architecture'],
|
||||
'nodes': 4,
|
||||
'drives': 4, 'filesystem': 'Linux tmpfs named volumes, held mounted across server restarts',
|
||||
'drive_bytes': 268435456, 'phases': [], 'status': 'RUNNING'}
|
||||
if version == 'current':
|
||||
result['binary_sha256'] = hashlib.sha256(CURRENT_BINARY.read_bytes()).hexdigest()
|
||||
result['source_revision'] = SOURCE_REVISION
|
||||
bucket = 'canary-' + uuid.uuid4().hex[:10]
|
||||
|
||||
def save(event=None):
|
||||
if event is not None:
|
||||
result['phases'].append(event)
|
||||
compact = {k: (len(v) if k in ('transient_errors', 'errors') else v) for k, v in event.items()}
|
||||
print(json.dumps({'version': version, **compact}), flush=True)
|
||||
(out / 'result.json').write_text(json.dumps(result, indent=2) + '\n')
|
||||
(out / 'acknowledged.json').write_text(json.dumps(ledger, indent=2) + '\n')
|
||||
|
||||
def parallel(fn, values):
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
return list(pool.map(fn, values))
|
||||
|
||||
def client(i, deadline):
|
||||
timeout = remaining(deadline)
|
||||
return boto3.client('s3', endpoint_url=endpoints[i], aws_access_key_id=user,
|
||||
aws_secret_access_key=password, region_name='us-east-1',
|
||||
config=Config(proxies={}, signature_version='s3v4', s3={'addressing_style': 'path'},
|
||||
retries={'total_max_attempts': 1}, connect_timeout=timeout,
|
||||
read_timeout=timeout, request_checksum_calculation='when_required',
|
||||
response_checksum_validation='when_required'))
|
||||
|
||||
def admin_gate(origin, phase):
|
||||
def check(deadline):
|
||||
first = [None] * 4
|
||||
while True:
|
||||
states = []
|
||||
for i in range(4):
|
||||
try:
|
||||
p = subprocess.run([str(MCLI), '--config-dir', str(out / 'mcli'), '--json',
|
||||
'admin', 'info', f'n{i}'], env=env, capture_output=True,
|
||||
text=True, timeout=min(5, remaining(deadline)))
|
||||
info = json.loads(p.stdout)['info']
|
||||
servers = info['servers']
|
||||
ok = len(servers) == 4 and all(s.get('state') == 'online' and s.get('drives')
|
||||
and all(d.get('state') == 'ok' for d in s['drives'])
|
||||
and all(v == 'online' for v in s.get('network', {}).values()) for s in servers)
|
||||
if ok:
|
||||
(out / f'{phase}-admin-{i}.json').write_text(json.dumps(info, indent=2) + '\n')
|
||||
if first[i] is None:
|
||||
first[i] = round(time.monotonic() - origin, 3)
|
||||
states.append(ok)
|
||||
except (Exception,):
|
||||
states.append(False)
|
||||
if all(states):
|
||||
event = {'phase': phase + '-admin', 'seconds_from_start': round(time.monotonic()-origin, 3),
|
||||
'first_online_by_coordinator': first}
|
||||
save(event)
|
||||
return time.monotonic()
|
||||
time.sleep(min(.25, remaining(deadline)))
|
||||
return bounded(90, check)
|
||||
|
||||
def canary(phase, origin, admin_time, setup=False):
|
||||
def check(deadline):
|
||||
started = time.monotonic()
|
||||
first_put, first_reads = [None] * 4, [None] * 4
|
||||
errors, attempt, setup_done = [], 0, not setup
|
||||
result['active_canary'] = {'phase': phase, 'errors': errors}
|
||||
while True:
|
||||
attempt += 1
|
||||
remaining(deadline)
|
||||
if not setup_done:
|
||||
try:
|
||||
try:
|
||||
client(0, deadline).create_bucket(Bucket=bucket)
|
||||
except Exception as e:
|
||||
if 'BucketAlreadyOwnedByYou' not in str(e):
|
||||
raise
|
||||
client(0, deadline).put_bucket_versioning(Bucket=bucket, VersioningConfiguration={'Status': 'Enabled'})
|
||||
setup_done = True
|
||||
except Exception as e:
|
||||
errors.append({'attempt': attempt, 'operation': 'setup', 'error': str(e)[:250]})
|
||||
time.sleep(min(.25, remaining(deadline)))
|
||||
continue
|
||||
acked = []
|
||||
for i in range(4):
|
||||
key = f'{phase}-attempt-{attempt}-node-{i}'
|
||||
payload = (key + '\n').encode() * 16384
|
||||
try:
|
||||
vid = client(i, deadline).put_object(Bucket=bucket, Key=key, Body=payload)['VersionId']
|
||||
entry = {'phase': phase, 'key': key, 'version': vid, 'bytes': len(payload),
|
||||
'sha256': hashlib.sha256(payload).hexdigest(), 'writer': i,
|
||||
'ack_seconds_from_start': round(time.monotonic()-origin, 3)}
|
||||
ledger.append(entry)
|
||||
save() # Persist every acknowledged write, including failed rounds.
|
||||
acked.append(entry)
|
||||
if first_put[i] is None:
|
||||
first_put[i] = round(time.monotonic()-admin_time, 3)
|
||||
except Exception as e:
|
||||
errors.append({'attempt': attempt, 'operation': 'put', 'node': i, 'error': str(e)[:250]})
|
||||
reads = 0
|
||||
for i in range(4):
|
||||
own_reads = 0
|
||||
for entry in acked:
|
||||
try:
|
||||
verify(i, entry, deadline)
|
||||
reads += 1
|
||||
own_reads += 1
|
||||
except Exception as e:
|
||||
errors.append({'attempt': attempt, 'operation': 'get', 'node': i,
|
||||
'key': entry['key'], 'error': str(e)[:250]})
|
||||
if own_reads == 4 and first_reads[i] is None:
|
||||
first_reads[i] = round(time.monotonic()-admin_time, 3)
|
||||
remaining(deadline)
|
||||
if len(acked) == 4 and reads == 16:
|
||||
result.pop('active_canary', None)
|
||||
save({'phase': phase + '-canary', 'attempts': attempt, 'puts': 4, 'gets': 16,
|
||||
'hard_deadline_seconds': 60, 'gate_seconds': round(time.monotonic()-started, 3),
|
||||
'seconds_from_start': round(time.monotonic()-origin, 3),
|
||||
'first_put_seconds_after_admin_by_coordinator': first_put,
|
||||
'first_four_reads_seconds_after_admin_by_coordinator': first_reads, 'transient_errors': errors})
|
||||
return time.monotonic()
|
||||
(out / f'{phase}-canary-errors.json').write_text(json.dumps(errors, indent=2) + '\n')
|
||||
if attempt == 1:
|
||||
print(json.dumps({'version': version, 'phase': phase, 'first_attempt_errors': errors}), flush=True)
|
||||
time.sleep(min(.25, remaining(deadline)))
|
||||
return bounded(60, check)
|
||||
|
||||
def verify(i, entry, deadline):
|
||||
got = client(i, deadline).get_object(Bucket=bucket, Key=entry['key'], VersionId=entry['version'])
|
||||
try:
|
||||
data = got['Body'].read()
|
||||
finally:
|
||||
got['Body'].close()
|
||||
assert len(data) == entry['bytes'] and hashlib.sha256(data).hexdigest() == entry['sha256'], entry['key']
|
||||
assert got.get('VersionId') == entry['version'], entry['key']
|
||||
remaining(deadline)
|
||||
|
||||
def readback(label, origin):
|
||||
def check(deadline):
|
||||
started = time.monotonic()
|
||||
errors = []
|
||||
for entry in ledger:
|
||||
for i in range(4):
|
||||
try:
|
||||
verify(i, entry, deadline)
|
||||
except Exception as e:
|
||||
errors.append({'key': entry['key'], 'node': i, 'error': str(e)[:250]})
|
||||
save({'phase': label, 'started_seconds_after_canary': round(started-origin, 3),
|
||||
'seconds_after_canary': round(time.monotonic()-origin, 3),
|
||||
'objects': len(ledger), 'reads': len(ledger)*4, 'errors': errors})
|
||||
return errors
|
||||
return bounded(60, check)
|
||||
|
||||
try:
|
||||
docker('network', 'create', runid)
|
||||
for volume in volumes:
|
||||
docker('volume', 'create', '--driver', 'local', '--opt', 'type=tmpfs',
|
||||
'--opt', 'device=tmpfs', '--opt', 'o=size=256m', volume)
|
||||
mounts = [arg for i, v in enumerate(volumes) for arg in ('--mount', f'type=volume,source={v},target=/keep/{i}')]
|
||||
docker('run', '-d', '--pull=never', '--network', 'none', '--name', runid + '-keeper',
|
||||
*mounts, '--entrypoint', 'sleep', 'alpine:3.23', '1800')
|
||||
urls = [f'http://{n}:9000/data' for n in nodes]
|
||||
def create(i):
|
||||
extra = []
|
||||
if version == 'current':
|
||||
extra = ['--mount', f'type=bind,source={CURRENT_BINARY},target=/lab/silo,readonly',
|
||||
'--entrypoint', '/lab/silo']
|
||||
docker('create', '--pull=never', '--name', nodes[i], '--network', runid,
|
||||
'--hostname', nodes[i], '--cpus', '2', '--memory', '3g', '--env-file', str(envfile),
|
||||
'--mount', f'type=volume,source={volumes[i]},target=/data',
|
||||
'-p', f'127.0.0.1:{ports[i]}:9000', *extra, image_info['Id'], 'server', '--address', ':9000',
|
||||
'--console-address', ':9001', *urls)
|
||||
parallel(create, range(4))
|
||||
start = time.monotonic()
|
||||
parallel(lambda n: docker('start', n), nodes)
|
||||
for i, n in enumerate(nodes):
|
||||
endpoint = 'http://' + docker('port', n, '9000/tcp').stdout.strip()
|
||||
endpoints.append(endpoint)
|
||||
env[f'MC_HOST_n{i}'] = endpoint.replace('http://', f'http://{user}:{password}@')
|
||||
admin = admin_gate(start, 'startup')
|
||||
canary('startup', start, admin, setup=True)
|
||||
parallel(lambda n: docker('stop', '-t', '10', n), nodes)
|
||||
start = time.monotonic()
|
||||
parallel(lambda n: docker('start', n), nodes)
|
||||
admin = admin_gate(start, 'full-restart')
|
||||
gate = canary('full-restart', start, admin)
|
||||
read_errors = []
|
||||
for after in (15, 30, 60):
|
||||
time.sleep(max(0, gate + after - time.monotonic()))
|
||||
read_errors.extend(readback(f'readback-{after}s', gate))
|
||||
assert not read_errors, 'acknowledged object readback failure; see result.json'
|
||||
docker('stop', '-t', '10', nodes[3])
|
||||
def outage(deadline):
|
||||
verify(0, ledger[0], deadline)
|
||||
payload = b'acknowledged with one Linux node offline' * 16384
|
||||
key = 'one-node-outage'
|
||||
vid = client(0, deadline).put_object(Bucket=bucket, Key=key, Body=payload)['VersionId']
|
||||
entry = {'phase': 'outage', 'key': key, 'version': vid, 'bytes': len(payload),
|
||||
'sha256': hashlib.sha256(payload).hexdigest(), 'writer': 0}
|
||||
ledger.append(entry)
|
||||
save()
|
||||
for i in range(3):
|
||||
verify(i, entry, deadline)
|
||||
save({'phase': 'one-node-outage', 'existing_read': True, 'put': True, 'readers': 3})
|
||||
bounded(60, outage)
|
||||
start = time.monotonic()
|
||||
docker('start', nodes[3])
|
||||
admin = admin_gate(start, 'rejoin')
|
||||
gate = canary('rejoin', start, admin)
|
||||
assert not readback('final-readback', gate)
|
||||
result['status'] = 'PASS'
|
||||
except BaseException as e:
|
||||
result['status'] = 'FAIL'
|
||||
result['error'] = f'{type(e).__name__}: {e}'
|
||||
raise
|
||||
finally:
|
||||
save()
|
||||
for n in nodes:
|
||||
log = docker('logs', n, check=False)
|
||||
(out / (n + '.log')).write_text(log.stdout + log.stderr)
|
||||
docker('rm', '-f', n, check=False)
|
||||
docker('rm', '-f', runid + '-keeper', check=False)
|
||||
for v in volumes:
|
||||
docker('volume', 'rm', v, check=False)
|
||||
docker('network', 'rm', runid, check=False)
|
||||
envfile.unlink(missing_ok=True)
|
||||
print(json.dumps({'version': version, 'status': result['status'], 'evidence': str(out)}), flush=True)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument('versions', nargs='+', choices=list(IMAGES))
|
||||
parser.add_argument('--output', type=Path, required=True, help='directory for retained evidence')
|
||||
parser.add_argument('--mcli', default=shutil.which('mcli'), help='native mcli executable')
|
||||
parser.add_argument('--current-binary', type=Path, help='Linux binary matching the Docker architecture')
|
||||
parser.add_argument('--source-revision', help='Git revision of --current-binary')
|
||||
parser.add_argument('--current-image', default=IMAGES['current'], help='cached Linux base image for current binary')
|
||||
args = parser.parse_args()
|
||||
if not args.mcli or not Path(args.mcli).is_file():
|
||||
parser.error('--mcli must point to an executable file')
|
||||
if 'current' in args.versions and (not args.current_binary or not args.current_binary.is_file()):
|
||||
parser.error('current requires --current-binary')
|
||||
ROOT = args.output.resolve()
|
||||
ROOT.mkdir(mode=0o700, parents=True, exist_ok=True)
|
||||
MCLI = Path(args.mcli).resolve()
|
||||
CURRENT_BINARY = args.current_binary.resolve() if args.current_binary else None
|
||||
SOURCE_REVISION = args.source_revision
|
||||
IMAGES['current'] = args.current_image
|
||||
for version in args.versions:
|
||||
run(version)
|
||||
@@ -0,0 +1,403 @@
|
||||
# SILO #154:OIDC discovery 连接重置调查
|
||||
|
||||
前两轮调查时间:2026-09-09;公开 issue 最后核对于 07:53 UTC。第二轮补充同源码、同依赖、不同 Go 工具链的 Linux 完整 Server 对照和候选补丁认证链路验证。
|
||||
|
||||
**后续更新:用户已授权扩展至整个 SILO 技术栈并修复。现已确认 Server 其他 TLS 路径也存在同类覆盖问题,并在产品工作区完成统一使用 Go 默认曲线的修复。当前实现、验证和交付状态见 [全栈调查](go127-stack.md)。下文保留前两轮的诊断与当时的 OIDC 局部候选;“未修改产品”和“不要扩大范围”等表述仅适用于当时的调查阶段,局部候选已被后续全路径修复取代。**
|
||||
|
||||
## 判断与处理顺序
|
||||
|
||||
**目前可以确认是 Server 发出的 discovery GET 失败,随后 IAM 初始化等待,Console 初始化也被延后;还不能确认真实连接由谁、在哪个协议阶段重置。优先调查 SILO/Go 客户端与 IdP 前置 TLS 终止器、代理或 WAF 的互操作。** 现有证据不支持将其定性为证书错误、Keycloak 配置错误、JWT 校验错误或 `coreos/go-oidc` 回归。
|
||||
|
||||
有两项与版本相关、可在本地验证的 TLS 差异:
|
||||
|
||||
1. **Go 1.27 改变了 `GODEBUG=tlsmlkem=0` 与显式 `CurvePreferences` 的关系。** SILO 两个版本都显式包含 X25519MLKEM768。旧版 Go 1.26.5 会根据该环境选项移除它;Go 1.27.1 保留显式配置。在模拟拒绝 ML-KEM 的入口上,能重现“相同选项下旧 Server 启动成功,新 Server 持续 reset”。**客户是否设置过这个选项尚未知,不能把条件性复现当成客户根因。**
|
||||
2. **Go 1.27 的 ClientHello 新增 ML-DSA 签名算法。** 没有上述环境选项时,新旧版本也会发送不同的握手。人为拒绝新算法编号的入口同样能产生旧成功、新失败。真实入口是否存在这种行为尚未知。
|
||||
|
||||
另外,HTTP User-Agent 从 `MinIO` 变成了 `Silo`;若连接在 TLS 完成、GET 发出之后被重置,应优先查 WAF、User-Agent 规则和 HTTP 路由,而不是继续调整 TLS。
|
||||
|
||||
最短路径:**先在故障进程所在环境拿到实际 Go 版本、是否设置 `tlsmlkem=0`、目标 IP 和 TLS 完成与否;再针对已证实的分支处理。** 优先修正入口兼容性或错误路由。若确认是上述环境选项失效,只为 OpenID 出站请求恢复 Go 默认曲线选择,是目前最小的代码候选。现阶段不宜做全局 TLS 改动或整体依赖回退。
|
||||
|
||||
## 第二轮结论:已隔离 Go 因素,局部候选修复通过 Linux 验证
|
||||
|
||||
**可以复现一种由 Go 1.26.5 → 1.27.1 单独触发的兼容性回归。建议保留 Go、针对已确认分支修复;整体回退只用于临时恢复服务。** 这里的“已确认”指本地实验机制,仍不等于已经确认客户入口的根因。
|
||||
|
||||
四个完整 Server 都从本地源码编译为 `linux/arm64`,在现成通用 Debian 12 基础镜像的 `--network none` 容器中运行;Server、合成 IdP、Console 和 curl 共用同一 loopback 网络,没有暴露端口。没有下载或运行 Server/Console 镜像。旧源码为 `d88f46ccee345a9c2fabe2d221d9a9e56bc11aec`,当前源码为 `d1105bbb3d4a0afa33b3a4ac11b821235038ed0e`。
|
||||
|
||||
旧源码两次构建使用完全相同的 `go.mod`、`go.sum` 和实际链接模块版本,仅替换编译器;当前源码与候选补丁构建的依赖图也完全相同。实际二进制 SHA-256、`go version -m` 依赖和构建选项保存在 [Linux 证据](issue-154/linux-evidence.json)。
|
||||
|
||||
下表的入口**人为设置为见到 X25519MLKEM768 就发 TCP RST**,Server 都设置 `GODEBUG=tlsmlkem=0`:
|
||||
|
||||
| 源码与编译器 | Server 初始 ClientHello | 完整 Server 结果 | 同容器 curl |
|
||||
| --- | --- | --- | --- |
|
||||
| 同一份旧源码 + Go 1.26.5 | 275 字节,无 ML-KEM | discovery、JWKS、IAM、Console 正常;cluster 200 | HTTP/2 200 |
|
||||
| 同一份旧源码 + Go 1.27.1 | 1509 字节,仍包含 ML-KEM | `connection reset by peer`;IAM 等待;cluster 503;Console 未启动 | HTTP/2 200 |
|
||||
| 当前源码 + Go 1.27.1 | 1509 字节,仍包含 ML-KEM | 同样失败 | HTTP/2 200 |
|
||||
| 当前源码 + 局部候选补丁 + Go 1.27.1 | 287 字节,无 ML-KEM | 完整启动及合成 OIDC 登录成功 | HTTP/2 200 |
|
||||
|
||||
这将该条件下的回归定位到工具链行为,而非 Console、pkg、mc 或 `coreos/go-oidc` 升级。Go 1.27 的发布说明明确将此作为有意改变:`tlsmlkem` / `tlssecpmlkem` 只控制默认曲线集合,显式指定的集合可以继续启用这些算法。SILO 现有曲线列表显式包含该算法,因而原来的兼容开关在这条路径失效。[Go 1.27 crypto/tls 说明](https://go.dev/doc/go1.27#crypto/tls)。
|
||||
|
||||
共完成 **12 个 Linux 场景**,其中失败用例按预期失败:
|
||||
|
||||
- 正常 TLS 1.2 / P-256 / RSA / AES-256-GCM 的 IdP,旧源码用两个 Go 版本编译均正常,证明不是 Go 1.27 普遍无法连接这套 TLS。
|
||||
- 上表四个对照均符合预期;候选补丁如果不设置 `tlsmlkem=0`,仍被 ML-KEM 拒绝规则拦截。补丁恢复显式兼容选项的作用,不会自行关闭后量子算法。
|
||||
- 候选补丁在上述 TLS 1.2 兼容场景、以及无 GODEBUG 的正常 TLS 1.3 场景,都完成 Console 登录信息获取 → IdP authorization redirect → callback → token exchange → STS 凭据 → Console 会话 → 桶列表读取。登录 API 为 204,桶列表为 200。
|
||||
- 两个登录场景分别提交错误签名与错误 audience 的 JWT,登录返回 500、桶列表返回 403,没有生成会话 cookie。这里只确认认证未放行,没有将现有 500 状态码行为改为另一项修复。
|
||||
- 不信任 CA 时,候选 Server 仍因 `x509: certificate signed by unknown authority` 停在 IAM 初始化。没有关闭证书校验。
|
||||
- 不配置 OIDC 启动后,经实际 Admin API 添加同一合成 provider:当前源码失败且返回 reset;候选补丁成功。
|
||||
- 入口改为拒绝 ML-DSA 签名编号,候选补丁加 `tlsmlkem=0` 仍失败。这是另一条机制,当前补丁没有解决它。
|
||||
|
||||
认证流程由 Python 驱动真实 Console HTTP API;IdP 使用一次性合成授权码和自行签发的实验 JWT,没有客户账户。没有执行浏览器页面交互、登出、真实 Keycloak 或生产数据升级测试。TLS 1.3 对照实际协商 TLS 1.3/P-256,不是所有新增后量子曲线的互操作覆盖。
|
||||
|
||||
### 修复与回退的取舍
|
||||
|
||||
[候选补丁](issue-154/openid-default-curves.patch) 只有三个文件:增加 OpenID 专用 transport helper,将其 `TLSClientConfig.CurvePreferences` 设为 `nil`,再替换 IAM 初始化和 OpenID 配置校验两个调用点。测试时仅应用于隔离源码副本,当前产品工作区未应用;Go 版本与所有依赖保持不变。它让 Go 默认策略和现有兼容开关接管外部 IdP 的密钥交换,其他 TLS 参数继续来自现有构造函数。
|
||||
|
||||
如果客户证据确认此分支,建议采用该局部修复,并在客户实际入口复验。如果客户没有设置 `tlsmlkem=0`,它不能单独解释旧版成功:旧版默认也发送 ML-KEM。此时应继续区分 ML-DSA、其他握手变化、HTTP/WAF 规则与网络路径;不把此补丁直接宣称为 #154 的完整修复。
|
||||
|
||||
**不建议将当前产品直接改回 Go 1.26。** 实测以 Go 1.26.7 和 `GOTOOLCHAIN=local` 读取当前源码即被 `go.mod requires go >= 1.27.1` 拒绝;所固定的 Server、Console、mc 均声明 Go 1.27.1。回退需要进一步调整这些模块及可能的传递依赖,不是只换一个编译器版本。这个报错证明当前依赖图不能原样回编,并不证明经过额外适配后绝对无法回编。报告中已恢复服务的旧版可作为临时运行状态,不能把这种处置等同于完成兼容修复。
|
||||
|
||||
第二轮的运行脚本是 [run-linux.py](issue-154/run-linux.py),结果是 [linux-evidence.json](issue-154/linux-evidence.json),具体构建和运行步骤见文末。没有 issue 评论、提交、推送、合并或发布。
|
||||
|
||||
候选副本另通过 Go 1.27.1、darwin/arm64、CGO 关闭的 `go test -mod=readonly -count=1 ./internal/http ./internal/config/identity/openid`;补丁可以干净应用到调查基线。这些包级测试与上述 Linux 集成验证分别记录,不将其当成 Linux 单元测试结果。
|
||||
|
||||
## 范围、版本与公开证据
|
||||
|
||||
- 初始工作区干净,处于 detached HEAD;调查分支为 `codex/investigate-oidc-154`,基线与远端 main 均为 `d1105bbb3d4a0afa33b3a4ac11b821235038ed0e`。
|
||||
- 已读取 `/Users/vonng/pgsty/silo/AGENTS.md` 及工作区适用说明。维护范围为 PGSTY 的 Server、Console、mc、silo-pkg;上游 MinIO 仅作参考。
|
||||
- 第一轮 Server 与 transport 探针为本地源码构建的 darwin/arm64 程序,第二轮完整 Server 交叉构建为 linux/arm64;均使用 `CGO_ENABLED=0 GOWORK=off`。fixture 与 Admin 辅助程序也由本机 Go 构建。历史源码使用 `git archive` 导入隔离临时目录。没有下载或运行 Server/Console Docker 镜像,没有访问客户端点,没有改动真实服务或数据,没有评论 issue、推送、合并或发布。
|
||||
- 产品源码、`go.mod`、`go.sum` 未修改。本目录中的 Go 文件是显式运行的调查工具,带 `//go:build ignore`,不进入正常构建。
|
||||
|
||||
| 项目 | 旧版:2026-08-04 | 报告故障版:2026-09-03 | 调查时 main |
|
||||
| --- | --- | --- | --- |
|
||||
| 完整 tag | `RELEASE.2026-08-04T00-00-00Z` | `RELEASE.2026-09-03T13-18-01Z` | 无新 release 声明 |
|
||||
| 源码 commit | `d88f46ccee345a9c2fabe2d221d9a9e56bc11aec` | `9b11dc9469e650815b775cb47b039610644f5da4` | `d1105bbb3d4a0afa33b3a4ac11b821235038ed0e` |
|
||||
| go.mod / Docker 构建定义 | Go 1.26.5 | Go 1.27.1 | Go 1.27.1 |
|
||||
| 本地 Server / 探针实际编译器 | Go 1.26.5 | Go 1.27.1 | Go 1.27.1 |
|
||||
| Console replacement | `v0.0.0-20260804042150-b952a1202869` | `v0.0.0-20260903111932-464a59d73ada` | `v0.0.0-20260908142700-c103d08ec36a` |
|
||||
| mc replacement | `v0.0.0-20260801042411-ad10a2a10b76` | `v0.0.0-20260903063637-a2ef95c035d9` | `v0.0.0-20260909015522-fcd5cad8247f` |
|
||||
| PGSTY silo-pkg | v3.11.0,替换历史 minio/pkg 路径 | v3.13.2,直接依赖 | v3.13.3,直接依赖 |
|
||||
| coreos/go-oidc/v3 | v3.17.0 | v3.21.0 | v3.21.0 |
|
||||
| x/crypto | v0.54.0 | v0.56.0 | v0.56.0 |
|
||||
| x/net | v0.57.0 | v0.58.0 | v0.58.0 |
|
||||
| x/oauth2 | v0.36.0 | v0.36.0 | v0.36.0 |
|
||||
|
||||
版本依据:[旧版 go.mod](https://github.com/pgsty/silo/blob/d88f46ccee345a9c2fabe2d221d9a9e56bc11aec/go.mod)、[故障版 go.mod](https://github.com/pgsty/silo/blob/9b11dc9469e650815b775cb47b039610644f5da4/go.mod)、[本次 main go.mod](https://github.com/pgsty/silo/blob/d1105bbb3d4a0afa33b3a4ac11b821235038ed0e/go.mod)。还核对了各 tag 的 `Dockerfile.goreleaser` 和 release workflow。它们声明相应 Go 构建版本、禁用 CGO;历史归档、本次探针和 Server 均用 `go version -m` 核实实际编译器与 replacement。**这些不是客户实际镜像 digest 或其内二进制的取证,后者仍需 `--version` / build info 确认。**
|
||||
|
||||
[Issue #154](https://github.com/pgsty/silo/issues/154) 当前 OPEN,最后更新时间 `2026-09-08T05:30:42Z`,评论数为 0。报告包含升级后 Server 初始化失败、旧版回退恢复、测试实例添加 OIDC 失败,以及 curl 成功的输出。
|
||||
|
||||
curl 那次连接验证了所收到的证书链,并选择 TLS 1.2、`ECDHE-RSA-AES256-GCM-SHA384`、P-256 和 HTTP/2;解析得到两个 IPv4,记录中实际访问了其中一个。**公开命令使用 `docker run --rm` 新建容器,并非 `docker exec` 进入原故障容器;同镜像不能证明同网络命名空间、环境变量、CA 挂载、DNS 结果或出口。** 域名、realm、IP 已脱敏,本次不推测其真实值。
|
||||
|
||||
## 实际请求链
|
||||
|
||||
### IAM 与配置校验
|
||||
|
||||
```text
|
||||
Server startup
|
||||
IAMSys.Init
|
||||
openid.LookupConfig
|
||||
parseDiscoveryDoc: GET .well-known/openid-configuration
|
||||
PopulatePublicKey: GET discovery 中的 jwks_uri
|
||||
IAM store 初始化
|
||||
Console 初始化
|
||||
|
||||
Console 添加 OIDC
|
||||
AdminClient.AddOrUpdateIDPConfig
|
||||
Server addOrUpdateIDPHandler
|
||||
validateConfig(identity_openid)
|
||||
同一个 openid.LookupConfig / NewHTTPTransport
|
||||
```
|
||||
|
||||
`parseDiscoveryDoc` 是 SILO 自己的实现,用标准库 `http.Client` 发 GET,收到成功响应后才解码 JSON;这次日志中的 `Get ... read tcp ... reset` 发生在该调用返回响应之前,不能进一步区分 TLS 与 HTTP。请求本身不需要客户 client secret、token 或私钥。[IAM 调用点](https://github.com/pgsty/silo/blob/d1105bbb3d4a0afa33b3a4ac11b821235038ed0e/cmd/iam.go#L278-L288)、[discovery 实现](https://github.com/pgsty/silo/blob/d1105bbb3d4a0afa33b3a4ac11b821235038ed0e/internal/config/identity/openid/jwt.go#L261-L285)、[JWKS 实现](https://github.com/pgsty/silo/blob/d1105bbb3d4a0afa33b3a4ac11b821235038ed0e/internal/config/identity/openid/jwt.go#L89-L110)。
|
||||
|
||||
Console 的添加表单通过 Admin API 触发 Server 配置校验。校验成功才写入配置;本地已重现该 API 返回同样的 reset,恢复 IdP 后再次创建成功并要求重启。[Console 调用](https://github.com/pgsty/silo-console/blob/c103d08ec36a/api/admin_idp.go#L79-L114)、[Admin 客户端](https://github.com/pgsty/silo-console/blob/c103d08ec36a/api/client-admin.go#L593-L595)、[Server 校验和保存边界](https://github.com/pgsty/silo/blob/d1105bbb3d4a0afa33b3a4ac11b821235038ed0e/cmd/admin-handlers-idp-config.go#L127-L150)、[OpenID 配置校验](https://github.com/pgsty/silo/blob/d1105bbb3d4a0afa33b3a4ac11b821235038ed0e/cmd/config-current.go#L353-L359)。
|
||||
|
||||
`coreos/go-oidc.NewProvider` 在 Server 中的使用是 `MockOpenIDTestUserInteraction` 测试辅助函数,不是这次 IAM discovery 调用链。升级此依赖不能单独解释或修复该 GET。`crypto/tls` 和这里的 `net/http` 属于 Go 标准库,不能用 go.mod 中 `x/crypto`、`x/net` 的版本代替它们的实际行为。[辅助函数](https://github.com/pgsty/silo/blob/d1105bbb3d4a0afa33b3a4ac11b821235038ed0e/cmd/utils.go#L994-L1012)。
|
||||
|
||||
### transport 参数与环境
|
||||
|
||||
| 项目 | 实际行为及意义 |
|
||||
| --- | --- |
|
||||
| 构造 | `NewHTTPTransport()` → `NewHTTPTransportWithTimeout(time.Minute)` → `xhttp.ConnSettings`。每次 IAM 初始化重试都会重新构造。 |
|
||||
| TLS 版本 | 未显式设置 Min/Max;所比较 Go 工具链的正常默认范围是 TLS 1.2–1.3。证书、主机名验证开启。 |
|
||||
| 密码套件 | 显式 `TLSCiphersBackwardCompatible()`,包含 curl 成功使用的 ECDHE-RSA/AES-256-GCM。没有理由为本 issue 添加旧 RSA、3DES 或 SHA-1 例外。 |
|
||||
| 曲线 | 显式 `{X25519MLKEM768, P256, X25519, P384, P521}`,两个 release 和当前 main 相同。实际上线顺序还受 Go 实现控制,见实验。 |
|
||||
| ALPN / HTTP | `EnableHTTP2=false`,同时设置自定义 TLS config 和 DialContext;实测 ClientHello 没有 ALPN,GET 使用 HTTP/1.1。三个版本一致。`GODEBUG=http2client=0` 对此基线路径无修复价值。 |
|
||||
| 代理 | `http.ProxyFromEnvironment`;HTTPS URL 使用 `HTTPS_PROXY` / `https_proxy` 与 `NO_PROXY` / `no_proxy`。这两版标准库均优先非空大写值,不使用 `ALL_PROXY`;设置在进程内缓存。不能根据 curl 的路由推断它。注意 go.mod 的 x/net v0.58.0 代码不是这里所用的标准库 vendored 实现。 |
|
||||
| DNS | `globalDNSCache.LookupHost`,dnscache v0.1.1;默认刷新窗口在容器/Kubernetes 为 30 秒,其他环境为 10 分钟,可配置。按返回地址逐个尝试 TCP,首次 TCP 成功就返回;随后 TLS/HTTP 失败不会回到这个循环尝试另一 IP。代码注释称随机选择,但该循环没有 shuffle。 |
|
||||
| Linux TCP 参数 | 使用 SILO 的自定义 dialer,包含 TCP fast open/keepalive 等设置,部分参数来自 Server CLI,包括 interface、buffer、user timeout。第二轮执行了完整 Linux Server 的正常 CLI 初始化,但只验证 loopback;不能排除实际出口设备、路由或非默认 CLI 参数的交互。 |
|
||||
| CA | `silo-pkg/certs.GetRootCAs` 加载系统根、Kubernetes CA 目录和 `certs/CAs`;Server 还加入自己的公开服务证书。相关 pkg CA 加载实现未在这次版本比较中变化;实际文件和路径仍可能因部署变化不同。 |
|
||||
| 超时 | TCP 拨号 5 秒,TLS 握手 10 秒,响应头 1 分钟;discovery/JWKS 的 Client 没有总超时,discovery 使用的 Request 也没有调用方 context。响应体停滞不受响应头超时保护。 |
|
||||
| 复用 | keep-alive 开启,idle 15 秒,TLS session cache 100。一次初始化内 discovery 与 JWKS 可复用连接;初始化重试的新 transport 没有旧连接或 session。持续首次握手失败不能用清理空闲连接解释。 |
|
||||
| 请求标识 | UA 包含产品、OS、架构、模式和构建信息,产品名从 `MinIO` 变为 `Silo`;传输层禁用自动压缩。UA 规则只能在 HTTPS 被终止、HTTP 请求可见之后起作用。 |
|
||||
|
||||
源码:[构造与超时](https://github.com/pgsty/silo/blob/d1105bbb3d4a0afa33b3a4ac11b821235038ed0e/cmd/utils.go#L651-L670)、[HTTP/TLS 参数](https://github.com/pgsty/silo/blob/d1105bbb3d4a0afa33b3a4ac11b821235038ed0e/internal/http/transports.go#L44-L94)、[密码套件与曲线](https://github.com/pgsty/silo/blob/d1105bbb3d4a0afa33b3a4ac11b821235038ed0e/internal/crypto/crypto.go#L52-L78)、[DNS 拨号循环](https://github.com/pgsty/silo/blob/d1105bbb3d4a0afa33b3a4ac11b821235038ed0e/internal/http/dial_dnscache.go#L42-L84)、[缓存刷新](https://github.com/pgsty/silo/blob/d1105bbb3d4a0afa33b3a4ac11b821235038ed0e/cmd/common-main.go#L551-L578)、[CA 加载](https://github.com/pgsty/silo/blob/d1105bbb3d4a0afa33b3a4ac11b821235038ed0e/cmd/server-main.go#L383-L395)、[UA](https://github.com/pgsty/silo/blob/d1105bbb3d4a0afa33b3a4ac11b821235038ed0e/cmd/update.go#L228-L266)。
|
||||
|
||||
比较旧 tag 与故障 tag,OpenID discovery、transport、曲线实现的变动仅为 pkg 导入路径调整;IAM 另有品牌日志变更。比较故障 tag 与本次 main,这些关键实现没有变动。因此不能把当前依赖推进当成 #154 已解决的证据。
|
||||
|
||||
**Console 登录阶段是另一条出站路径。** 当前及故障版 Console 通过 `GetConsoleHTTPClient` / `GlobalTransport` 再获取 discovery、交换令牌,TLS config 未指定 CurvePreferences,仍做完整证书验证;不能把“添加配置走 Server”推广为所有 Console OIDC 请求都走 Server transport。任何修复最终都必须验证完整登录。`CONSOLE_MINIO_SERVER_TLS_SKIP_VERIFY` 只针对 SILO 端点,不能作为 IdP 修复。[Console transport](https://github.com/pgsty/silo-console/blob/c103d08ec36a/api/config.go#L68-L121)、[IdP 客户端](https://github.com/pgsty/silo-console/blob/c103d08ec36a/api/tls.go#L59-L70)、[Console discovery](https://github.com/pgsty/silo-console/blob/c103d08ec36a/pkg/auth/idp/oauth2/provider.go#L428-L449)。
|
||||
|
||||
## 本地实验与能排除的假设
|
||||
|
||||
工具与原始结果放在 [issue-154/](issue-154/):
|
||||
|
||||
- `probe.go` 直接调用 `cmd.NewHTTPTransport()`,用同版本 `certs.GetRootCAs` 装入实验 CA;记录 TCP、TLS、HTTP 阶段。诊断参数仅修改被比较的一项。
|
||||
- `fixture.go` 仅监听 IPv4 loopback;使用即时生成的 RSA 测试证书与专用 CA,提供 discovery 和有效 JWKS。正常基线限制 TLS 1.2、P-256、`TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384`,支持 HTTP/1.1 和 HTTP/2。
|
||||
- `admin-check.go` 仅允许 loopback Server,验证 Console 使用的 Admin API;使用本地虚构配置和临时凭据。
|
||||
- `evidence.json` 保存版本、握手参数、分阶段 trace 和完整 Server 实验结果;无客户信息、私钥或 token。
|
||||
- 第二轮扩展 fixture 的合成授权码、token 和 JWKS 流程;`run-linux.py` 驱动 Linux 完整 Server 及 Console API,`linux-evidence.json` 保存十二组场景和构建身份。敏感运行值不写入结果。
|
||||
|
||||
### 正常服务及握手差异
|
||||
|
||||
三个源码版本的实际 transport 都能通过完整证书验证,以 TLS 1.2 / AES-256-GCM / HTTP/1.1 获取测试文档。**Go 1.27 本身并非不能连接 TLS 1.2、RSA 证书或这套密码套件。** 正常服务也接受诊断性的 HTTP/2。
|
||||
|
||||
| 构建与选项 | fixture 读到的初始握手字节数 | 支持的 group ID | 新增 ML-DSA 签名编号 |
|
||||
| --- | ---: | --- | --- |
|
||||
| 旧源码 + Go 1.26.5,默认 | 1497 | 4588, 29, 23, 24, 25 | 无 |
|
||||
| 故障源码 + Go 1.27.1,默认 | 1509 | 同上 | 0x0904, 0x0905, 0x0906 |
|
||||
| 当前源码 + Go 1.27.1,默认 | 1509 | 同上 | 同上 |
|
||||
| 旧源码 + Go 1.26.5,`tlsmlkem=0` | 275 | 29, 23, 24, 25 | 无 |
|
||||
| 故障/当前源码 + Go 1.27.1,`tlsmlkem=0` | 1509 | 4588, 29, 23, 24, 25 | 有 |
|
||||
| 旧源码、旧依赖,只改为 Go 1.27.1 | 1509 | 4588, 29, 23, 24, 25 | 有;`tlsmlkem=0` 也不再移除 4588 |
|
||||
|
||||
4588 是 X25519MLKEM768,29 是 X25519,23/24/25 是 P-256/384/521。这些字节数包含本地 fixture 收到的 TLS record,测试 URL 是 IP,没有 DNS SNI;不能直接当成客户网络中的包长或 MTU 证据。默认新旧差异约 12 字节,没有证据支持“本次才突然出现巨大 ML-KEM 握手”的说法。设置上述环境选项时的差异则显著不同。
|
||||
|
||||
旧源码保留旧依赖、仅更换 Go 编译器后,行为随编译器变化,隔离了本次发现与 silo-pkg/Console 版本更新之间的关系。Go 1.27 官方说明也明确记录显式曲线配置不再受这些默认值开关限制,并新增 ML-DSA 支持。[Go 1.27 发布说明](https://go.dev/doc/go1.27)。本地进一步核对了两版 `crypto/tls/defaults.go`、`common.go` 的 `curvePreferences`/`supportsCurve` 和 `handshake_client.go`。
|
||||
|
||||
### 主动拒绝与对照结果
|
||||
|
||||
下列拒绝规则是人为设置的模型,**只证明机制可以产生相同症状,不证明真实 Keycloak 或其入口使用这些规则**。
|
||||
|
||||
| fixture 规则 | 对照结果 | 能支持的结论 |
|
||||
| --- | --- | --- |
|
||||
| ClientHello 带 ML-KEM 就发送 TCP RST | 旧版默认也失败;旧版 + `tlsmlkem=0` 成功;故障版 + 同选项失败;故障版显式 classical 曲线成功 | 需要旧环境选项或其他变化,才能用该机制解释升级回归。仅说 ML-KEM 不兼容不充分。 |
|
||||
| ClientHello 带 ML-DSA 编号就 RST | 旧版默认成功;故障版默认/仅 classical 都失败;故障版 TLS 1.2-only 成功 | 新的签名算法列表是另一种可区分机制。ML-DSA 与 ML-KEM 不是同一项。TLS 1.2-only 会同时改变多项 ClientHello,成功不等于唯一定位 ML-DSA。 |
|
||||
| 必须提供 h2 ALPN | 旧、新 Server transport 默认都失败;`-h2` 成功 | 可以解释 curl 与 Server 的不同,单独不能解释新旧版本差异。 |
|
||||
| TLS 完成后,对 `Silo` UA 的 GET 发送 RST | 同一个新 transport,`MinIO` UA 成功、`Silo` UA 失败 | 报告的外层 `Get ... reset` 错误也可能来自 HTTP 层,必须先判断 TLS 是否完成。 |
|
||||
| 不信任测试 CA | 返回 `*tls.CertificateVerificationError` / x509 类错误 | 与人为 RST 的错误不同;没有证据要求跳过证书验证。仍须比较客户实际连接收到的链。 |
|
||||
| 正常连接复用 | 第二个请求 `reused=true`;关闭 idle 连接后重新建 TCP 可恢复 TLS session | keep-alive 与 TLS session 复用是两件事。首次新 transport 就失败时,此分支优先级低。 |
|
||||
|
||||
### 完整 Server、IAM 和恢复
|
||||
|
||||
使用三个本地编译的完整 Server,独立空数据/配置目录、独立 CA 和临时凭据;未登录真实 IdP。
|
||||
|
||||
| 场景 | 实际结果 |
|
||||
| --- | --- |
|
||||
| 旧版、故障版连接正常 IdP | discovery + JWKS 成功;一条 TLS 连接;cluster health 200;Console HTTP 200;Admin ListUsers 成功。 |
|
||||
| 当前版连接持续 reset 的 IdP | IAM 持续等待;cluster health 503,`X-Minio-Server-Status: iam-offline`;Console 端口尚未提供服务;5 秒限时的 Admin ListUsers 未完成。 |
|
||||
| 上述场景恢复 IdP,不重启 Server | 约 0.43 秒后 cluster/Console 200,ListUsers 成功。该时间是单次本地样本,不是恢复 SLA。 |
|
||||
| 旧版 + `tlsmlkem=0`,IdP 拒绝 ML-KEM | 完整启动成功。 |
|
||||
| 故障版 + `tlsmlkem=0`,相同拒绝规则 | IAM 等待、cluster 503;撤掉规则后约 1.38 秒内完整恢复,无需重启。 |
|
||||
| 当前版 discovery 成功、JWKS 返回 503 | 同样阻塞 IAM;JWKS 恢复后约 0.33 秒内恢复。只验证 discovery 200 不够。 |
|
||||
| 当前版先不配置 OIDC,再经 Admin API 添加 | IdP reset 时返回同型 `Get ... read tcp ... connection reset by peer`;恢复后同名创建成功,`restart=true`。失败校验没有保存该 provider。 |
|
||||
|
||||
在本地 IAM 阻塞的场景中,`/minio/health/live` 和 `/minio/health/ready` **仍为 200**。判断这次恢复应使用 `/minio/health/cluster` 并验证受认证操作和 Console,不能只看 ready。源码上 cluster 的 `checkHealth` 检查 IAM,而 ready 没有此检查;这是已有行为,本文不扩展为一次健康检查重构。[health 检查](https://github.com/pgsty/silo/blob/d1105bbb3d4a0afa33b3a4ac11b821235038ed0e/cmd/healthcheck-handler.go#L32-L65)、[ready 检查](https://github.com/pgsty/silo/blob/d1105bbb3d4a0afa33b3a4ac11b821235038ed0e/cmd/healthcheck-handler.go#L129-L186)。
|
||||
|
||||
现有 IAM 重试间隔随机为 0–3 秒,GET 本身还会占用网络等待时间;初始化成功前不会继续创建 IAM store,Console 又在 IAM 调用返回后启动。外部连接恢复可由现有重试自行恢复;这不意味着靠增加重试能修复持续不兼容。缺少整体请求期限、请求取消的部分是另外一个可单独修复的启动健壮性问题。[重试逻辑](https://github.com/pgsty/silo/blob/d1105bbb3d4a0afa33b3a4ac11b821235038ed0e/cmd/iam.go#L342-L365)、[Console 启动顺序](https://github.com/pgsty/silo/blob/d1105bbb3d4a0afa33b3a4ac11b821235038ed0e/cmd/server-main.go#L1007-L1027)。
|
||||
|
||||
已通过:`CGO_ENABLED=0 GOWORK=off go test -mod=readonly -count=1 ./internal/http ./internal/config/identity/openid`。这些测试没有替代真实 Keycloak 登录或 Linux 故障网络的验证。
|
||||
|
||||
## 最少补充证据与诊断命令
|
||||
|
||||
先收集第一轮,按结果才展开后续。所有请求只取公开 discovery,不需要客户端密钥、密码、token 或私钥。不要求环境变量全量导出、配置导出或证书私钥。
|
||||
|
||||
### 第一轮:运行身份、网络一致性、协议阶段
|
||||
|
||||
在**已有故障容器/Pod 的实际网络环境**中运行;旧版也做同样检查。不要以新建默认网络容器替代。如果实际进程经启动脚本修改过环境,探针也应使用修改后的相关环境和同一 CA 挂载。
|
||||
|
||||
```sh
|
||||
# 选择实际 Server 可执行文件;记录输出中的版本、Go、OS/架构。
|
||||
silo --version
|
||||
# 旧镜像的程序名可能是 minio。
|
||||
|
||||
# Linux:PID 设为实际 Server 进程 PID,不预设一定是 1。
|
||||
# 只输出 Go 调试选项以及相关环境项是否存在,不输出代理凭据/地址。
|
||||
tr '\0' '\n' < "/proc/$PID/environ" | awk '
|
||||
/^GODEBUG=/ { print; next }
|
||||
/^(HTTP_PROXY|HTTPS_PROXY|NO_PROXY|ALL_PROXY|http_proxy|https_proxy|no_proxy|all_proxy|SSL_CERT_FILE|SSL_CERT_DIR)=/ {
|
||||
split($0, a, "="); print a[1] "=<set>"
|
||||
}'
|
||||
|
||||
# OIDC_URL 仅在本地设为原 config_url;URL 不应带凭据或令牌。
|
||||
export OIDC_URL
|
||||
curl --http1.1 --connect-timeout 5 --max-time 20 -sS -o /dev/null \
|
||||
-w 'ip=%{remote_ip} http=%{http_version} status=%{http_code} verify=%{ssl_verify_result}\n' "$OIDC_URL"
|
||||
curl --http2 --connect-timeout 5 --max-time 20 -sS -o /dev/null \
|
||||
-w 'ip=%{remote_ip} http=%{http_version} status=%{http_code} verify=%{ssl_verify_result}\n' "$OIDC_URL"
|
||||
|
||||
# 由维护者从对应源码构建的探针;OIDC_CA 是与 Server 相同的 CAs 目录。
|
||||
./oidc-probe -ca "$OIDC_CA"
|
||||
```
|
||||
|
||||
探针从 `OIDC_URL` 读取 URL。URL、响应体、请求头不会打印;输出的 IP 可按一致映射替换为 IP-A/IP-B。它使用真实 Server transport 构造函数,但添加 20 秒总期限、不跟随重定向、限制响应体读取为 1 MiB,并使用 `issue-154-probe` UA;因此是定位连接阶段的工具,不是完整 OIDC 流程。它没有执行 Server 的 CLI 初始化,也不继承该进程的 `--interface`、socket buffer、TCP user timeout 或存量 DNS 缓存;若使用这些非默认参数,必须对齐后才能归因。若 Server 将自己的公开服务证书也作为根信任,需要把相同公开证书加入探针的临时 CA 目录。
|
||||
|
||||
读结果的方法:
|
||||
|
||||
- `tls_start` 后 `tls_done ... err=reset`:先查 TLS ClientHello、代理 CONNECT 或 TLS 终止设备;尚不能从客户端确定 RST 由终端还是中间设备发出。
|
||||
- `tls_done ... err=none`、`wrote_request` 后 reset:检查 HTTP/WAF/UA/入口路由。此时更换证书信任或密钥交换没有针对性。
|
||||
- 出现 x509 类错误:比较该进程实际收到的证书链、SNI、系统 CA 和自定义 CA;保持验证开启。
|
||||
- 两次 curl 的 IP 不同,或探针目标与 curl 不同:先做同 IP 对照。curl HTTP/1.1 成功也不代表 Go ClientHello 相同。
|
||||
- 仅 curl h2 成功:确认实际协商的 `http_version` 是 2,再检查入口 HTTP/1.1 支持;不要先全局启用 Server HTTP/2。
|
||||
|
||||
### 只对命中的分支做 A/B
|
||||
|
||||
```sh
|
||||
# TLS 阶段失败:仅移除 hybrid key exchange,仍支持 TLS 1.3 和验证证书。
|
||||
./oidc-probe -ca "$OIDC_CA" -classical
|
||||
|
||||
# 如果旧进程确实使用 tlsmlkem=0,验证最小候选是否恢复其效果。
|
||||
# 应保留原 GODEBUG 的其他相关选项;以下假定没有需要保留的其他值。
|
||||
GODEBUG=tlsmlkem=0 ./oidc-probe -ca "$OIDC_CA" -default-curves
|
||||
|
||||
# 只有 classical 仍失败时,作为鉴别实验测试 TLS 1.2-only。
|
||||
./oidc-probe -ca "$OIDC_CA" -tls12
|
||||
|
||||
# 只有 HTTP/ALPN 对照指向此分支时才测试。
|
||||
./oidc-probe -ca "$OIDC_CA" -h2
|
||||
|
||||
# HTTP 阶段才失败:UA_OLD / UA_NEW 是两版实际请求的完整 UA,非密钥。
|
||||
./oidc-probe -ca "$OIDC_CA" -ua "$UA_OLD"
|
||||
./oidc-probe -ca "$OIDC_CA" -ua "$UA_NEW"
|
||||
```
|
||||
|
||||
若 first-hop 使用代理,先比较两进程的代理选择和 `NO_PROXY`,不公开含密码的代理 URL。只在明确允许直连的部署中使用 `-direct`。确认直连后,可针对每个 DNS 地址运行以下两项,保留原 URL 主机名与 SNI,不能直接把 HTTPS URL 改成 IP:
|
||||
|
||||
```sh
|
||||
curl --noproxy '*' --resolve "$OIDC_HOST:443:$IP_A" --http1.1 \
|
||||
--connect-timeout 5 --max-time 20 -sS -o /dev/null \
|
||||
-w 'ip=%{remote_ip} status=%{http_code} verify=%{ssl_verify_result}\n' "$OIDC_URL"
|
||||
./oidc-probe -ca "$OIDC_CA" -direct -ip "$IP_A"
|
||||
# 对 IP-B 重复;端口不是 443 时据实修改 --resolve。
|
||||
```
|
||||
|
||||
仅第二次请求失败时才补 `-n 2` 与 `-n 2 -fresh`;后者重建 TCP,但同一 transport 的 TLS session cache 仍保留。若仍无法区分,下一步要的是入口侧同一时间窗口的握手失败原因/命中规则,或由客户自行脱敏后的 ClientHello 参数和 RST 阶段,不是完整认证流量包。
|
||||
|
||||
## 条件性最小修复方案
|
||||
|
||||
### 1. 路由、代理或入口策略差异已证实
|
||||
|
||||
优先统一有问题的 IdP 入口、修正具体域名的代理/NO_PROXY 或后端节点配置;更新错误拒绝合法 ClientHello 的 TLS 终止器/WAF。证书仍按原 hostname 和有效 CA 验证,OIDC issuer 不随意改名。若是 `Silo` UA 被规则拒绝,调整该规则;不把全产品 UA 改回 MinIO。
|
||||
|
||||
这是配置层处理,可以不改 SILO。工作量取决于入口归属;成功标准是原版故障二进制在原网络环境中完成 discovery、JWKS 和完整登录,而非仅 curl 200。
|
||||
|
||||
### 2. 证实旧环境依赖 `tlsmlkem=0`,且 classical / default-curves 对照成功
|
||||
|
||||
最小代码候选是为外部 OpenID 请求使用 Go 的默认曲线集合,恢复已有 GODEBUG 选项的效果;保留当前 trust pool、SNI、密码套件、超时、代理及 HTTP/1.1 行为。候选代码如下,**已在隔离副本完成上述验证,尚未应用到产品工作区**:
|
||||
|
||||
```go
|
||||
func NewOpenIDHTTPTransport() *http.Transport {
|
||||
tr := NewHTTPTransport()
|
||||
tr.TLSClientConfig.CurvePreferences = nil
|
||||
return tr
|
||||
}
|
||||
```
|
||||
|
||||
当时的候选只将 `cmd/iam.go` 和 `cmd/config-current.go` 两处 OpenID 调用改用该 helper,通过现有 UA wrapper 传入 `openid.LookupConfig`。后续排查确认节点互联、复制、远端存储等连接也存在同样的问题,此局部方案已被 [SILO 跨组件修复](go127-stack.md) 取代;请勿再应用下面归档的 OIDC-only 补丁。
|
||||
|
||||
候选已在真实 transport 探针及第二轮完整 Linux Server 中验证:`CurvePreferences=nil` + Go 1.27.1 + `tlsmlkem=0` 会移除 ML-KEM,并通过 `reject-mlkem` fixture、配置添加和合成登录。它仍不能通过 `reject-mldsa` fixture,说明此方案针对的是一个明确分支。
|
||||
|
||||
影响需要明确:
|
||||
|
||||
- 不设置 GODEBUG 时会采用完整 Go 默认集合,实测额外提供 SecP256r1MLKEM768 和 SecP384r1MLKEM1024;这也是一项兼容性变化。第二轮默认 TLS 1.3 登录通过,仍不能称为完全无行为变化或所有曲线均已覆盖。
|
||||
- `GODEBUG` 是进程级设置,其他使用 Go 默认曲线的客户端也可能受到影响;本次 helper 的改动范围是 OpenID,但该环境选项本身不是逐 provider 开关。
|
||||
- 禁用 hybrid 后仍有标准 ECDHE/TLS 和证书验证,失去的是相应后量子密钥交换保护。优先修正入口,临时兼容设置应有撤销条件;不能自动遇到 reset 就降级重试。
|
||||
- 当前 Console IdP transport 本来使用默认曲线,同一进程中的该 GODEBUG 策略可以与之保持一致;第二轮合成登录链路已经验证,真实 IdP 和浏览器验收仍待进行。
|
||||
- 隔离源码副本中的候选实现及上述本地验证已完成;真实端点 A/B 证据、生产适用性和发布是尚未完成的步骤。
|
||||
|
||||
### 3. 未设置上述选项,或 classical 仍失败
|
||||
|
||||
不要套用方案 2。若同 IP、同代理、同 UA 下仅 Go 1.27 失败,优先收集入口对新签名算法/扩展的处理证据。`-tls12` 成功只能缩小到 ClientHello/TLS 特征集合;它同时移除 hybrid key share 和 TLS 1.3 特有签名编号,不能唯一证明 ML-DSA。
|
||||
|
||||
优先更新入口或获得 Go 上游可复现用例。只有真实证据证明 TLS 1.2 兼容模式是必要且有效、入口又短期无法处理时,才评估**明确限定于该 IdP**的临时 TLS 1.2 选项,并保留现代 ECDHE/AEAD 和证书验证。不要把 `MaxVersion=TLS12` 全局写死,不引入自定义 ClientHello/TLS 栈或未受支持的“关闭 ML-DSA”环境选项。该分支尚不足以确定补丁或工期。
|
||||
|
||||
### 4. 启动健壮性可单独改进
|
||||
|
||||
如需小幅改善可诊断性,应单独给 discovery/JWKS 加明确阶段标识和有限总请求期限,让 IAM 重试可感知取消;在请求完成前发生 stall 时及时释放资源。日志避免输出 client secret/token,错误保留原始 cause。保留已配置 OIDC 的失败关闭行为及 IdP 恢复后的自动初始化,不自动关闭 OIDC,也不把无限重试包装成根因修复。
|
||||
|
||||
这类改动约 0.5–1 个工程日,可分别回归 stalled body、取消、重试后恢复;它不会使持续 RST 的 TLS 连接成功,不应替代前面鉴别。
|
||||
|
||||
## 临时处置与验收边界
|
||||
|
||||
当前可沿用报告中已经恢复服务的旧版回退状态,尽快完成上述定位。不要将旧版本长期保留视为解决方案,也不要为了它整体降级新版本依赖。本次空数据实验不证明任意生产数据/配置的降级兼容;再次切换版本前应沿既有备份和升级边界操作。
|
||||
|
||||
修复应按以下范围验证,均从 PGSTY 源码本地构建:
|
||||
|
||||
1. 对确认的分支增加最小回归:实际 OpenID transport、匹配的 ClientHello/入口拒绝条件、默认设置与明确 opt-out;确保通用和 internode transport 不变。
|
||||
2. TLS 1.2(报告密码套件)与 TLS 1.3、有效自定义 CA、错误 CA 和 hostname 拒绝;适用时覆盖代理及多地址入口。不放宽证书、JWT 签名或 audience 等认证校验。
|
||||
3. 完整 Server 的 discovery 与 JWKS、IdP 中断后恢复、cluster health、受认证 Admin 操作;Console 添加配置、浏览器重定向、回调、令牌交换、STS 授权和登出。mc 添加/读取配置路径应一致。
|
||||
4. 在实际 Linux 容器/Pod 网络和每个 IdP 入口地址复验。证据应绑定最终 Server/Console/pkg/mc commit 和编译器;发布、镜像及生产可用性属于后续独立验收。
|
||||
|
||||
第二轮完成 Linux loopback 上的合成 OAuth token/STS 登录;本次没有真实 Keycloak、真实 Linux 故障路径、浏览器页面或生产数据升级测试。当前 main 对正常 fixture 成功,并不能据此宣告 #154 修复。下一项最有价值的新增证据是**实际进程的 `tlsmlkem` 设置和一个带 TLS 完成事件的同环境 GET trace**。
|
||||
|
||||
## 复现实验
|
||||
|
||||
从本任务 worktree 根目录执行;工具均使用本地源码,输出目录必须是新建临时目录。
|
||||
|
||||
```sh
|
||||
LAB_DIR=$(mktemp -d)
|
||||
CGO_ENABLED=0 GOWORK=off go build -mod=readonly -tags kqueue \
|
||||
-o "$LAB_DIR/silo" .
|
||||
CGO_ENABLED=0 GOWORK=off go build -mod=readonly -tags kqueue \
|
||||
-o "$LAB_DIR/probe" docs/investigations/issue-154/probe.go
|
||||
go build -o "$LAB_DIR/fixture" docs/investigations/issue-154/fixture.go
|
||||
go build -mod=readonly -o "$LAB_DIR/admin-check" docs/investigations/issue-154/admin-check.go
|
||||
"$LAB_DIR/fixture" -dir "$LAB_DIR/idp" > "$LAB_DIR/hello.jsonl" 2> "$LAB_DIR/fixture.log" &
|
||||
FIXTURE_PID=$!
|
||||
trap 'kill "$FIXTURE_PID" 2>/dev/null || true' EXIT
|
||||
attempt=0
|
||||
while [ ! -s "$LAB_DIR/idp/url" ] && [ "$attempt" -lt 50 ]; do
|
||||
sleep 0.1
|
||||
attempt=$((attempt + 1))
|
||||
done
|
||||
test -s "$LAB_DIR/idp/url" || exit 1
|
||||
# 私钥仅保存在 fixture 内存。
|
||||
OIDC_URL="$(cat "$LAB_DIR/idp/url")/.well-known/openid-configuration"
|
||||
export OIDC_URL
|
||||
"$LAB_DIR/probe" -ca "$LAB_DIR/idp/ca.pem"
|
||||
printf '%s' reject-mlkem > "$LAB_DIR/idp/mode"
|
||||
GODEBUG=tlsmlkem=0 "$LAB_DIR/probe" -ca "$LAB_DIR/idp/ca.pem"
|
||||
GODEBUG=tlsmlkem=0 "$LAB_DIR/probe" -ca "$LAB_DIR/idp/ca.pem" -default-curves
|
||||
printf '%s' reject-mldsa > "$LAB_DIR/idp/mode"
|
||||
"$LAB_DIR/probe" -ca "$LAB_DIR/idp/ca.pem" -classical
|
||||
"$LAB_DIR/probe" -ca "$LAB_DIR/idp/ca.pem" -tls12
|
||||
kill "$FIXTURE_PID"
|
||||
```
|
||||
|
||||
完整 Server 实验使用上述临时目录下的 `certs/CAs` 和数据目录,设置虚构的 `MINIO_IDENTITY_OPENID_CLIENT_ID`、fixture URL、临时 root 凭据,并显式指定 `--config-dir`、`--certs-dir`、loopback API/Console 地址。用 mode 文件切换 `reset`/`bad-jwks` 到 `normal`,同时检查 cluster health 和 Admin ListUsers;结果已保存在 `evidence.json`。`admin-check add` 只操作 `LAB_SERVER=127.0.0.1:port` 的实验实例,读取临时 `LAB_USER`、`LAB_PASSWORD`、`LAB_OIDC_URL`,使用虚构 OIDC secret。
|
||||
|
||||
跨版本构建时从各 tag `git archive` 获取源码,把 `probe.go` 放入该 module 根目录;旧版探针仅将 certs 导入替换为 `github.com/minio/pkg/v3/certs`,由旧版 go.mod 选择 PGSTY v3.11.0。分别强制 `GOTOOLCHAIN=go1.26.5` / `go1.27.1`,使用 `-mod=readonly`,不修改历史 go.mod。另将旧源码原依赖用 Go 1.27.1 构建,隔离工具链因素。若为 Linux 客户端构建探针,按已确认的架构设置 `GOOS=linux GOARCH=amd64` 或 `arm64`,不使用 Server 镜像代替。
|
||||
|
||||
### 第二轮 Linux 完整 Server 对照
|
||||
|
||||
从本任务根目录运行以下 Bash 命令。需要预先准备 Go 1.26.5、1.27.1 及源码依赖缓存,以及带 Python 3、curl/OpenSSL/HTTP2 的通用 Linux 基础镜像。`GOTOOLCHAIN` 明确选定编译器,`-mod=readonly` 保留依赖版本;实际测试构建用已安装工具链的绝对路径配合 `GOTOOLCHAIN=local`,等价地避免自动切换编译器。以下固定 `arm64` 与本次实验一致。
|
||||
|
||||
```bash
|
||||
LAB_DIR=$(mktemp -d)
|
||||
mkdir -p "$LAB_DIR/old" "$LAB_DIR/head" "$LAB_DIR/candidate" "$LAB_DIR/bin" "$LAB_DIR/out"
|
||||
git archive d88f46ccee345a9c2fabe2d221d9a9e56bc11aec | tar -x -C "$LAB_DIR/old"
|
||||
git archive d1105bbb3d4a0afa33b3a4ac11b821235038ed0e | tar -x -C "$LAB_DIR/head"
|
||||
git archive d1105bbb3d4a0afa33b3a4ac11b821235038ed0e | tar -x -C "$LAB_DIR/candidate"
|
||||
git -C "$LAB_DIR/candidate" apply "$PWD/docs/investigations/issue-154/openid-default-curves.patch"
|
||||
|
||||
(cd "$LAB_DIR/old" && CGO_ENABLED=0 GOWORK=off GOOS=linux GOARCH=arm64 \
|
||||
GOTOOLCHAIN=go1.26.5 go build -mod=readonly -tags kqueue -o "$LAB_DIR/bin/old-go126" .)
|
||||
(cd "$LAB_DIR/old" && CGO_ENABLED=0 GOWORK=off GOOS=linux GOARCH=arm64 \
|
||||
GOTOOLCHAIN=go1.27.1 go build -mod=readonly -tags kqueue -o "$LAB_DIR/bin/old-go127" .)
|
||||
(cd "$LAB_DIR/head" && CGO_ENABLED=0 GOWORK=off GOOS=linux GOARCH=arm64 \
|
||||
GOTOOLCHAIN=go1.27.1 go build -mod=readonly -tags kqueue -o "$LAB_DIR/bin/head-go127" .)
|
||||
(cd "$LAB_DIR/candidate" && CGO_ENABLED=0 GOWORK=off GOOS=linux GOARCH=arm64 \
|
||||
GOTOOLCHAIN=go1.27.1 go build -mod=readonly -tags kqueue -o "$LAB_DIR/bin/candidate-go127" .)
|
||||
CGO_ENABLED=0 GOWORK=off GOOS=linux GOARCH=arm64 GOTOOLCHAIN=go1.27.1 \
|
||||
go build -mod=readonly -o "$LAB_DIR/bin/fixture" docs/investigations/issue-154/fixture.go
|
||||
CGO_ENABLED=0 GOWORK=off GOOS=linux GOARCH=arm64 GOTOOLCHAIN=go1.27.1 \
|
||||
go build -mod=readonly -o "$LAB_DIR/bin/admin-check" docs/investigations/issue-154/admin-check.go
|
||||
|
||||
# 本机已存在的通用 Debian 12 arm64 基础镜像;不拉取镜像,不映射端口。
|
||||
LINUX_BASE_IMAGE=sha256:307af7711e2e04ab75759cb42a1eef45c43c4404894c0e30dd19f742b107b922
|
||||
docker run --rm --pull=never --network none \
|
||||
--mount "type=bind,source=$LAB_DIR/bin,target=/lab/bin,readonly" \
|
||||
--mount "type=bind,source=$LAB_DIR/out,target=/lab/out" \
|
||||
--mount "type=bind,source=$PWD/docs/investigations/issue-154/run-linux.py,target=/lab/run-linux.py,readonly" \
|
||||
--entrypoint python3 "$LINUX_BASE_IMAGE" /lab/run-linux.py
|
||||
```
|
||||
|
||||
每组场景输出一行摘要,同时在独立输出目录保存 `result.json`。脚本用 `finally` 终止其 Server/fixture,容器结束自动删除。它没有导出会话 cookie、授权码、JWT、state 或临时密码;原始运行目录只用于该次隔离实验,交付证据只保留握手、结果和构建身份。
|
||||
@@ -0,0 +1,41 @@
|
||||
//go:build ignore
|
||||
|
||||
// Loopback-only lab client for the Admin API used by Console's OIDC form.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"net"
|
||||
"os"
|
||||
"time"
|
||||
|
||||
"github.com/minio/madmin-go/v3"
|
||||
)
|
||||
|
||||
func main() {
|
||||
endpoint := os.Getenv("LAB_SERVER")
|
||||
host, _, err := net.SplitHostPort(endpoint)
|
||||
if err != nil || host != "127.0.0.1" {
|
||||
panic("LAB_SERVER must use IPv4 loopback")
|
||||
}
|
||||
a, err := madmin.New(endpoint, os.Getenv("LAB_USER"), os.Getenv("LAB_PASSWORD"), false)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
|
||||
defer cancel()
|
||||
if len(os.Args) > 1 && os.Args[1] == "add" {
|
||||
restart, err := a.AddOrUpdateIDPConfig(ctx, "openid", "local154", "enable=on client_id=local154 client_secret=local154-placeholder config_url="+os.Getenv("LAB_OIDC_URL"), false)
|
||||
fmt.Printf("add restart=%v err=%v\n", restart, err)
|
||||
if err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
return
|
||||
}
|
||||
users, err := a.ListUsers(ctx)
|
||||
fmt.Printf("list_users count=%d err=%v\n", len(users), err)
|
||||
if err != nil {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
//go:build ignore
|
||||
|
||||
// Run only with the public, synthetic CA made by fixture.go.
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto/x509"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"os"
|
||||
"runtime"
|
||||
|
||||
"github.com/pgsty/silo-pkg/v3/certs"
|
||||
)
|
||||
|
||||
func main() {
|
||||
if len(os.Args) != 3 {
|
||||
panic("usage: cert-roots synthetic-ca.pem explicit-ca-path-or-empty")
|
||||
}
|
||||
data, err := os.ReadFile(os.Args[1])
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
block, _ := pem.Decode(data)
|
||||
if block == nil || block.Type != "CERTIFICATE" {
|
||||
panic("expected public certificate")
|
||||
}
|
||||
certificate, err := x509.ParseCertificate(block.Bytes)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
roots, err := certs.GetRootCAs(os.Args[2])
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
_, err = certificate.Verify(x509.VerifyOptions{Roots: roots})
|
||||
_ = json.NewEncoder(os.Stdout).Encode(map[string]any{
|
||||
"go": runtime.Version(), "os": runtime.GOOS,
|
||||
"explicit_ca": os.Args[2] != "", "trusted": err == nil,
|
||||
})
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,179 @@
|
||||
//go:build ignore
|
||||
|
||||
// Loopback-only synthetic OIDC/TLS fixture. Only disposable lab identities are used.
|
||||
// Rejection modes model hypotheses; they are not evidence about the user's IdP.
|
||||
package main
|
||||
|
||||
import (
|
||||
"crypto"
|
||||
"crypto/rand"
|
||||
"crypto/rsa"
|
||||
"crypto/sha256"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"crypto/x509/pkix"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"encoding/pem"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"math/big"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"os"
|
||||
"path/filepath"
|
||||
"slices"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
type observedConn struct {
|
||||
net.Conn
|
||||
readBytes int
|
||||
}
|
||||
|
||||
func (c *observedConn) Read(p []byte) (int, error) {
|
||||
n, e := c.Conn.Read(p)
|
||||
c.readBytes += n
|
||||
return n, e
|
||||
}
|
||||
func (c *observedConn) reset() { _ = c.Conn.(*net.TCPConn).SetLinger(0); _ = c.Conn.Close() }
|
||||
|
||||
type observedListener struct{ net.Listener }
|
||||
|
||||
func (l observedListener) Accept() (net.Conn, error) {
|
||||
c, e := l.Listener.Accept()
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
return &observedConn{Conn: c}, nil
|
||||
}
|
||||
|
||||
func main() {
|
||||
dir := flag.String("dir", "", "isolated output directory for public CA, URL, and mode file")
|
||||
tls13 := flag.Bool("tls13", false, "allow TLS 1.3 in addition to the TLS 1.2 baseline")
|
||||
flag.Parse()
|
||||
if *dir == "" {
|
||||
panic("-dir required")
|
||||
}
|
||||
must(os.MkdirAll(*dir, 0700))
|
||||
key, err := rsa.GenerateKey(rand.Reader, 2048)
|
||||
must(err)
|
||||
root := &x509.Certificate{SerialNumber: big.NewInt(1), Subject: pkix.Name{CommonName: "issue-154 local CA"}, NotBefore: time.Now().Add(-time.Hour), NotAfter: time.Now().Add(24 * time.Hour), IsCA: true, BasicConstraintsValid: true, KeyUsage: x509.KeyUsageCertSign | x509.KeyUsageDigitalSignature}
|
||||
rootDER, err := x509.CreateCertificate(rand.Reader, root, root, &key.PublicKey, key)
|
||||
must(err)
|
||||
leaf := &x509.Certificate{SerialNumber: big.NewInt(2), Subject: pkix.Name{CommonName: "localhost"}, DNSNames: []string{"localhost"}, IPAddresses: []net.IP{net.ParseIP("127.0.0.1")}, NotBefore: root.NotBefore, NotAfter: root.NotAfter, ExtKeyUsage: []x509.ExtKeyUsage{x509.ExtKeyUsageServerAuth}, KeyUsage: x509.KeyUsageDigitalSignature}
|
||||
leafDER, err := x509.CreateCertificate(rand.Reader, leaf, root, &key.PublicKey, key)
|
||||
must(err)
|
||||
must(os.WriteFile(filepath.Join(*dir, "ca.pem"), pem.EncodeToMemory(&pem.Block{Type: "CERTIFICATE", Bytes: rootDER}), 0600))
|
||||
ln, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
must(err)
|
||||
base := "https://" + ln.Addr().String()
|
||||
must(os.WriteFile(filepath.Join(*dir, "url"), []byte(base), 0600))
|
||||
mode := func() string { b, _ := os.ReadFile(filepath.Join(*dir, "mode")); return strings.TrimSpace(string(b)) }
|
||||
var mu sync.Mutex
|
||||
log := func(v any) { mu.Lock(); defer mu.Unlock(); _ = json.NewEncoder(os.Stdout).Encode(v) }
|
||||
tc := &tls.Config{Certificates: []tls.Certificate{{Certificate: [][]byte{leafDER, rootDER}, PrivateKey: key}}, MinVersion: tls.VersionTLS12, MaxVersion: tls.VersionTLS12, CurvePreferences: []tls.CurveID{tls.CurveP256}, CipherSuites: []uint16{tls.TLS_ECDHE_RSA_WITH_AES_256_GCM_SHA384}}
|
||||
if *tls13 {
|
||||
tc.MaxVersion = tls.VersionTLS13
|
||||
}
|
||||
peerConfig := tc.Clone()
|
||||
peerConfig.NextProtos = []string{"h2", "http/1.1"}
|
||||
// net/http validates HTTP/2 support before GetConfigForClient; the fixture
|
||||
// then deliberately selects only the reported AES-256 suite.
|
||||
tc.CipherSuites = append(tc.CipherSuites, tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256)
|
||||
tc.GetConfigForClient = func(chi *tls.ClientHelloInfo) (*tls.Config, error) {
|
||||
m := mode()
|
||||
c := chi.Conn.(*observedConn)
|
||||
log(map[string]any{"event": "hello", "mode": m, "bytes_read": c.readBytes, "curves": chi.SupportedCurves, "signatures": chi.SignatureSchemes, "alpn": chi.SupportedProtos, "versions": chi.SupportedVersions})
|
||||
reject := m == "reset" || m == "reject-mlkem" && slices.Contains(chi.SupportedCurves, tls.CurveID(4588)) || m == "reject-mldsa" && slices.Contains(chi.SignatureSchemes, tls.SignatureScheme(0x0904)) || m == "require-h2" && !slices.Contains(chi.SupportedProtos, "h2")
|
||||
if reject {
|
||||
c.reset()
|
||||
return nil, errors.New("synthetic ClientHello rejection")
|
||||
}
|
||||
return peerConfig, nil
|
||||
}
|
||||
server := &http.Server{TLSConfig: tc, ReadHeaderTimeout: 5 * time.Second}
|
||||
var codes sync.Map
|
||||
server.Handler = http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
log(map[string]any{"event": "request", "path": r.URL.Path, "protocol": r.Proto, "tls": r.TLS.Version, "cipher": r.TLS.CipherSuite, "resumed": r.TLS.DidResume, "ua": r.UserAgent()})
|
||||
if mode() == "reject-silo-ua" && strings.HasPrefix(r.UserAgent(), "Silo") {
|
||||
c, _, e := w.(http.Hijacker).Hijack()
|
||||
if e == nil {
|
||||
c.(*tls.Conn).NetConn().(*observedConn).reset()
|
||||
}
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
switch r.URL.Path {
|
||||
case "/authorize":
|
||||
q := r.URL.Query()
|
||||
redirect, err := url.Parse(q.Get("redirect_uri"))
|
||||
if err != nil || redirect.Scheme != "http" || redirect.Hostname() != "127.0.0.1" || redirect.Path != "/oauth_callback" || q.Get("client_id") != "local154" {
|
||||
http.Error(w, "loopback lab authorization only", 400)
|
||||
return
|
||||
}
|
||||
codeBytes := make([]byte, 18)
|
||||
_, err = rand.Read(codeBytes)
|
||||
must(err)
|
||||
code := base64.RawURLEncoding.EncodeToString(codeBytes)
|
||||
codes.Store(code, q.Get("nonce"))
|
||||
values := redirect.Query()
|
||||
values.Set("code", code)
|
||||
values.Set("state", q.Get("state"))
|
||||
redirect.RawQuery = values.Encode()
|
||||
http.Redirect(w, r, redirect.String(), http.StatusFound)
|
||||
case "/token":
|
||||
if r.Method != http.MethodPost || r.ParseForm() != nil {
|
||||
http.Error(w, "bad token request", 400)
|
||||
return
|
||||
}
|
||||
id, secret, ok := r.BasicAuth()
|
||||
if !ok {
|
||||
id, secret = r.Form.Get("client_id"), r.Form.Get("client_secret")
|
||||
}
|
||||
nonce, found := codes.LoadAndDelete(r.Form.Get("code"))
|
||||
if id != "local154" || secret != "local154-placeholder" || !found || r.Form.Get("grant_type") != "authorization_code" {
|
||||
w.WriteHeader(400)
|
||||
_ = json.NewEncoder(w).Encode(map[string]string{"error": "invalid_grant"})
|
||||
return
|
||||
}
|
||||
audience := id
|
||||
if mode() == "bad-audience" {
|
||||
audience = "different-lab-client"
|
||||
}
|
||||
claims, _ := json.Marshal(map[string]any{"iss": base, "sub": "local154-user", "aud": audience, "iat": time.Now().Unix(), "exp": time.Now().Add(time.Hour).Unix(), "policy": "readwrite", "nonce": nonce})
|
||||
header := base64.RawURLEncoding.EncodeToString([]byte(`{"alg":"RS256","kid":"local-154","typ":"JWT"}`))
|
||||
payload := header + "." + base64.RawURLEncoding.EncodeToString(claims)
|
||||
hash := sha256.Sum256([]byte(payload))
|
||||
signature, err := rsa.SignPKCS1v15(rand.Reader, key, crypto.SHA256, hash[:])
|
||||
must(err)
|
||||
if mode() == "bad-signature" {
|
||||
signature[0] ^= 1
|
||||
}
|
||||
token := payload + "." + base64.RawURLEncoding.EncodeToString(signature)
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"access_token": token, "id_token": token, "token_type": "Bearer", "expires_in": 3600})
|
||||
case "/.well-known/openid-configuration":
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"issuer": base, "jwks_uri": base + "/jwks", "authorization_endpoint": base + "/authorize", "token_endpoint": base + "/token", "response_types_supported": []string{"code"}, "subject_types_supported": []string{"public"}, "id_token_signing_alg_values_supported": []string{"RS256"}, "scopes_supported": []string{"openid"}})
|
||||
case "/jwks":
|
||||
if mode() == "bad-jwks" {
|
||||
http.Error(w, "synthetic JWKS outage", 503)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(map[string]any{"keys": []any{map[string]any{"kty": "RSA", "kid": "local-154", "use": "sig", "alg": "RS256", "n": base64.RawURLEncoding.EncodeToString(key.N.Bytes()), "e": "AQAB"}}})
|
||||
default:
|
||||
http.NotFound(w, r)
|
||||
}
|
||||
})
|
||||
fmt.Fprintln(os.Stderr, base)
|
||||
must(server.ServeTLS(observedListener{ln}, "", ""))
|
||||
}
|
||||
|
||||
func must(err error) {
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,40 @@
|
||||
# Historical OIDC-only candidate; superseded by ../go127-stack.md. Do not apply on top of the stack fix.
|
||||
--- a/cmd/utils.go
|
||||
+++ b/cmd/utils.go
|
||||
@@ -654,6 +654,14 @@
|
||||
return NewHTTPTransportWithTimeout(1 * time.Minute)
|
||||
}
|
||||
|
||||
+// NewOpenIDHTTPTransport uses Go defaults for external identity-provider key exchange.
|
||||
+// This lets tlsmlkem/tlssecpmlkem configure their documented default sets.
|
||||
+func NewOpenIDHTTPTransport() *http.Transport {
|
||||
+ tr := NewHTTPTransport()
|
||||
+ tr.TLSClientConfig.CurvePreferences = nil
|
||||
+ return tr
|
||||
+}
|
||||
+
|
||||
// Default values for dial timeout
|
||||
const defaultDialTimeout = 5 * time.Second
|
||||
|
||||
--- a/cmd/iam.go
|
||||
+++ b/cmd/iam.go
|
||||
@@ -277,7 +277,7 @@
|
||||
for {
|
||||
if !openidInit {
|
||||
openidConfig, err := openid.LookupConfig(s,
|
||||
- xhttp.WithUserAgent(NewHTTPTransport(), func() string {
|
||||
+ xhttp.WithUserAgent(NewOpenIDHTTPTransport(), func() string {
|
||||
return getUserAgent(getMinioMode())
|
||||
}), xhttp.DrainBody, globalSite.Region())
|
||||
if err != nil {
|
||||
--- a/cmd/config-current.go
|
||||
+++ b/cmd/config-current.go
|
||||
@@ -352,7 +352,7 @@
|
||||
}
|
||||
case config.IdentityOpenIDSubSys:
|
||||
if _, err := openid.LookupConfig(s,
|
||||
- xhttp.WithUserAgent(NewHTTPTransport(), func() string {
|
||||
+ xhttp.WithUserAgent(NewOpenIDHTTPTransport(), func() string {
|
||||
return getUserAgent(getMinioMode())
|
||||
}), xhttp.DrainBody, globalSite.Region()); err != nil {
|
||||
return err
|
||||
@@ -0,0 +1,165 @@
|
||||
//go:build ignore
|
||||
|
||||
// Diagnostic GET using the Server's actual transport constructor.
|
||||
// Build explicitly from the SILO module root; see ../issue-154.md.
|
||||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"errors"
|
||||
"flag"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptrace"
|
||||
"net/url"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
|
||||
"github.com/minio/minio/cmd"
|
||||
xhttp "github.com/minio/minio/internal/http"
|
||||
"github.com/pgsty/silo-pkg/v3/certs"
|
||||
)
|
||||
|
||||
func main() {
|
||||
endpoint := flag.String("url", os.Getenv("OIDC_URL"), "discovery URL; no credentials or query string")
|
||||
ca := flag.String("ca", "", "same CA file or certs/CAs directory as Server")
|
||||
h2 := flag.Bool("h2", false, "diagnostic: opt in to HTTP/2")
|
||||
classical := flag.Bool("classical", false, "diagnostic: omit hybrid key exchange only")
|
||||
defaultCurves := flag.Bool("default-curves", false, "diagnostic: let Go choose curves and honor its GODEBUG defaults")
|
||||
tls12 := flag.Bool("tls12", false, "diagnostic: TLS 1.2 only; keeps certificate verification")
|
||||
direct := flag.Bool("direct", false, "diagnostic: bypass environment proxy")
|
||||
ip := flag.String("ip", "", "diagnostic: pin destination IP, preserving Host/SNI; requires -direct")
|
||||
fresh := flag.Bool("fresh", false, "diagnostic: close idle connections between requests")
|
||||
ua := flag.String("ua", "issue-154-probe", "HTTP User-Agent; supply actual Server UA to investigate a WAF")
|
||||
n := flag.Int("n", 1, "number of GETs (1 to 3)")
|
||||
flag.Parse()
|
||||
u, err := url.Parse(*endpoint)
|
||||
if err != nil || u.Scheme != "https" || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || *n < 1 || *n > 3 {
|
||||
fmt.Fprintln(os.Stderr, "require an HTTPS URL without credentials/query/fragment and -n between 1 and 3")
|
||||
os.Exit(2)
|
||||
}
|
||||
if *ip != "" && (!*direct || net.ParseIP(*ip) == nil) {
|
||||
fmt.Fprintln(os.Stderr, "-ip requires a literal IP and -direct")
|
||||
os.Exit(2)
|
||||
}
|
||||
if *classical && *defaultCurves {
|
||||
fmt.Fprintln(os.Stderr, "choose at most one of -classical and -default-curves")
|
||||
os.Exit(2)
|
||||
}
|
||||
tr := cmd.NewHTTPTransport()
|
||||
tr.TLSClientConfig.RootCAs, err = certs.GetRootCAs(*ca)
|
||||
if err != nil {
|
||||
fmt.Fprintln(os.Stderr, "CA loading failed; check the local CA path")
|
||||
os.Exit(2)
|
||||
}
|
||||
if *h2 {
|
||||
tr.ForceAttemptHTTP2 = true
|
||||
}
|
||||
if *classical {
|
||||
tr.TLSClientConfig.CurvePreferences = []tls.CurveID{tls.CurveP256, tls.X25519, tls.CurveP384, tls.CurveP521}
|
||||
}
|
||||
if *defaultCurves {
|
||||
tr.TLSClientConfig.CurvePreferences = nil
|
||||
}
|
||||
if *tls12 {
|
||||
tr.TLSClientConfig.MinVersion = tls.VersionTLS12
|
||||
tr.TLSClientConfig.MaxVersion = tls.VersionTLS12
|
||||
}
|
||||
if *direct {
|
||||
tr.Proxy = nil
|
||||
}
|
||||
if *ip != "" {
|
||||
base := tr.DialContext
|
||||
tr.DialContext = func(ctx context.Context, network, address string) (net.Conn, error) {
|
||||
host, port, e := net.SplitHostPort(address)
|
||||
if e != nil {
|
||||
return nil, e
|
||||
}
|
||||
if host == u.Hostname() {
|
||||
address = net.JoinHostPort(*ip, port)
|
||||
}
|
||||
return base(ctx, network, address)
|
||||
}
|
||||
}
|
||||
defer tr.CloseIdleConnections()
|
||||
var mu sync.Mutex
|
||||
log := func(format string, args ...any) { mu.Lock(); defer mu.Unlock(); fmt.Printf(format+"\n", args...) }
|
||||
log("go=%s os=%s arch=%s h2=%v classical=%v default_curves=%v tls12=%v", runtime.Version(), runtime.GOOS, runtime.GOARCH, *h2, *classical, *defaultCurves, *tls12)
|
||||
// Deliberately print no URL, headers, body, client ID, secret, or token.
|
||||
req, _ := http.NewRequest(http.MethodGet, u.String(), nil)
|
||||
proxy := "direct"
|
||||
if tr.Proxy != nil {
|
||||
p, e := tr.Proxy(req)
|
||||
if e != nil {
|
||||
log("proxy_selection_error=%T", e)
|
||||
os.Exit(2)
|
||||
}
|
||||
if p != nil {
|
||||
proxy = p.Scheme + " proxy (address omitted)"
|
||||
}
|
||||
}
|
||||
log("route=%s curves=%v", proxy, tr.TLSClientConfig.CurvePreferences)
|
||||
client := &http.Client{Transport: xhttp.WithUserAgent(tr, func() string { return *ua }), Timeout: 20 * time.Second,
|
||||
CheckRedirect: func(_ *http.Request, _ []*http.Request) error { return http.ErrUseLastResponse }}
|
||||
failed := false
|
||||
for i := 0; i < *n; i++ {
|
||||
if *fresh {
|
||||
tr.CloseIdleConnections()
|
||||
}
|
||||
log("request=%d", i+1)
|
||||
trace := &httptrace.ClientTrace{
|
||||
DNSDone: func(d httptrace.DNSDoneInfo) { log("dns_addresses=%v err=%s", d.Addrs, errorClass(d.Err)) },
|
||||
ConnectStart: func(network, addr string) { log("connect=%s %s", network, addr) },
|
||||
ConnectDone: func(_, addr string, e error) { log("connected=%s err=%s", addr, errorClass(e)) },
|
||||
TLSHandshakeStart: func() { log("tls_start") },
|
||||
TLSHandshakeDone: func(s tls.ConnectionState, e error) {
|
||||
log("tls_done=0x%x cipher=%s alpn=%q resumed=%v verified_chains=%d err=%s", s.Version, tls.CipherSuiteName(s.CipherSuite), s.NegotiatedProtocol, s.DidResume, len(s.VerifiedChains), errorClass(e))
|
||||
},
|
||||
GotConn: func(c httptrace.GotConnInfo) { log("got_conn=%s reused=%v", c.Conn.RemoteAddr(), c.Reused) },
|
||||
WroteRequest: func(w httptrace.WroteRequestInfo) { log("wrote_request err=%s", errorClass(w.Err)) },
|
||||
GotFirstResponseByte: func() { log("first_response_byte") },
|
||||
}
|
||||
r := req.Clone(httptrace.WithClientTrace(context.Background(), trace))
|
||||
resp, e := client.Do(r)
|
||||
if e != nil {
|
||||
log("get_error=%s", errorClass(e))
|
||||
failed = true
|
||||
continue
|
||||
}
|
||||
log("status=%d protocol=%s", resp.StatusCode, resp.Proto)
|
||||
_, e = io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<20))
|
||||
resp.Body.Close()
|
||||
if e != nil || resp.StatusCode != http.StatusOK {
|
||||
failed = true
|
||||
log("body_error=%s", errorClass(e))
|
||||
}
|
||||
}
|
||||
if failed {
|
||||
os.Exit(1)
|
||||
}
|
||||
}
|
||||
|
||||
func errorClass(err error) string {
|
||||
if err == nil {
|
||||
return "none"
|
||||
}
|
||||
if errors.Is(err, context.DeadlineExceeded) {
|
||||
return "deadline"
|
||||
}
|
||||
// Error text may contain a private URL. Emit only category and concrete type.
|
||||
category := "other"
|
||||
s := err.Error()
|
||||
for _, k := range []string{"connection reset by peer", "x509:", "TLS handshake timeout", "connection refused", "EOF"} {
|
||||
if strings.Contains(s, k) {
|
||||
category = k
|
||||
break
|
||||
}
|
||||
}
|
||||
return fmt.Sprintf("%s (%T)", category, err)
|
||||
}
|
||||
@@ -0,0 +1,170 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Bounded, loopback-only full-Server comparison. See the investigation report.
|
||||
|
||||
Run in an isolated generic Linux container with locally built binaries in
|
||||
/lab/bin and a new disposable /lab/out. No customer identities or endpoints.
|
||||
"""
|
||||
import http.cookiejar
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import shutil
|
||||
import socket
|
||||
import ssl
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
ROOT = Path("/lab")
|
||||
OUT = ROOT / "out"
|
||||
BASE = {k: v for k, v in os.environ.items()
|
||||
if not k.startswith(("MINIO_", "SILO_", "CONSOLE_"))
|
||||
and k.lower() not in {"http_proxy", "https_proxy", "all_proxy", "no_proxy", "godebug"}}
|
||||
|
||||
|
||||
def port():
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
return sock.getsockname()[1]
|
||||
|
||||
|
||||
def request(url, opener=None, payload=None):
|
||||
headers = {"Origin": f"http://{urllib.parse.urlparse(url).netloc}"}
|
||||
if payload is not None:
|
||||
headers["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(url, data=None if payload is None else json.dumps(payload).encode(), headers=headers)
|
||||
try:
|
||||
response = (opener.open if opener else urllib.request.urlopen)(req, timeout=2)
|
||||
except urllib.error.HTTPError as err:
|
||||
response = err
|
||||
except (urllib.error.URLError, TimeoutError):
|
||||
return 0, {}, b""
|
||||
with response:
|
||||
return response.code, dict(response.headers), response.read(1 << 20)
|
||||
|
||||
|
||||
def stop(proc):
|
||||
proc.terminate()
|
||||
try:
|
||||
proc.wait(timeout=4)
|
||||
except subprocess.TimeoutExpired:
|
||||
proc.kill()
|
||||
proc.wait(timeout=2)
|
||||
|
||||
|
||||
class NoRedirect(urllib.request.HTTPRedirectHandler):
|
||||
def redirect_request(self, req, fp, code, msg, headers, newurl):
|
||||
return None
|
||||
|
||||
|
||||
def login(console, ca):
|
||||
jar = http.cookiejar.CookieJar()
|
||||
client = urllib.request.build_opener(urllib.request.HTTPCookieProcessor(jar))
|
||||
status, _, raw = request(console + "/api/v1/login", client)
|
||||
details = json.loads(raw)
|
||||
rules = details.get("redirectRules", [])
|
||||
assert status == 200 and len(rules) == 1, (status, details)
|
||||
auth_url = rules[0]["redirect"]
|
||||
provider = urllib.request.build_opener(NoRedirect(), urllib.request.HTTPSHandler(context=ssl.create_default_context(cafile=str(ca))))
|
||||
status, headers, _ = request(auth_url, provider)
|
||||
callback = headers.get("Location", headers.get("location", ""))
|
||||
assert status == 302 and callback.startswith(console + "/oauth_callback?"), (status, callback)
|
||||
values = urllib.parse.parse_qs(urllib.parse.urlparse(callback).query)
|
||||
callback_status, _, _ = request(callback, client)
|
||||
status, _, _ = request(console + "/api/v1/login/oauth2/auth", client,
|
||||
{"code": values["code"][0], "state": values["state"][0]})
|
||||
buckets_status, _, _ = request(console + "/api/v1/buckets", client)
|
||||
# Do not record cookies, codes, JWTs, or the state value.
|
||||
return {"callback_status": callback_status, "login_status": status,
|
||||
"buckets_status": buckets_status, "session_cookie": any(c.name == "token" for c in jar)}
|
||||
|
||||
|
||||
def run(name, binary, mode="normal", debug=None, tls13=False,
|
||||
expected=True, trusted=True, oidc=True, oauth=False, add=False):
|
||||
d = OUT / name
|
||||
(d / "certs/CAs").mkdir(parents=True, exist_ok=False)
|
||||
idp = d / "idp"
|
||||
idp.mkdir()
|
||||
(idp / "mode").write_text(mode)
|
||||
with (d / "fixture.jsonl").open("w") as events, (d / "fixture.stderr").open("w") as errors, (d / "server.log").open("w") as logs:
|
||||
fixture = subprocess.Popen([str(ROOT / "bin/fixture"), "-dir", str(idp), *(["-tls13"] if tls13 else [])], env=BASE, stdout=events, stderr=errors)
|
||||
server = None
|
||||
try:
|
||||
until = time.monotonic() + 5
|
||||
while not (idp / "url").is_file() and time.monotonic() < until:
|
||||
time.sleep(.05)
|
||||
assert (idp / "url").is_file(), "fixture did not initialize"
|
||||
url = (idp / "url").read_text() + "/.well-known/openid-configuration"
|
||||
if trusted:
|
||||
shutil.copyfile(idp / "ca.pem", d / "certs/CAs/lab.pem")
|
||||
sport, cport = port(), port()
|
||||
address = f"127.0.0.1:{sport}"
|
||||
api, console = "http://" + address, f"http://127.0.0.1:{cport}"
|
||||
password = secrets.token_urlsafe(24)
|
||||
env = dict(BASE, MINIO_ROOT_USER="local154", MINIO_ROOT_PASSWORD=password, MINIO_BROWSER="on")
|
||||
if debug:
|
||||
env["GODEBUG"] = debug
|
||||
if oidc:
|
||||
env.update(MINIO_IDENTITY_OPENID_CONFIG_URL=url,
|
||||
MINIO_IDENTITY_OPENID_CLIENT_ID="local154",
|
||||
MINIO_IDENTITY_OPENID_CLIENT_SECRET="local154-placeholder",
|
||||
MINIO_IDENTITY_OPENID_REDIRECT_URI=console + "/oauth_callback")
|
||||
server = subprocess.Popen([str(ROOT / "bin" / binary), "--config-dir", str(d / "config"), "--certs-dir", str(d / "certs"), "server", "--address", address, "--console-address", f"127.0.0.1:{cport}", str(d / "data")], env=env, stdout=logs, stderr=subprocess.STDOUT)
|
||||
until = time.monotonic() + 15
|
||||
while time.monotonic() < until:
|
||||
assert server.poll() is None, "Server exited; inspect its local log"
|
||||
status, _, _ = request(api + "/minio/health/cluster")
|
||||
if status == 200 and request(console)[0] == 200:
|
||||
break
|
||||
if not expected and (d / "server.log").read_text().count("Waiting for OpenID") >= 2:
|
||||
break
|
||||
time.sleep(.1)
|
||||
result = {"case": name, "binary": binary, "mode": mode, "godebug": debug, "tls13": tls13,
|
||||
"cluster": request(api + "/minio/health/cluster")[0],
|
||||
"ready": request(api + "/minio/health/ready")[0], "console": request(console)[0]}
|
||||
assert result["cluster"] == (200 if expected else 503), result
|
||||
aenv = dict(BASE, LAB_SERVER=address, LAB_USER="local154", LAB_PASSWORD=password, LAB_OIDC_URL=url)
|
||||
if expected:
|
||||
admin = subprocess.run([str(ROOT / "bin/admin-check")], env=aenv, capture_output=True, text=True, timeout=7)
|
||||
result["admin_list_ok"] = admin.returncode == 0
|
||||
assert result["admin_list_ok"], admin.stdout
|
||||
curl = subprocess.run(["curl", "--cacert", str(idp / "ca.pem"), "--http2", "--max-time", "3", "-sS", "-o", "/dev/null", "-w", "%{http_code} %{http_version}", url], env=BASE, capture_output=True, text=True, timeout=5)
|
||||
result["curl"] = {"exit": curl.returncode, "status_protocol": curl.stdout}
|
||||
if add:
|
||||
attempt = subprocess.run([str(ROOT / "bin/admin-check"), "add"], env=aenv, capture_output=True, text=True, timeout=7)
|
||||
result["add_ok"] = attempt.returncode == 0
|
||||
result["add_reset"] = "connection reset by peer" in attempt.stdout
|
||||
assert result["add_ok"] == binary.startswith("candidate"), result
|
||||
if oauth:
|
||||
result["oauth"] = login(console, idp / "ca.pem")
|
||||
assert result["oauth"]["login_status"] == 204 and result["oauth"]["buckets_status"] == 200, result
|
||||
for bad in ("bad-signature", "bad-audience"):
|
||||
(idp / "mode").write_text(bad)
|
||||
result[bad] = login(console, idp / "ca.pem")
|
||||
assert result[bad]["login_status"] >= 400 and result[bad]["buckets_status"] >= 400, result
|
||||
# Public handshake metadata only; no authorization parameters.
|
||||
result["events"] = [json.loads(line) for line in (d / "fixture.jsonl").read_text().splitlines()]
|
||||
(d / "result.json").write_text(json.dumps(result, indent=2) + "\n")
|
||||
print(json.dumps({k: v for k, v in result.items() if k != "events"}), flush=True)
|
||||
finally:
|
||||
if server is not None:
|
||||
stop(server)
|
||||
stop(fixture)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run("old126-normal", "old-go126")
|
||||
run("old127-normal", "old-go127")
|
||||
run("old126-compat", "old-go126", "reject-mlkem", "tlsmlkem=0")
|
||||
run("old127-compat", "old-go127", "reject-mlkem", "tlsmlkem=0", expected=False)
|
||||
run("head127-compat", "head-go127", "reject-mlkem", "tlsmlkem=0", expected=False)
|
||||
run("candidate127-compat-login", "candidate-go127", "reject-mlkem", "tlsmlkem=0", oauth=True)
|
||||
run("candidate127-no-optout", "candidate-go127", "reject-mlkem", expected=False)
|
||||
run("candidate127-tls13-login", "candidate-go127", tls13=True, oauth=True)
|
||||
run("candidate127-untrusted", "candidate-go127", trusted=False, expected=False)
|
||||
run("candidate127-mldsa", "candidate-go127", "reject-mldsa", "tlsmlkem=0", expected=False)
|
||||
run("head127-add", "head-go127", "reject-mlkem", "tlsmlkem=0", oidc=False, add=True)
|
||||
run("candidate127-add", "candidate-go127", "reject-mlkem", "tlsmlkem=0", oidc=False, add=True)
|
||||
@@ -0,0 +1,143 @@
|
||||
# Remaining release correctness work, 2026-09-11
|
||||
|
||||
This records the three work items agreed after the branch/PR consolidation:
|
||||
OIDC #154, Linux restart/readback #116, and the related multi-pool defects
|
||||
#133/#144. The maintained target is SILO with the PGSTY Console, mcli and
|
||||
silo-pkg dependencies in the repository's current `go.mod`.
|
||||
|
||||
## Multi-pool writes and conditional deletion (#133, #144)
|
||||
|
||||
The pools layer now holds its object write lock across PUT and multipart
|
||||
completion, as it already does for metadata updates and DELETE. Multipart
|
||||
completion acquires the object lock before the upload lock. Queued healing and
|
||||
drive healing use this namespace too; healing under a caller-owned lock retains
|
||||
that lock's cancellation context. The destination-pool allocation policy is
|
||||
unchanged.
|
||||
|
||||
Trusted replica writes resolve the addressed version in every pool, including
|
||||
draining and rebalancing pools. Retention, legal hold and tags retain their
|
||||
independent ordering timestamps. A timestamp-only removal survives a stale
|
||||
retransmit. Completion resolves the version persisted in the upload, including
|
||||
the null version, rather than taking a later latest version's metadata.
|
||||
|
||||
Successful replica replacement retires competing copies of that exact version,
|
||||
so an equal-ModTime copy in an earlier pool cannot shadow the reconciled result.
|
||||
Metadata updates evaluate their callback once against the merged version and
|
||||
update all its copies. Replica metadata COPY rechecks ordering under the lock.
|
||||
Cleanup failures propagate; a replacement may already have committed when
|
||||
cleanup fails, and a retry can finish cleanup. Data movement keeps ownership of
|
||||
its source cleanup.
|
||||
|
||||
Retiring copies preserves any remote-tier reference still held by a surviving
|
||||
copy, including temporarily restored objects. Only the last copy of that tier
|
||||
reference schedules remote contents for garbage collection. This also protects
|
||||
the authoritative copy if the final conditional deletion fails; unrelated tier
|
||||
contents remain eligible for cleanup.
|
||||
|
||||
Conditional DELETE evaluates its precondition against the logical latest or
|
||||
explicitly addressed version. It checks all pools before mutation, removes
|
||||
secondary copies before the authoritative one, and returns cleanup errors.
|
||||
Versioned DELETE without a version ID creates a delete marker and preserves
|
||||
version history. Retention and replication callbacks evaluate the reconciled
|
||||
logical version. The existing all-pool delete helper also propagates errors
|
||||
from non-first pools.
|
||||
|
||||
The deterministic two-pool, 32-drive fixtures cover version selection,
|
||||
duplicate removal, delete failure propagation, PUT/DELETE and completion/DELETE
|
||||
interleavings, independent lock winners, draining/rebalancing owners, null
|
||||
versions, metadata COPY, metadata/healing serialization and cleanup retry.
|
||||
Tiered-copy tests inspect the persisted garbage-collection markers after
|
||||
metadata COPY, restored COPY, successful deletion and failed primary deletion,
|
||||
with distinct remote references as cleanup controls.
|
||||
The original branch reproduced the wrong-version lookup, surviving duplicate,
|
||||
suppressed delete error, PUT/DELETE race, and PUT/completion lock-state failures
|
||||
before the fixes were applied.
|
||||
|
||||
Before the final tier-reference guard, local validation passed the full `cmd`
|
||||
suite (255.720 s), all `internal` tests, `go vet ./...`, generated-file checks
|
||||
and the branding/entrypoint checks.
|
||||
Focused race checks cover the pooled interleavings, SSE-C lock regressions,
|
||||
conditional deletion, access-tier movement and TLS defaults. The two-pool and
|
||||
related replica/delete/movement tests also passed as a Linux/arm64 test binary
|
||||
in an isolated container with an 8 GiB `/tmp` tmpfs. Its initial 1 GiB tmpfs
|
||||
was insufficient for the existing single-drive test fixtures' free-space guard.
|
||||
The final tier-reference guard passed all six new cases in that Linux fixture;
|
||||
the retained restart binary below predates this guard and has no remote tier
|
||||
configured.
|
||||
|
||||
## Linux restart/readback (#116)
|
||||
|
||||
The [runner](issue-116/run-linux.py) creates four Linux/arm64 server containers
|
||||
on one Docker Desktop Linux VM, with separate network identities and one drive
|
||||
per node (EC 2+2). A holder container keeps four 256 MiB Linux tmpfs named
|
||||
volumes mounted across full server stops. Docker's ordinary filesystem had
|
||||
only 3.8 GiB free out of 2 TiB and correctly hit the server's free-space limit;
|
||||
the test uses the separate tmpfs filesystems without changing that threshold.
|
||||
This is the four-containers-on-one-Linux-host option explicitly accepted in
|
||||
the [#116 V1 plan](https://github.com/pgsty/silo/issues/116).
|
||||
|
||||
This covers process/container restart and TCP peer reconnection on one Linux
|
||||
host. It does not establish independent-host, host-reboot or physical-media
|
||||
durability. Every resource created by the runner is removed in its cleanup.
|
||||
The [retained summary](issue-116/evidence-20260911.json) records image identities,
|
||||
per-coordinator observations and readback counts.
|
||||
|
||||
| Binary | Full restart to all admin views online | Admin gate to complete 4 PUT / 16 GET round | Timed readbacks | Final readback |
|
||||
|---|---:|---:|---:|---:|
|
||||
| 0806 release | 2.084 s | 14.449 s | 660 / 660 | 240 / 240 |
|
||||
| 0903 release | 2.284 s | 0.191 s | 96 / 96 | 52 / 52 |
|
||||
| Current fix candidate | 2.461 s | 14.489 s | 1356 / 1356 | 904 / 904 |
|
||||
|
||||
Each canary has one hard 60-second deadline covering setup, requests, response
|
||||
body reads and sleeps, with SDK retries disabled. Every acknowledged PUT uses
|
||||
a unique versioned key and immediately records its VersionId, size and SHA-256.
|
||||
The timed checks reread these same objects through all four coordinators at
|
||||
15, 30 and 60 seconds **after the data canary succeeds**. They do not replace
|
||||
early acknowledgements with later writes. The final check also includes writes
|
||||
made during the one-node outage and subsequent rejoin canary.
|
||||
|
||||
All three runs passed the bounded canary, scheduled readbacks, one-node-outage
|
||||
read/write and rejoin readback. The candidate also showed a rejoin window:
|
||||
admin online at 2.490 s, complete data canary 13.977 s later. These are individual
|
||||
observations, not a latency guarantee or a comparison proving one version
|
||||
faster. Admin/health readiness still must be followed by a data-path check.
|
||||
|
||||
To repeat with cached images and a native mcli executable:
|
||||
|
||||
```sh
|
||||
uv run --with boto3==1.43.92 docs/investigations/issue-116/run-linux.py \
|
||||
0806 0903 --output /tmp/silo-linux-acceptance --mcli /path/to/mcli
|
||||
|
||||
CGO_ENABLED=0 GOOS=linux GOARCH=arm64 go build -tags kqueue -o /tmp/silo-linux .
|
||||
uv run --with boto3==1.43.92 docs/investigations/issue-116/run-linux.py \
|
||||
current --output /tmp/silo-linux-candidate --mcli /path/to/mcli \
|
||||
--current-binary /tmp/silo-linux --source-revision "$(git rev-parse HEAD)"
|
||||
```
|
||||
|
||||
The runner uses `--pull=never`; preload the two release images, `alpine:3.23`,
|
||||
and the Linux base image selected with `--current-image`. Match the candidate
|
||||
binary architecture to that image. Detailed local evidence, including the
|
||||
acknowledgement ledger and full logs, remains in the requested output directory.
|
||||
|
||||
## OIDC (#154)
|
||||
|
||||
The TLS implementation fix was already merged in `48e1846525cc`: transports
|
||||
honor Go's key-exchange defaults, so `GODEBUG=tlsmlkem=0` can opt out of ML-KEM
|
||||
for an ingress that rejects it. It does not disable certificate validation or
|
||||
force an automatic protocol downgrade. See the existing
|
||||
[Go 1.27 investigation](go127-stack.md) and [issue investigation](issue-154.md).
|
||||
|
||||
A Linux build of main `b32f2d9dd01a` passed fresh isolated fixture checks:
|
||||
|
||||
- ML-KEM-intolerant IdP with `tlsmlkem=0`: discovery, IAM, Console login (204),
|
||||
authenticated bucket listing (200).
|
||||
- Normal TLS 1.3 IdP without that override: the same complete login chain.
|
||||
- Add OIDC through the real administration API with the compatibility setting.
|
||||
- Invalid JWT signature and audience: no session cookie and bucket access 403.
|
||||
- Untrusted CA: discovery fails and cluster readiness remains 503.
|
||||
|
||||
The affected customer's discovery URL and ingress configuration are still
|
||||
unavailable. This establishes the supported local fix and its negative
|
||||
controls, not the root cause or recovery of that hidden deployment. #154 stays
|
||||
open for an affected-environment retest; no release date or published artifact
|
||||
is implied by these checks.
|
||||
@@ -33,6 +33,7 @@ The first Silo community release was cut from upstream history that already cont
|
||||
| `SN-2026-008` | [PR #101](https://github.com/pgsty/silo/pull/101) ([`938603458`](https://github.com/pgsty/silo/commit/938603458) through [`04b097fd9`](https://github.com/pgsty/silo/commit/04b097fd9)) | Internal replication request headers such as `X-Minio-Source-Etag`, `X-Minio-Source-Mtime`, `X-Minio-Source-Replication-Request`, the replication SSE key headers, and `X-Amz-Bucket-Replication-Status` on object reads, writes, multipart uploads, deletes, Snowball extraction, and bucket events | Yes; any authenticated principal that can read or write the object | Completes CVE-2026-34204. The server still trusted these internal headers on presence in most handlers: any client could preserve arbitrary ETags and modification times, read SSE-C ciphertext without the key, inject replication checksums and Object Lock timestamps, suppress bucket notifications, and route deletes as replication deletes. | Replication semantics now require the exact marker value together with `s3:ReplicateObject` or `s3:ReplicateDelete`; other requests have these headers removed after signature verification and are processed as ordinary requests. Site replication service accounts and bucket-replication targets that already hold the replication permissions are unaffected. Inherited from upstream. |
|
||||
| `SN-2026-009` | [`58735ee38`](https://github.com/pgsty/silo/commit/58735ee38) and [`229fe2b3c`](https://github.com/pgsty/silo/commit/229fe2b3c) ([PR #73](https://github.com/pgsty/silo/pull/73)) | Admin `SetUserStatus` and `SetGroupStatus` | Yes; authenticated admin API | Status changes were authorized against `admin:EnableUser` / `admin:EnableGroup` regardless of the requested status, so a principal allowed only to enable could also disable, and vice versa. | Enable and disable now require the action matching the target status. Policies that grant only one of the pair lose the other operation; `admin:*` and the built-in `consoleAdmin` policy are unaffected. Inherited from upstream. |
|
||||
| `SN-2026-010` | [PR #104](https://github.com/pgsty/silo/pull/104) ([`75a6734e4`](https://github.com/pgsty/silo/commit/75a6734e4) through [`d2d47a41f`](https://github.com/pgsty/silo/commit/d2d47a41f), [#58](https://github.com/pgsty/silo/issues/58)) | `DeleteObject` and `DeleteObjects` with an explicit `versionId` | Yes; authenticated S3 API | Explicit version deletes were authorized as `s3:DeleteObject` with only a deny check on `s3:DeleteObjectVersion`, diverging from AWS. | Explicit version deletes now require `s3:DeleteObjectVersion`, as on AWS. **Two policy effects:** principals granted only `s3:DeleteObject` can no longer delete specific versions, and a policy that relied on `Deny s3:DeleteObject` to block permanent deletes must also deny `s3:DeleteObjectVersion`, because `Allow s3:*` now permits explicit version deletes. Replication targets keep the `s3:ReplicateDelete` contract. Inherited from upstream. |
|
||||
| `SN-2026-011` | [`123325430`](https://github.com/pgsty/silo/commit/1233254309b15571f101b2b26d531951ceaeef1e) | SigV4 signed-header coverage; `x-amz-copy-source` dispatch to `CopyObject` / `UploadPartCopy` | Yes; a party holding only a presigned PUT URL, or any signed PUT, needs no credentials of its own | SigV4 verification only checked that each named signed header was present and never inspected the `x-amz-*` headers that actually arrived (the meta-header check covered only `X-Amz-Meta-` and ran only on the presigned path), while the router dispatches any PUT carrying `x-amz-copy-source` to `CopyObjectHandler`. An unsigned `x-amz-copy-source` therefore turned a one-object write grant into a server-side copy of any object the signing key can read, executed as the signer; both the presigned and Authorization-header paths were affected, and where the destination bucket allows anonymous `GetObject` the copied private bytes become readable unauthenticated. | Any unsigned `x-amz-*` request header is now refused with `AccessDenied` on both paths, matching AWS S3 (AWS returns `403`; Silo returns `400 AccessDenied`, otherwise identical). Membership in the signed-headers list is required, so a header whose first value is empty cannot slip through. `X-Amz-Content-Sha256` remains accepted unsigned (payload hash, taken from the query for presigned requests and bound into the string-to-sign for signed ones); the internal `X-Amz-Signature-Age` scratch header is exempt so repeated verification stays idempotent; `PutObjectTagging` now injects its body-derived `X-Amz-Tagging` header after signature verification. Every AWS SDK, `minio-go`, and `mc` already signs its `x-amz-*` headers, so legitimate clients need no change. Inherited unchanged from upstream `minio/minio`; every earlier release is affected. Reported by Oren Yomtov; a CVE has been requested. |
|
||||
|
||||
## Dependency security updates
|
||||
|
||||
|
||||
@@ -4,9 +4,9 @@ go 1.27.1
|
||||
|
||||
// Console and MC retain their historical module paths for best-effort upstream
|
||||
// compatibility. Pin the maintained PGSTY implementations used by SILO.
|
||||
replace github.com/minio/console => github.com/pgsty/silo-console v0.0.0-20260908142700-c103d08ec36a
|
||||
replace github.com/minio/console => github.com/pgsty/silo-console v0.0.0-20260911085047-638eefd7aece
|
||||
|
||||
replace github.com/minio/mc => github.com/pgsty/mc v0.0.0-20260909015522-fcd5cad8247f
|
||||
replace github.com/minio/mc => github.com/pgsty/mc v0.0.0-20260910093317-e6a60edf0952
|
||||
|
||||
// v22.7.0 does not compile on NetBSD because its unix implementation uses
|
||||
// CLOCK_MONOTONIC, which is unavailable there. Keep the last portable release
|
||||
@@ -68,7 +68,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.3.1-0.20260828014306-0e78d3f18efe
|
||||
github.com/minio/minio-go/v7 v7.3.1-0.20260909183557-78bfa91607c2
|
||||
github.com/minio/mux v1.10.1
|
||||
github.com/minio/selfupdate v0.6.0
|
||||
github.com/minio/simdjson-go v0.4.5
|
||||
@@ -81,7 +81,7 @@ require (
|
||||
github.com/nats-io/stan.go v0.10.4
|
||||
github.com/ncw/directio v1.0.5
|
||||
github.com/nsqio/go-nsq v1.1.0
|
||||
github.com/pgsty/silo-pkg/v3 v3.13.3
|
||||
github.com/pgsty/silo-pkg/v3 v3.13.4-0.20260910091716-2d8fd3cbbf07
|
||||
github.com/philhofer/fwd v1.2.0
|
||||
github.com/pierrec/lz4/v4 v4.1.29
|
||||
github.com/pkg/errors v0.9.1
|
||||
@@ -92,7 +92,7 @@ require (
|
||||
github.com/prometheus/common v0.71.0
|
||||
github.com/prometheus/procfs v0.22.0
|
||||
github.com/puzpuzpuz/xsync/v3 v3.5.1
|
||||
github.com/rabbitmq/amqp091-go v1.10.0
|
||||
github.com/rabbitmq/amqp091-go v1.14.0
|
||||
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9
|
||||
github.com/rs/cors v1.11.1
|
||||
github.com/secure-io/sio-go v0.3.1
|
||||
|
||||
@@ -474,8 +474,8 @@ 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.3.1-0.20260828014306-0e78d3f18efe h1:By2FKNSOUGLOeb0x4D7xJMHr8x/X1ZW8PG780SpKUwQ=
|
||||
github.com/minio/minio-go/v7 v7.3.1-0.20260828014306-0e78d3f18efe/go.mod h1:KUPWdecEO1LWyUz+sTGXAuf2jZHrPh5fCsRH86QbPfk=
|
||||
github.com/minio/minio-go/v7 v7.3.1-0.20260909183557-78bfa91607c2 h1:nvX7IksPFOF/cBvkSg/Z+urBZkmhZrfUVmzdNFLjZ5Y=
|
||||
github.com/minio/minio-go/v7 v7.3.1-0.20260909183557-78bfa91607c2/go.mod h1:KUPWdecEO1LWyUz+sTGXAuf2jZHrPh5fCsRH86QbPfk=
|
||||
github.com/minio/mux v1.10.1 h1:grrK8SwRKbkNFE6qG7WAvFGH09bB46d5teOOtKfQ14s=
|
||||
github.com/minio/mux v1.10.1/go.mod h1:INYT4sMSTJy0QWUEA/E2DZNxJ5sAxIwbnyZjkzNFRfE=
|
||||
github.com/minio/pkg/v3 v3.6.1 h1:gaNT80BS/iuIany5ylTkVmfN4s6UYY30OtImFv4GQA8=
|
||||
@@ -545,12 +545,12 @@ 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-20260909015522-fcd5cad8247f h1:JiL/FcsGMsAhA+Iv+0Jzk9VnEAVVv4HUNbR0cGf+/CE=
|
||||
github.com/pgsty/mc v0.0.0-20260909015522-fcd5cad8247f/go.mod h1:VHif+uy3s+nOcQKy808NlNpYawINOeGSyisgjoSBNVs=
|
||||
github.com/pgsty/silo-console v0.0.0-20260908142700-c103d08ec36a h1:aHLqQ7INozqGLEOB1tr+n/eKgrBhlQ20fHyLmeNu+ao=
|
||||
github.com/pgsty/silo-console v0.0.0-20260908142700-c103d08ec36a/go.mod h1:d16nCLu7flJ6Fv0hPTW+JsyjhgyqZN87//URYO0nETU=
|
||||
github.com/pgsty/silo-pkg/v3 v3.13.3 h1:d2xYTn4LXoWIAIjBlW/17wtA/Ut1ap29t+1ww4TFa8o=
|
||||
github.com/pgsty/silo-pkg/v3 v3.13.3/go.mod h1:0GmaDA0ArQ8bkAI/obiSNTBQzdgBu6W0e0olDCbyXXo=
|
||||
github.com/pgsty/mc v0.0.0-20260910093317-e6a60edf0952 h1:b6jpBuZWUiZhBox64eF1cmNL4HWGwdSk/LVXNc3DBQ0=
|
||||
github.com/pgsty/mc v0.0.0-20260910093317-e6a60edf0952/go.mod h1:VsGNEmditljwBgmYKy7X+//dXLN8gEfSPR2m4lcMPmo=
|
||||
github.com/pgsty/silo-console v0.0.0-20260911085047-638eefd7aece h1:1QGCeVCRV4TzDLww9IFfRT70YOI8r/X88pRo+KILvZ4=
|
||||
github.com/pgsty/silo-console v0.0.0-20260911085047-638eefd7aece/go.mod h1:bCyOnZactQajLOqlgCn0lHwQWMNylvP6MUOqqLako00=
|
||||
github.com/pgsty/silo-pkg/v3 v3.13.4-0.20260910091716-2d8fd3cbbf07 h1:IKm2AyPsvuL4NyniK3ixqqQz1CIargmhyCkL2eZvlhA=
|
||||
github.com/pgsty/silo-pkg/v3 v3.13.4-0.20260910091716-2d8fd3cbbf07/go.mod h1:1JdcUcM+TRXObb9QrC8FWhav0RKk6/u8RT2RgimfxRQ=
|
||||
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.29 h1:CDQY6qZOLI4DW0Nx6R1vRrifrCeQHnNXkMb0hZWXFjg=
|
||||
@@ -590,8 +590,8 @@ github.com/prometheus/prometheus v0.314.0 h1:YjsimqsIi6/mOtzZcrPEYUALO6zpfaht9O5
|
||||
github.com/prometheus/prometheus v0.314.0/go.mod h1:zjg3pMTAkY0/JG8jy/h8/YgSQUVB+aCXMhUqN6l64jg=
|
||||
github.com/puzpuzpuz/xsync/v3 v3.5.1 h1:GJYJZwO6IdxN/IKbneznS6yPkVC+c3zyY/j19c++5Fg=
|
||||
github.com/puzpuzpuz/xsync/v3 v3.5.1/go.mod h1:VjzYrABPabuM4KyBh1Ftq6u8nhwY5tBPKP9jpmh0nnA=
|
||||
github.com/rabbitmq/amqp091-go v1.10.0 h1:STpn5XsHlHGcecLmMFCtg7mqq0RnD+zFr4uzukfVhBw=
|
||||
github.com/rabbitmq/amqp091-go v1.10.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/rabbitmq/amqp091-go v1.14.0 h1:RSaT7aOKt/OrkVUyswPDW29lnRz9psuGmfZFBmLqLek=
|
||||
github.com/rabbitmq/amqp091-go v1.14.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o=
|
||||
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9 h1:bsUq1dX0N8AOIL7EB/X911+m4EHsnWEHeJ0c+3TTBrg=
|
||||
github.com/rcrowley/go-metrics v0.0.0-20250401214520-65e299d6c5c9/go.mod h1:bCqnVzQkZxMG4s8nGwiZ5l3QUCyqpo9Y+/ZMZ9VjZe4=
|
||||
github.com/rivo/uniseg v0.1.0/go.mod h1:J6wj4VEh+S6ZtnVlnTBMWIodfgj8LQOQFoIToxlJtxc=
|
||||
|
||||
@@ -166,7 +166,6 @@ func LookupConfig(kvs config.KVS, rootCAs *x509.CertPool) (Config, error) {
|
||||
NextProtos: []string{"http/1.1", "h2"},
|
||||
ClientSessionCache: tls.NewLRUClientSessionCache(64),
|
||||
CipherSuites: crypto.TLSCiphersBackwardCompatible(),
|
||||
CurvePreferences: crypto.TLSCurveIDs(),
|
||||
}
|
||||
// This is only to support client side certificate authentication
|
||||
// https://coreos.com/etcd/docs/latest/op-guide/security.html
|
||||
|
||||
@@ -70,9 +70,3 @@ func TLSCiphersBackwardCompatible() []uint16 {
|
||||
tls.TLS_RSA_WITH_AES_256_CBC_SHA,
|
||||
}
|
||||
}
|
||||
|
||||
// TLSCurveIDs returns a list of supported elliptic curve IDs
|
||||
// in preference order.
|
||||
func TLSCurveIDs() []tls.CurveID {
|
||||
return []tls.CurveID{tls.X25519MLKEM768, tls.CurveP256, tls.X25519, tls.CurveP384, tls.CurveP521}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
// Copyright (c) 2026 PGSTY
|
||||
// SPDX-License-Identifier: AGPL-3.0-only
|
||||
|
||||
package target
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/rabbitmq/amqp091-go"
|
||||
)
|
||||
|
||||
// A broker must not make the notification client allocate or read an oversized
|
||||
// frame, including before connection.tune negotiates the frame size limit.
|
||||
func TestAMQPRejectsOversizedHandshakeFrame(t *testing.T) {
|
||||
listener, err := net.Listen("tcp", "127.0.0.1:0")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { listener.Close() })
|
||||
|
||||
uri, err := amqp091.ParseURI("amqp://" + listener.Addr().String())
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
target, err := NewAMQPTarget("oversized-frame", AMQPArgs{Enable: true, URL: uri},
|
||||
func(context.Context, error, string, ...any) {})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
t.Cleanup(func() { target.Close() })
|
||||
|
||||
brokerDone := make(chan error, 1)
|
||||
go func() {
|
||||
brokerDone <- func() error {
|
||||
conn, err := listener.Accept()
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
defer conn.Close()
|
||||
if err := conn.SetDeadline(time.Now().Add(5 * time.Second)); err != nil {
|
||||
return err
|
||||
}
|
||||
var protocol [8]byte
|
||||
if _, err := io.ReadFull(conn, protocol[:]); err != nil {
|
||||
return err
|
||||
}
|
||||
if protocol != [8]byte{'A', 'M', 'Q', 'P', 0, 0, 9, 1} {
|
||||
return fmt.Errorf("unexpected AMQP protocol header: %x", protocol)
|
||||
}
|
||||
// A method frame declaring an 8 KiB payload exceeds the 4 KiB
|
||||
// pre-negotiation limit. Send only its header: rejection must
|
||||
// happen without allocating or waiting for the declared body.
|
||||
if _, err := conn.Write([]byte{1, 0, 0, 0, 0, 0x20, 0}); err != nil {
|
||||
return err
|
||||
}
|
||||
var response [1]byte
|
||||
if n, err := conn.Read(response[:]); n != 0 || !errors.Is(err, io.EOF) {
|
||||
return fmt.Errorf("client did not close after oversized frame header: read %d bytes, error %v", n, err)
|
||||
}
|
||||
return nil
|
||||
}()
|
||||
}()
|
||||
|
||||
active, err := target.IsActive()
|
||||
if active || err == nil {
|
||||
t.Errorf("oversized handshake frame accepted: active=%v, error=%v", active, err)
|
||||
}
|
||||
if err := <-brokerDone; err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
@@ -46,9 +46,8 @@ type ConnSettings struct {
|
||||
DialTimeout time.Duration
|
||||
|
||||
// TLS Settings
|
||||
RootCAs *x509.CertPool
|
||||
CipherSuites []uint16
|
||||
CurvePreferences []tls.CurveID
|
||||
RootCAs *x509.CertPool
|
||||
CipherSuites []uint16
|
||||
|
||||
// HTTP2
|
||||
EnableHTTP2 bool
|
||||
@@ -70,7 +69,6 @@ func (s ConnSettings) getDefaultTransport(maxIdleConnsPerHost int) *http.Transpo
|
||||
tlsClientConfig := tls.Config{
|
||||
RootCAs: s.RootCAs,
|
||||
CipherSuites: s.CipherSuites,
|
||||
CurvePreferences: s.CurvePreferences,
|
||||
ClientSessionCache: tls.NewLRUClientSessionCache(tlsClientSessionCacheSize),
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user