fix(objectgateway): 取消整桶独占前置并按维护停写更新
build / build (push) Failing after 2m29s

现象:共享桶部署下网关启动即报 gateway_auditor_key_required,残留过期
审计文件则每次 Execute 报 gateway_exclusive_writer_evidence_unverified;
用户已改为“停目标写入容器→更新→启动”的维护式更新。

根因:Gateway.Ready 强制 Isolation.Verify,main 强制 Ed25519 公钥,等于
把整桶独占证明当作发布前置;这与共享桶、沿用原 AK 的实际部署矛盾。

取舍:删除审计校验与相关 env 依赖,保留 journal、治理 PG 只读 authority、
plan/owner/attempt/epoch 绑定、intent-before-send、单次写与精确版本回滚。
create 仅在精确版本读回且仍为 current 时提交;发现外部 latest 只返回冲突,
不在 confirm 阶段删除(journal create intent 已提交,删除会变成无 delete
intent/receipt 的未记账副作用并让 intent 永久 held)。同 key 不自动合并。

证据:真实二进制无审计/残留审计两环境通过;kg-pgtest-writeset 一次性库 +
随机 MinIO 桶跑 14 个网关用例(含共享桶共存写者、同 key 既有对象拒绝、
精确回滚)全过;umask 022 下 make verify 本地必需项全 success。
This commit is contained in:
姚章浩
2026-11-04 09:45:47 +08:00
parent 017765763a
commit a55319d972
25 changed files with 510 additions and 171 deletions
@@ -24,7 +24,7 @@ func TestGatewayAcquisitionPersistsAttemptDelivery(t *testing.T) {
expected := g.Grant{Epoch: 1, Owner: g.Digest([]byte(claim.JobID)), Plan: claim.PlanDigest}
req := request("acquired-object", expected)
authority := &currentPlanAuthority{claim, planFor(expected, req)}
gateway := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20, Authority: authority}
gateway := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, MaxBytes: 1 << 20, Authority: authority}
grant, e := gateway.Acquire(ctx, claim)
if e != nil || grant != expected {
t.Fatal("anchored active attempt grant unavailable", e)
@@ -79,7 +79,7 @@ func TestGatewayAcquisitionCannotHandOverUnknownSend(t *testing.T) {
req := request("acquire-held", expected)
body := []byte("gateway fixture acquire-held")
authority := &currentPlanAuthority{claim, planFor(expected, req)}
gateway := &g.Gateway{Pool: pool, Scope: real.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20, Authority: authority}
gateway := &g.Gateway{Pool: pool, Scope: real.Bucket, Backend: backend, MaxBytes: 1 << 20, Authority: authority}
if _, e := gateway.Acquire(ctx, claim); e != nil {
t.Fatal(e)
}
@@ -0,0 +1,26 @@
package objectgateway
import (
"encoding/json"
"time"
)
// Attestation is the retired whole-bucket exclusive-writer evidence format.
// It is kept only so historical audit artifacts remain readable; no runtime
// path loads, verifies or requires it. Admission is the journal, the backend
// capability and the frozen plan, all of which work on a shared bucket.
type Attestation struct {
Protocol string `json:"protocol"`
Scope string `json:"scope"`
GatewayID string `json:"gateway_id"`
IssuedAt time.Time `json:"issued_at"`
ExpiresAt time.Time `json:"expires_at"`
WriterInventory string `json:"writer_inventory_sha256"`
PolicyEvidence string `json:"policy_evidence_sha256"`
DenialEvidence string `json:"denial_evidence_sha256"`
DrainEvidence string `json:"drain_evidence_sha256"`
}
type SignedAttestation struct {
Payload json.RawMessage `json:"payload"`
Signature []byte `json:"signature"`
}
-57
View File
@@ -1,57 +0,0 @@
package objectgateway
import (
"context"
"crypto/ed25519"
"encoding/json"
"os"
"time"
)
// Attestation is issued by an independent deployment auditor, never by a worker.
// Its signature authenticates an audit, not the truth of self-reported config.
// Runtime cutover must invalidate/replace the audit whenever writer rights change.
type Attestation struct {
Protocol string `json:"protocol"`
Scope string `json:"scope"`
GatewayID string `json:"gateway_id"`
IssuedAt time.Time `json:"issued_at"`
ExpiresAt time.Time `json:"expires_at"`
WriterInventory string `json:"writer_inventory_sha256"`
PolicyEvidence string `json:"policy_evidence_sha256"`
DenialEvidence string `json:"denial_evidence_sha256"`
DrainEvidence string `json:"drain_evidence_sha256"`
}
type SignedAttestation struct {
Payload json.RawMessage `json:"payload"`
Signature []byte `json:"signature"`
}
type AuditVerifier struct {
Path string
PublicKey ed25519.PublicKey
Scope, GatewayID string
}
func (v AuditVerifier) Verify(ctx context.Context) error {
if ctx.Err() != nil {
return ErrIsolation
}
st, e := os.Lstat(v.Path)
if e != nil || !st.Mode().IsRegular() || st.Size() > 16384 || st.Mode().Perm()&0022 != 0 {
return ErrIsolation
}
raw, e := os.ReadFile(v.Path)
if e != nil {
return ErrIsolation
}
var signed SignedAttestation
var a Attestation
if json.Unmarshal(raw, &signed) != nil || len(v.PublicKey) != ed25519.PublicKeySize || !ed25519.Verify(v.PublicKey, signed.Payload, signed.Signature) || json.Unmarshal(signed.Payload, &a) != nil {
return ErrIsolation
}
now := time.Now()
if a.Protocol != Protocol || a.Scope != v.Scope || a.GatewayID != v.GatewayID || a.GatewayID == "" || a.IssuedAt.After(now) || !a.ExpiresAt.After(now) || a.ExpiresAt.Sub(a.IssuedAt) > time.Hour || !validHash(a.WriterInventory) || !validHash(a.PolicyEvidence) || !validHash(a.DenialEvidence) || !validHash(a.DrainEvidence) {
return ErrIsolation
}
return nil
}
-59
View File
@@ -1,59 +0,0 @@
package objectgateway_test
import (
"context"
"crypto/ed25519"
"crypto/rand"
"encoding/json"
g "knowledge-governance/internal/objectgateway"
"os"
"path/filepath"
"testing"
"time"
)
func TestGatewayAuditCannotBeConfigurationBoolean(t *testing.T) {
pub, priv, e := ed25519.GenerateKey(rand.Reader)
if e != nil {
t.Fatal(e)
}
dir := t.TempDir()
path := filepath.Join(dir, "audit.json")
verifier := g.AuditVerifier{Path: path, PublicKey: pub, Scope: "target", GatewayID: "gateway"}
if verifier.Verify(context.Background()) == nil {
t.Fatal("missing audit accepted")
}
if os.WriteFile(path, []byte(`{"isolated":true,"ready":true}`), 0600) != nil {
t.Fatal("fixture")
}
if verifier.Verify(context.Background()) == nil {
t.Fatal("boolean accepted as isolation proof")
}
a := g.Attestation{Protocol: g.Protocol, Scope: "target", GatewayID: "gateway", IssuedAt: time.Now().Add(-time.Minute), ExpiresAt: time.Now().Add(30 * time.Minute), WriterInventory: g.Digest([]byte("inventory")), PolicyEvidence: g.Digest([]byte("policy")), DenialEvidence: g.Digest([]byte("denials")), DrainEvidence: g.Digest([]byte("drain"))}
write := func(v g.Attestation) {
t.Helper()
raw, _ := json.Marshal(v)
signed, _ := json.Marshal(g.SignedAttestation{Payload: raw, Signature: ed25519.Sign(priv, raw)})
if os.WriteFile(path, signed, 0600) != nil {
t.Fatal("fixture")
}
}
write(a)
if verifier.Verify(context.Background()) != nil {
t.Fatal("valid test auditor signature rejected")
}
for _, mutate := range []func(*g.Attestation){func(v *g.Attestation) { v.Scope = "other" }, func(v *g.Attestation) { v.GatewayID = "other" }, func(v *g.Attestation) { v.ExpiresAt = time.Now().Add(-time.Second) }, func(v *g.Attestation) { v.DenialEvidence = "" }, func(v *g.Attestation) { v.IssuedAt = time.Now().Add(time.Hour) }, func(v *g.Attestation) { v.ExpiresAt = time.Now().Add(24 * time.Hour) }} {
bad := a
mutate(&bad)
write(bad)
if verifier.Verify(context.Background()) == nil {
t.Fatal("invalid isolation audit accepted")
}
}
write(a)
other, _, _ := ed25519.GenerateKey(rand.Reader)
verifier.PublicKey = other
if verifier.Verify(context.Background()) == nil {
t.Fatal("untrusted signer accepted")
}
}
+43
View File
@@ -0,0 +1,43 @@
package objectgateway
import "context"
// sendCreate performs exactly one non-retried versioned PUT and then confirms
// the result. Versioned object stores do not provide atomic create-if-absent,
// so the confirmation re-reads the current version to make sure this request's
// version is still the one a reader would observe.
func sendCreate(ctx context.Context, b Backend, r Request, body []byte) (Version, error) {
v, err := b.Put(ctx, r.Key, body, r.token())
if err != nil {
// Unknown outcome: the intent stays unresolved, nothing is retried and
// nothing is deleted because no version id is confirmed.
return Version{}, ErrHeld
}
return confirmCreate(ctx, b, r, v)
}
// confirmCreate binds the receipt to a version that is both the exact version
// this request wrote and the current version of the key. It is read-only: the
// create intent is already committed, so withdrawing a version here would be an
// unrecorded mutation with no delete intent or receipt and would leave the
// create intent permanently held. A concurrent writer that produced a newer
// current version therefore wins by explicit conflict; both versions stay in
// the store and an operator resolves the key with evidence.
func confirmCreate(ctx context.Context, b Backend, r Request, v Version) (Version, error) {
exact, exists, err := b.Observe(ctx, r.Key, v.ID)
if err != nil || !exists || !r.matches(exact) || v != exact {
return Version{}, ErrHeld
}
latest, current, err := b.Observe(ctx, r.Key, "")
if err != nil || !current {
// Cannot tell whether our write is still current: keep the intent held
// rather than mutating anything on a guess.
return Version{}, ErrHeld
}
if latest.ID != v.ID {
// Another writer owns the current version. Report the conflict and leave
// both versions untouched; this path never merges them automatically.
return Version{}, ErrConflict
}
return v, nil
}
+153
View File
@@ -0,0 +1,153 @@
package objectgateway
import (
"context"
"errors"
"testing"
)
type fakeBackend struct {
byID map[string]Version
latest Version
latestExists bool
latestErr error
putVersion Version
putErr error
putCalls int
deletes []string
deleteErr error
}
func (f *fakeBackend) Ready(context.Context) error { return nil }
func (f *fakeBackend) Observe(_ context.Context, _ string, id string) (Version, bool, error) {
if id == "" {
if f.latestErr != nil {
return Version{}, false, f.latestErr
}
return f.latest, f.latestExists, nil
}
v, ok := f.byID[id]
return v, ok, nil
}
func (f *fakeBackend) List(context.Context, string) ([]Version, error) { return nil, nil }
func (f *fakeBackend) Put(context.Context, string, []byte, string) (Version, error) {
f.putCalls++
if f.putErr != nil {
return Version{}, f.putErr
}
return f.putVersion, nil
}
func (f *fakeBackend) Delete(_ context.Context, _ string, v Version) error {
if f.deleteErr != nil {
return f.deleteErr
}
f.deletes = append(f.deletes, v.ID)
delete(f.byID, v.ID)
return nil
}
func createFixture(t *testing.T) (Request, Version) {
t.Helper()
body := []byte("shared bucket object")
grant := Grant{Epoch: 1, Owner: Digest([]byte("owner")), Plan: Digest([]byte("plan"))}
r := Request{Grant: grant, Operation: Digest([]byte("operation")), Key: "kb/bound/object-1", Action: "create", SHA256: Digest(body), Bytes: int64(len(body))}
v := Version{ID: "version-own", Owner: r.token(), SHA256: r.SHA256, Bytes: r.Bytes, ETag: `"etag-own"`}
return r, v
}
func TestCreateConfirmationDetectsNewerForeignVersionWithoutSideEffects(t *testing.T) {
r, own := createFixture(t)
foreign := Version{ID: "version-foreign", Owner: Digest([]byte("foreign-owner")), SHA256: Digest([]byte("foreign")), Bytes: 7, ETag: `"etag-foreign"`}
f := &fakeBackend{byID: map[string]Version{own.ID: own, foreign.ID: foreign}, latest: foreign, latestExists: true, putVersion: own}
if _, err := confirmCreate(context.Background(), f, r, own); !errors.Is(err, ErrConflict) {
t.Fatalf("concurrent newer version accepted as committed: %v", err)
}
// Confirmation runs after the journal intent exists. Deleting here would be
// an unrecorded mutation with no delete intent/receipt and would strand the
// create intent in held forever, so confirmation must be read-only.
if len(f.deletes) != 0 {
t.Fatalf("confirmation deleted without a delete intent/receipt: %v", f.deletes)
}
if _, ok := f.byID[own.ID]; !ok {
t.Fatal("own version removed without a recorded delete")
}
if _, ok := f.byID[foreign.ID]; !ok {
t.Fatal("foreign version was deleted")
}
}
func TestCreateConfirmationCommitsOnlyWhenOwnVersionIsCurrent(t *testing.T) {
r, own := createFixture(t)
f := &fakeBackend{byID: map[string]Version{own.ID: own}, latest: own, latestExists: true, putVersion: own}
got, err := confirmCreate(context.Background(), f, r, own)
if err != nil || got != own {
t.Fatalf("own current version not committed: %v %v", got, err)
}
if len(f.deletes) != 0 {
t.Fatalf("unexpected rollback %v", f.deletes)
}
}
func TestCreateConfirmationHoldsWithoutDeletingWhenCurrentVersionUnreadable(t *testing.T) {
r, own := createFixture(t)
f := &fakeBackend{byID: map[string]Version{own.ID: own}, putVersion: own, latestErr: errors.New("read failed")}
if _, err := confirmCreate(context.Background(), f, r, own); !errors.Is(err, ErrHeld) {
t.Fatalf("unreadable current version treated as terminal: %v", err)
}
if len(f.deletes) != 0 {
t.Fatalf("deleted on an unknown observation: %v", f.deletes)
}
}
func TestCreateConfirmationHoldsOnExactReadbackMismatch(t *testing.T) {
r, own := createFixture(t)
other := own
other.ETag = `"different"`
f := &fakeBackend{byID: map[string]Version{own.ID: other}, latest: other, latestExists: true, putVersion: own}
if _, err := confirmCreate(context.Background(), f, r, own); !errors.Is(err, ErrHeld) {
t.Fatalf("mismatched readback treated as committed: %v", err)
}
if len(f.deletes) != 0 {
t.Fatalf("deleted on mismatch: %v", f.deletes)
}
}
func TestCreateSendIsSingleAttemptAndNeverDeletesUnknownPut(t *testing.T) {
r, _ := createFixture(t)
f := &fakeBackend{putErr: errors.New("transport lost")}
if _, err := sendCreate(context.Background(), f, r, []byte("shared bucket object")); !errors.Is(err, ErrHeld) {
t.Fatalf("unknown PUT treated as terminal: %v", err)
}
if f.putCalls != 1 {
t.Fatalf("PUT retried: calls=%d", f.putCalls)
}
if len(f.deletes) != 0 {
t.Fatalf("deleted without a confirmed version: %v", f.deletes)
}
}
func TestPlanAuthorizesOnlyFrozenObjectList(t *testing.T) {
body := []byte("planned")
owner, digest := Digest([]byte("owner")), Digest([]byte("plan-digest"))
p := Plan{Digest: digest, Owner: owner, Objects: []ObjectBinding{{Operation: Digest([]byte("op-1")), Key: "kb/allowed/1", SHA256: Digest(body), Bytes: int64(len(body))}}}
allowed := Request{Grant: Grant{1, owner, digest}, Operation: Digest([]byte("op-1")), Key: "kb/allowed/1", Action: "create", SHA256: Digest(body), Bytes: int64(len(body))}
if !p.allows(allowed) {
t.Fatal("frozen object rejected")
}
for name, mutate := range map[string]func(*Request){
"other_kb_key": func(r *Request) { r.Key = "kb/other-kb/1" },
"other_object": func(r *Request) { r.Key = "kb/allowed/2" },
"other_operation": func(r *Request) { r.Operation = Digest([]byte("op-2")) },
} {
got := allowed
mutate(&got)
if p.allows(got) {
t.Fatalf("%s authorized outside the frozen write set", name)
}
}
dup := p
dup.Objects = append(dup.Objects, p.Objects[0])
if dup.valid() {
t.Fatal("duplicate key accepted in plan")
}
}
+17 -10
View File
@@ -20,17 +20,18 @@ type Gateway struct {
Pool *pgxpool.Pool
Scope string
Backend Backend
Isolation IsolationVerifier
MaxBytes int64
}
// Ready gates admission on the local journal and the object backend only. A
// shared bucket is the supported deployment shape: unrelated writers on other
// keys do not need to be drained, and no whole-bucket exclusivity evidence is
// required. Per-key competition is handled at execute time, not by a global
// "only writer" attestation.
func (g *Gateway) Ready(ctx context.Context) error {
if g.Pool == nil || g.Scope == "" || g.Backend == nil || g.MaxBytes < 1 {
return ErrPersistence
}
if g.Isolation == nil || g.Isolation.Verify(ctx) != nil {
return ErrIsolation
}
var sync, fsync, full string
if g.Pool.QueryRow(ctx, "SELECT current_setting('synchronous_commit'), current_setting('fsync'), current_setting('full_page_writes')").Scan(&sync, &fsync, &full) != nil || sync != "on" || fsync != "on" || full != "on" {
return ErrPersistence
@@ -249,13 +250,9 @@ func (g *Gateway) execute(ctx context.Context, r Request, body []byte, authoriza
if exists {
return g.finish(ctx, r, "rejected", Version{})
}
v, err := g.Backend.Put(ctx, r.Key, body, r.token())
v, err := sendCreate(ctx, g.Backend, r, body)
if err != nil {
return Receipt{}, ErrHeld
}
exact, exists, err := g.Backend.Observe(ctx, r.Key, v.ID)
if err != nil || !exists || !r.matches(exact) || v != exact {
return Receipt{}, ErrHeld
return Receipt{}, err
}
return g.finish(ctx, r, "committed", v)
}
@@ -322,5 +319,15 @@ func (g *Gateway) Reconcile(ctx context.Context, r Request) (Receipt, error) {
if err != nil || !exists || exact != found[0] {
return Receipt{}, ErrHeld
}
latest, current, err := g.Backend.Observe(ctx, r.Key, "")
if err != nil || !current {
return Receipt{}, ErrHeld
}
if latest.ID != exact.ID {
// Another writer owns the current version of this key. Do not delete
// anything during reconcile and do not report a committed create for a
// key this plan no longer controls.
return Receipt{}, ErrConflict
}
return g.finish(ctx, r, "committed", exact)
}
@@ -30,9 +30,6 @@ import (
g "knowledge-governance/internal/objectgateway"
)
type verifiedFixture struct{}
func (verifiedFixture) Verify(context.Context) error { return nil }
func fixture(t *testing.T) (context.Context, *pgxpool.Pool, *g.S3Backend) {
t.Helper()
dsn := os.Getenv("KG_GATEWAY_TEST_DATABASE_URL")
@@ -118,7 +115,7 @@ func TestGatewayReadinessRequiresJournal(t *testing.T) {
t.Fatal(e)
}
defer other.Close()
gw := &g.Gateway{Pool: other, Scope: "missing-journal", Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
gw := &g.Gateway{Pool: other, Scope: "missing-journal", Backend: backend, MaxBytes: 1 << 20}
if e := gw.Ready(ctx); !errors.Is(e, g.ErrPersistence) {
t.Fatalf("missing durable journal accepted: %v", e)
}
@@ -126,7 +123,7 @@ func TestGatewayReadinessRequiresJournal(t *testing.T) {
func TestGatewayRealReplayAndImmutableLedger(t *testing.T) {
ctx, pool, backend := fixture(t)
grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("fixed-plan"))}
gw := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
gw := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, MaxBytes: 1 << 20}
if _, exists, err := backend.Observe(ctx, "missing-key-probe", ""); err != nil || exists {
t.Fatalf("initial authoritative absence unavailable: %v exists=%v", err, exists)
}
-2
View File
@@ -239,8 +239,6 @@ func (c *Client) call(ctx context.Context, path string, in, out any) error {
return ErrHeld
case ErrPersistence.Error():
return ErrPersistence
case ErrIsolation.Error():
return ErrIsolation
}
return errors.New("gateway_request_refused")
}
@@ -14,7 +14,7 @@ import (
func TestGatewayTargetIdentityOnEveryCall(t *testing.T) {
ctx, pool, backend := fixture(t)
grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("fixed-plan"))}
gw := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
gw := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, MaxBytes: 1 << 20}
if e := gw.InstallPlan(ctx, planFor(grant, request(t.Name(), grant))); e != nil {
t.Fatal(e)
}
@@ -10,7 +10,7 @@ func TestGatewayIntentCommitFailureNeverSends(t *testing.T) {
ctx, pool, real := fixture(t)
backend := &stoppedBeforeSend{Backend: real}
grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("plan"))}
gateway := &g.Gateway{Pool: pool, Scope: real.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
gateway := &g.Gateway{Pool: pool, Scope: real.Bucket, Backend: backend, MaxBytes: 1 << 20}
if e := gateway.InstallPlan(ctx, planFor(grant, request(t.Name(), grant))); e != nil {
t.Fatal(e)
}
@@ -9,7 +9,7 @@ import (
func TestGatewayGrantCannotAuthorizeUnplannedKey(t *testing.T) {
ctx, pool, backend := fixture(t)
grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("fixed-plan"))}
gateway := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
gateway := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, MaxBytes: 1 << 20}
if e := gateway.Advance(ctx, 0, grant); !errors.Is(e, g.ErrConflict) {
t.Fatal("unregistered plan grant", e)
}
-2
View File
@@ -19,7 +19,6 @@ var (
ErrPersistence = errors.New("gateway_persistence_unavailable")
ErrAuthority = errors.New("gateway_control_authority_unavailable")
ErrAuthorityPrivileges = errors.New("gateway_control_reader_privileges_invalid")
ErrIsolation = errors.New("gateway_exclusive_writer_evidence_unverified")
ErrRejected = errors.New("gateway_create_rejected_existing_object")
)
@@ -60,7 +59,6 @@ type Backend interface {
Put(context.Context, string, []byte, string) (Version, error)
Delete(context.Context, string, Version) error
}
type IsolationVerifier interface{ Verify(context.Context) error }
func Digest(b []byte) string { s := sha256.Sum256(b); return hex.EncodeToString(s[:]) }
func validHash(s string) bool {
@@ -0,0 +1,114 @@
package objectgateway_test
import (
"bytes"
"net"
"os"
"testing"
"github.com/aws/aws-sdk-go-v2/aws"
"github.com/aws/aws-sdk-go-v2/service/s3"
g "knowledge-governance/internal/objectgateway"
)
// A maintenance update of the target KB runs while the same bucket still
// serves other writers. Publishing planned objects must neither require a
// whole-bucket exclusivity attestation nor disturb an unrelated key or a
// pre-existing object at a planned key. External writes here are made before
// execute (coexistence), not interleaved concurrently with the PUT.
func TestGatewaySharedBucketCoexistenceWithOtherWriters(t *testing.T) {
ctx, pool, backend := fixture(t)
endpoint := os.Getenv("KG_GATEWAY_TEST_ENDPOINT")
scope := g.Digest([]byte("minio\x00" + endpoint + "\x00" + backend.Bucket))
listener, e := net.Listen("tcp", "127.0.0.1:0")
if e != nil {
t.Fatal(e)
}
addr := listener.Addr().String()
listener.Close()
data, control := g.Digest([]byte("data "+scope)), g.Digest([]byte("control "+scope))
client, e := g.NewClient("http://"+addr, data, scope)
if e != nil {
t.Fatal(e)
}
admin, _ := g.NewClient("http://"+addr, control, scope)
// Deliberately no OBJECT_GATEWAY_AUDIT_FILE / OBJECT_GATEWAY_AUDIT_PUBLIC_KEY:
// the default shared-bucket path must start without whole-bucket evidence.
env := []string{
"PATH=" + os.Getenv("PATH"),
"HOME=" + os.Getenv("HOME"),
"OBJECT_GATEWAY_LISTEN=" + addr,
"OBJECT_GATEWAY_DATABASE_URL=" + os.Getenv("KG_GATEWAY_TEST_DATABASE_URL"),
"OBJECT_GATEWAY_PROVIDER=minio",
"OBJECT_GATEWAY_ENDPOINT=" + endpoint,
"OBJECT_GATEWAY_BUCKET=" + backend.Bucket,
"OBJECT_GATEWAY_REGION=us-east-1",
"OBJECT_GATEWAY_ACCESS_KEY=" + os.Getenv("KG_GATEWAY_TEST_ACCESS_KEY"),
"OBJECT_GATEWAY_SECRET_KEY=" + os.Getenv("KG_GATEWAY_TEST_SECRET_KEY"),
"OBJECT_GATEWAY_DATA_TOKEN=" + data,
"OBJECT_GATEWAY_CONTROL_TOKEN=" + control,
}
startGateway(t, env, client)
if e = client.ReadyForAcquisition(ctx); e == nil {
t.Fatal("gateway without control authority advertised automatic grants")
}
// Another service keeps writing unrelated keys during the maintenance window.
externalOwner := g.Digest([]byte("other-service"))
unrelatedKey := "other-service/unrelated-" + g.Digest([]byte(backend.Bucket))[:8]
unrelatedBody := []byte("unrelated service body")
if _, e = backend.Client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(backend.Bucket), Key: aws.String(unrelatedKey), Body: bytes.NewReader(unrelatedBody), Metadata: map[string]string{"kg-release-owner": externalOwner}}); e != nil {
t.Fatalf("external unrelated write failed: %v", e)
}
unrelated, _, e := backend.Observe(ctx, unrelatedKey, "")
if e != nil {
t.Fatal(e)
}
// A planned key already holds a foreign object: the plan must refuse it and
// leave that object byte-identical.
existingKey := "unchanged/existing-object"
existingBody := []byte("pre-existing production content")
if _, e = backend.Client.PutObject(ctx, &s3.PutObjectInput{Bucket: aws.String(backend.Bucket), Key: aws.String(existingKey), Body: bytes.NewReader(existingBody), Metadata: map[string]string{"kg-release-owner": externalOwner}}); e != nil {
t.Fatal(e)
}
existing, _, e := backend.Observe(ctx, existingKey, "")
if e != nil {
t.Fatal(e)
}
grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte("maintenance-owner")), Plan: g.Digest([]byte("maintenance-plan"))}
fresh := request("shared-fresh", grant)
clash := request("shared-clash", grant)
clash.Key = existingKey
if e = admin.InstallPlan(ctx, planFor(grant, fresh, clash)); e != nil {
t.Fatal(e)
}
if e = admin.Advance(ctx, 0, grant); e != nil {
t.Fatal(e)
}
receipt, e := client.Execute(ctx, fresh, []byte("gateway fixture shared-fresh"))
if e != nil || receipt.State != "committed" {
t.Fatalf("planned create blocked by unrelated writers: %v %s", e, receipt.State)
}
rejected, e := client.Execute(ctx, clash, []byte("gateway fixture shared-clash"))
if e != nil || rejected.State != "rejected" {
t.Fatalf("pre-existing planned key not rejected: %v %s", e, rejected.State)
}
after, exists, e := backend.Observe(ctx, existingKey, "")
if e != nil || !exists || after.ID != existing.ID || after.SHA256 != g.Digest(existingBody) {
t.Fatalf("pre-existing object modified: %v %+v", e, after)
}
still, exists, e := backend.Observe(ctx, unrelatedKey, "")
if e != nil || !exists || still.ID != unrelated.ID {
t.Fatalf("unrelated object disturbed: %v %+v", e, still)
}
// Precise rollback removes only the version this gateway created.
cleanup(t, ctx, &g.Gateway{Pool: pool, Scope: scope, Backend: backend, MaxBytes: 1 << 20}, receipt)
for key, keep := range map[string]g.Version{existingKey: existing, unrelatedKey: unrelated} {
if e = backend.Delete(ctx, key, keep); e != nil {
t.Fatalf("external fixture cleanup %s: %v", key, e)
}
}
}
@@ -13,7 +13,7 @@ import (
func TestGatewayNewEpochPreservesOriginalSendIdentity(t *testing.T) {
ctx, pool, backend := fixture(t)
gateway := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
gateway := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, MaxBytes: 1 << 20}
first := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("takeover-plan"))}
sent, unsent := request("takeover-sent", first), request("takeover-unsent", first)
if e := gateway.InstallPlan(ctx, planFor(first, sent, unsent)); e != nil {
@@ -22,7 +22,7 @@ func TestGatewayAbsenceNeverSettlesUnknown(t *testing.T) {
ctx, pool, real := fixture(t)
backend := &stoppedBeforeSend{Backend: real}
grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte(t.Name())), Plan: g.Digest([]byte("plan"))}
gateway := &g.Gateway{Pool: pool, Scope: real.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
gateway := &g.Gateway{Pool: pool, Scope: real.Bucket, Backend: backend, MaxBytes: 1 << 20}
if e := gateway.InstallPlan(ctx, planFor(grant, request(t.Name(), grant))); e != nil {
t.Fatal(e)
}
@@ -62,7 +62,7 @@ func TestGatewayReadOnlyPersistenceBlocksSend(t *testing.T) {
t.Fatal(e)
}
defer other.Close()
gateway := &g.Gateway{Pool: other, Scope: backend.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
gateway := &g.Gateway{Pool: other, Scope: backend.Bucket, Backend: backend, MaxBytes: 1 << 20}
if e = gateway.Ready(ctx); !errors.Is(e, g.ErrPersistence) {
t.Fatal("read-only persistence accepted", e)
}