feat(object-gateway): 统一对象写网关与不可变治理日志
方案A:所有对象写入经 loopback 网关,持久计划/grant/intent/逐版本 receipt 与 attempt→grant delivery 落在治理 PG;scope 由 provider+endpoint+bucket 决定, 同一物理桶只允许一个写域。版本 append 不等于 CAS,未锚定计划在首笔业务写前拒绝。 本提交只含网关与其适配层接线、协议文档;生产独占、凭据切换与桶设置未改动。
This commit is contained in:
@@ -0,0 +1,159 @@
|
||||
package objectgateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5"
|
||||
"math"
|
||||
)
|
||||
|
||||
// Claim names an already persisted application attempt and write-set anchor.
|
||||
// It never carries keys, bodies, a replacement plan or a chosen gateway epoch.
|
||||
type Claim struct {
|
||||
JobID string `json:"job_id"`
|
||||
OperationID string `json:"operation_id"`
|
||||
AttemptEpoch int64 `json:"attempt_epoch"`
|
||||
Owner string `json:"owner"`
|
||||
PlanDigest string `json:"plan_digest"`
|
||||
RecoveryJobID string `json:"recovery_job_id,omitempty"`
|
||||
RecoveryOperationID string `json:"recovery_operation_id,omitempty"`
|
||||
}
|
||||
type PlanAuthority interface {
|
||||
Load(context.Context, Claim) (Plan, error)
|
||||
}
|
||||
|
||||
func (g *Gateway) Acquire(ctx context.Context, c Claim) (Grant, error) {
|
||||
if g.Authority == nil {
|
||||
return Grant{}, ErrAuthority
|
||||
}
|
||||
if c.JobID == "" || c.OperationID == "" || c.Owner == "" || c.AttemptEpoch < 1 || !validHash(c.PlanDigest) {
|
||||
return Grant{}, ErrEpoch
|
||||
}
|
||||
if e := g.Ready(ctx); e != nil {
|
||||
return Grant{}, e
|
||||
}
|
||||
plan, e := g.Authority.Load(ctx, c)
|
||||
if e != nil {
|
||||
return Grant{}, e
|
||||
}
|
||||
if plan.Digest != c.PlanDigest || plan.Owner != Digest([]byte(c.JobID)) {
|
||||
return Grant{}, ErrConflict
|
||||
}
|
||||
if e = g.InstallPlan(ctx, plan); e != nil {
|
||||
return Grant{}, e
|
||||
}
|
||||
// Recover only sends in this exact frozen plan. No absent observation can
|
||||
// settle an unknown send; the locked advancement below still checks all intents.
|
||||
rows, e := g.Pool.Query(ctx, `SELECT i.request FROM kg_object_gateway_intents i
|
||||
LEFT JOIN kg_object_gateway_receipts r ON r.scope=i.scope AND r.operation=i.operation
|
||||
WHERE i.scope=$1 AND r.operation IS NULL`, g.Scope)
|
||||
if e != nil {
|
||||
return Grant{}, ErrPersistence
|
||||
}
|
||||
var pending []Request
|
||||
for rows.Next() {
|
||||
var raw []byte
|
||||
var request Request
|
||||
if rows.Scan(&raw) != nil || json.Unmarshal(raw, &request) != nil {
|
||||
rows.Close()
|
||||
return Grant{}, ErrPersistence
|
||||
}
|
||||
if request.Grant.Plan == plan.Digest {
|
||||
pending = append(pending, request)
|
||||
}
|
||||
}
|
||||
e = rows.Err()
|
||||
rows.Close()
|
||||
if e != nil {
|
||||
return Grant{}, ErrPersistence
|
||||
}
|
||||
for _, request := range pending {
|
||||
if request.Grant.Owner != plan.Owner {
|
||||
return Grant{}, ErrConflict
|
||||
}
|
||||
if _, e = g.Reconcile(ctx, request); e != nil {
|
||||
return Grant{}, e
|
||||
}
|
||||
}
|
||||
tx, e := g.Pool.Begin(ctx)
|
||||
if e != nil {
|
||||
return Grant{}, ErrPersistence
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
if _, e = tx.Exec(ctx, "INSERT INTO kg_object_gateway_scopes(scope) VALUES($1) ON CONFLICT DO NOTHING", g.Scope); e != nil {
|
||||
return Grant{}, ErrPersistence
|
||||
}
|
||||
var epoch int64
|
||||
if e = tx.QueryRow(ctx, "SELECT epoch FROM kg_object_gateway_scopes WHERE scope=$1 FOR UPDATE", g.Scope).Scan(&epoch); e != nil {
|
||||
return Grant{}, ErrPersistence
|
||||
}
|
||||
// Recheck after serialization. This is admission evidence, not an OSS fence:
|
||||
// a persisted uncertain object intent still prevents every epoch transition.
|
||||
verified, e := g.Authority.Load(ctx, c)
|
||||
if e != nil {
|
||||
return Grant{}, e
|
||||
}
|
||||
frozen, _ := json.Marshal(plan)
|
||||
again, _ := json.Marshal(verified)
|
||||
if !bytes.Equal(frozen, again) {
|
||||
return Grant{}, ErrConflict
|
||||
}
|
||||
raw, _ := json.Marshal(c)
|
||||
var oldClaim, oldGrant []byte
|
||||
e = tx.QueryRow(ctx, "SELECT claim,grant_body FROM kg_object_gateway_deliveries WHERE scope=$1 AND job=$2 AND attempt_epoch=$3", g.Scope, c.JobID, c.AttemptEpoch).Scan(&oldClaim, &oldGrant)
|
||||
if e == nil {
|
||||
var grant Grant
|
||||
if !bytes.Equal(raw, oldClaim) || json.Unmarshal(oldGrant, &grant) != nil || !grant.valid() {
|
||||
return Grant{}, ErrConflict
|
||||
}
|
||||
if grant.Epoch != epoch {
|
||||
return Grant{}, ErrEpoch
|
||||
}
|
||||
return grant, nil
|
||||
}
|
||||
if !errors.Is(e, pgx.ErrNoRows) {
|
||||
return Grant{}, ErrPersistence
|
||||
}
|
||||
var firstRaw []byte
|
||||
firstErr := tx.QueryRow(ctx, "SELECT claim FROM kg_object_gateway_deliveries WHERE scope=$1 AND job=$2 ORDER BY attempt_epoch LIMIT 1", g.Scope, c.JobID).Scan(&firstRaw)
|
||||
if firstErr == nil {
|
||||
var first Claim
|
||||
if json.Unmarshal(firstRaw, &first) != nil {
|
||||
return Grant{}, ErrPersistence
|
||||
}
|
||||
if first.JobID != c.JobID || first.OperationID != c.OperationID || first.PlanDigest != c.PlanDigest {
|
||||
return Grant{}, ErrConflict
|
||||
}
|
||||
} else if !errors.Is(firstErr, pgx.ErrNoRows) {
|
||||
return Grant{}, ErrPersistence
|
||||
}
|
||||
var stale bool
|
||||
if tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM kg_object_gateway_deliveries WHERE scope=$1 AND job=$2 AND attempt_epoch>=$3)", g.Scope, c.JobID, c.AttemptEpoch).Scan(&stale) != nil {
|
||||
return Grant{}, ErrPersistence
|
||||
}
|
||||
if stale || epoch == math.MaxInt64 {
|
||||
return Grant{}, ErrEpoch
|
||||
}
|
||||
next := Grant{Epoch: epoch + 1, Owner: plan.Owner, Plan: plan.Digest}
|
||||
if e = g.advanceLocked(ctx, tx, epoch, next); e != nil {
|
||||
return Grant{}, e
|
||||
}
|
||||
grantRaw, _ := json.Marshal(next)
|
||||
if _, e = tx.Exec(ctx, "INSERT INTO kg_object_gateway_deliveries(scope,job,attempt_epoch,claim,grant_epoch,grant_body) VALUES($1,$2,$3,$4,$5,$6)", g.Scope, c.JobID, c.AttemptEpoch, raw, next.Epoch, grantRaw); e != nil {
|
||||
return Grant{}, ErrPersistence
|
||||
}
|
||||
if tx.Commit(ctx) != nil {
|
||||
return Grant{}, ErrPersistence
|
||||
}
|
||||
return next, nil
|
||||
}
|
||||
func (c *Client) Acquire(ctx context.Context, claim Claim) (Grant, error) {
|
||||
var out Grant
|
||||
e := c.call(ctx, "/v1/acquire", claim, &out)
|
||||
if e == nil && (!out.valid() || out.Plan != claim.PlanDigest || out.Owner != Digest([]byte(claim.JobID))) {
|
||||
e = ErrConflict
|
||||
}
|
||||
return out, e
|
||||
}
|
||||
@@ -0,0 +1,122 @@
|
||||
package objectgateway_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
g "knowledge-governance/internal/objectgateway"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type currentPlanAuthority struct {
|
||||
claim g.Claim
|
||||
plan g.Plan
|
||||
}
|
||||
|
||||
func (a *currentPlanAuthority) Load(_ context.Context, c g.Claim) (g.Plan, error) {
|
||||
if c != a.claim {
|
||||
return g.Plan{}, g.ErrEpoch
|
||||
}
|
||||
return a.plan, nil
|
||||
}
|
||||
func TestGatewayAcquisitionPersistsAttemptDelivery(t *testing.T) {
|
||||
ctx, pool, backend := fixture(t)
|
||||
claim := g.Claim{JobID: "job-acquire", OperationID: "operation-acquire", AttemptEpoch: 1, Owner: "worker-1", PlanDigest: g.Digest([]byte(t.Name()))}
|
||||
expected := g.Grant{Epoch: 1, Owner: g.Digest([]byte(claim.JobID)), Plan: claim.PlanDigest}
|
||||
req := request("acquired-object", expected)
|
||||
authority := ¤tPlanAuthority{claim, planFor(expected, req)}
|
||||
gateway := &g.Gateway{Pool: pool, Scope: backend.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20, Authority: authority}
|
||||
grant, e := gateway.Acquire(ctx, claim)
|
||||
if e != nil || grant != expected {
|
||||
t.Fatal("anchored active attempt grant unavailable", e)
|
||||
}
|
||||
replay, e := gateway.Acquire(ctx, claim)
|
||||
if e != nil || replay != grant {
|
||||
t.Fatal("grant delivery replay changed epoch", e)
|
||||
}
|
||||
oldClaim := claim
|
||||
claim.AttemptEpoch = 2
|
||||
claim.Owner = "worker-2"
|
||||
authority.claim = claim
|
||||
next, e := gateway.Acquire(ctx, claim)
|
||||
if e != nil || next.Epoch != 2 {
|
||||
t.Fatal("next active attempt", e)
|
||||
}
|
||||
if _, e = gateway.Acquire(ctx, oldClaim); !errors.Is(e, g.ErrEpoch) {
|
||||
t.Fatal("stale attempt acquired grant", e)
|
||||
}
|
||||
replacement := claim
|
||||
replacement.AttemptEpoch++
|
||||
replacement.PlanDigest = g.Digest([]byte("replacement-plan"))
|
||||
authority.claim = replacement
|
||||
authority.plan.Digest = replacement.PlanDigest
|
||||
if _, e = gateway.Acquire(ctx, replacement); !errors.Is(e, g.ErrConflict) {
|
||||
t.Fatal("new attempt replaced original plan", e)
|
||||
}
|
||||
authority.claim = claim
|
||||
authority.plan.Digest = claim.PlanDigest
|
||||
req.Grant = next
|
||||
receipt, e := gateway.ExecuteAuthorized(ctx, next, req, []byte("gateway fixture acquired-object"))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
cleanup(t, ctx, gateway, receipt)
|
||||
var count int
|
||||
if e = pool.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_deliveries WHERE scope=$1", gateway.Scope).Scan(&count); e != nil || count != 2 {
|
||||
t.Fatal("immutable delivery count", count, e)
|
||||
}
|
||||
for _, statement := range []string{"UPDATE kg_object_gateway_deliveries SET job=job", "DELETE FROM kg_object_gateway_deliveries", "TRUNCATE kg_object_gateway_deliveries"} {
|
||||
if _, e = pool.Exec(ctx, statement); e == nil {
|
||||
t.Fatal("mutable grant delivery", statement)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestGatewayAcquisitionCannotHandOverUnknownSend(t *testing.T) {
|
||||
ctx, pool, real := fixture(t)
|
||||
backend := &stoppedBeforeSend{Backend: real}
|
||||
claim := g.Claim{JobID: "job-held", OperationID: "operation-held", AttemptEpoch: 1, Owner: "worker-first", PlanDigest: g.Digest([]byte(t.Name()))}
|
||||
expected := g.Grant{Epoch: 1, Owner: g.Digest([]byte(claim.JobID)), Plan: claim.PlanDigest}
|
||||
req := request("acquire-held", expected)
|
||||
body := []byte("gateway fixture acquire-held")
|
||||
authority := ¤tPlanAuthority{claim, planFor(expected, req)}
|
||||
gateway := &g.Gateway{Pool: pool, Scope: real.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20, Authority: authority}
|
||||
if _, e := gateway.Acquire(ctx, claim); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if _, e := gateway.ExecuteAuthorized(ctx, expected, req, body); !errors.Is(e, g.ErrHeld) {
|
||||
t.Fatal(e)
|
||||
}
|
||||
claim.AttemptEpoch++
|
||||
claim.Owner = "worker-next"
|
||||
authority.claim = claim
|
||||
for i := 0; i < 2; i++ {
|
||||
if _, e := gateway.Acquire(ctx, claim); !errors.Is(e, g.ErrHeld) {
|
||||
t.Fatal("absent send handed over", e)
|
||||
}
|
||||
}
|
||||
if backend.calls != 1 {
|
||||
t.Fatal("control acquisition re-sent PUT")
|
||||
}
|
||||
var count int
|
||||
if e := pool.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_deliveries WHERE scope=$1", gateway.Scope).Scan(&count); e != nil || count != 1 {
|
||||
t.Fatal("unknown send advanced delivery", count, e)
|
||||
}
|
||||
// Deliver the previously uncertain request late, using its exact immutable claim.
|
||||
if _, e := real.Put(ctx, req.Key, body, req.Claim()); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
next, e := gateway.Acquire(ctx, claim)
|
||||
if e != nil || next.Epoch != 2 {
|
||||
t.Fatal("committed send was not reconciled before handover", e)
|
||||
}
|
||||
receipt, e := gateway.ExecuteAuthorized(ctx, next, req, body)
|
||||
if e != nil || receipt.Request != req {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if backend.calls != 1 {
|
||||
t.Fatal("reconciled send was retried")
|
||||
}
|
||||
receipt.Request.Grant = next
|
||||
cleanup(t, ctx, gateway, receipt)
|
||||
t.Log("new controller attempt stayed held while absent; late committed original recovered without replay PUT")
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
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
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
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")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package objectgateway
|
||||
|
||||
import "context"
|
||||
|
||||
type claimContextKey struct{}
|
||||
|
||||
// WithClaim is set by the owned-attempt runner, never from an HTTP caller's
|
||||
// proposed plan. The controller independently checks every field against PG.
|
||||
func WithClaim(ctx context.Context, c Claim) context.Context {
|
||||
return context.WithValue(ctx, claimContextKey{}, c)
|
||||
}
|
||||
func ClaimFromContext(ctx context.Context) Claim {
|
||||
c, _ := ctx.Value(claimContextKey{}).(Claim)
|
||||
return c
|
||||
}
|
||||
@@ -0,0 +1,326 @@
|
||||
package objectgateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
_ "embed"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// Schema is applied explicitly by the migration identity, never on server startup.
|
||||
//
|
||||
//go:embed schema.sql
|
||||
var Schema string
|
||||
|
||||
type Gateway struct {
|
||||
Authority PlanAuthority
|
||||
Pool *pgxpool.Pool
|
||||
Scope string
|
||||
Backend Backend
|
||||
Isolation IsolationVerifier
|
||||
MaxBytes int64
|
||||
}
|
||||
|
||||
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
|
||||
}
|
||||
var journal bool
|
||||
if g.Pool.QueryRow(ctx, `SELECT NOT pg_is_in_recovery() AND current_setting('transaction_read_only')='off'
|
||||
AND to_regclass('kg_object_gateway_plans') IS NOT NULL
|
||||
AND to_regclass('kg_object_gateway_scopes') IS NOT NULL
|
||||
AND to_regclass('kg_object_gateway_grants') IS NOT NULL
|
||||
AND to_regclass('kg_object_gateway_intents') IS NOT NULL
|
||||
AND to_regclass('kg_object_gateway_receipts') IS NOT NULL
|
||||
AND to_regclass('kg_object_gateway_deliveries') IS NOT NULL
|
||||
AND (SELECT count(*)=10 FROM pg_trigger WHERE tgname IN ('kg_object_gateway_deliveries_immutable','kg_object_gateway_deliveries_no_truncate','kg_object_gateway_plans_no_truncate','kg_object_gateway_intents_no_truncate','kg_object_gateway_receipts_no_truncate','kg_object_gateway_grants_no_truncate','kg_object_gateway_plans_immutable','kg_object_gateway_intents_immutable','kg_object_gateway_receipts_immutable','kg_object_gateway_grants_immutable') AND tgenabled='O')`).Scan(&journal) != nil || !journal {
|
||||
return ErrPersistence
|
||||
}
|
||||
if g.Backend.Ready(ctx) != nil {
|
||||
return errors.New("gateway_backend_not_ready")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (g *Gateway) Advance(ctx context.Context, expected int64, next Grant) error {
|
||||
if !next.valid() || next.Epoch != expected+1 {
|
||||
return ErrEpoch
|
||||
}
|
||||
if err := g.Ready(ctx); err != nil {
|
||||
return err
|
||||
}
|
||||
var frozen []byte
|
||||
var plan Plan
|
||||
if g.Pool.QueryRow(ctx, "SELECT body FROM kg_object_gateway_plans WHERE scope=$1 AND plan=$2", g.Scope, next.Plan).Scan(&frozen) != nil {
|
||||
return ErrConflict
|
||||
}
|
||||
if json.Unmarshal(frozen, &plan) != nil || !plan.valid() || plan.Owner != next.Owner {
|
||||
return ErrConflict
|
||||
}
|
||||
tx, err := g.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return ErrPersistence
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
if _, err = tx.Exec(ctx, "INSERT INTO kg_object_gateway_scopes(scope) VALUES($1) ON CONFLICT DO NOTHING", g.Scope); err != nil {
|
||||
return ErrPersistence
|
||||
}
|
||||
var epoch int64
|
||||
if tx.QueryRow(ctx, "SELECT epoch FROM kg_object_gateway_scopes WHERE scope=$1 FOR UPDATE", g.Scope).Scan(&epoch) != nil {
|
||||
return ErrPersistence
|
||||
}
|
||||
if err = g.advanceLocked(ctx, tx, epoch, next); err != nil {
|
||||
return err
|
||||
}
|
||||
if tx.Commit(ctx) != nil {
|
||||
return ErrPersistence
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func (g *Gateway) advanceLocked(ctx context.Context, tx pgx.Tx, epoch int64, next Grant) error {
|
||||
var err error
|
||||
if epoch == next.Epoch {
|
||||
var owner, plan string
|
||||
if tx.QueryRow(ctx, "SELECT owner,plan FROM kg_object_gateway_grants WHERE scope=$1 AND epoch=$2", g.Scope, epoch).Scan(&owner, &plan) != nil {
|
||||
return ErrPersistence
|
||||
}
|
||||
if owner != next.Owner || plan != next.Plan {
|
||||
return ErrEpoch
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if epoch != next.Epoch-1 {
|
||||
return ErrEpoch
|
||||
}
|
||||
var pending bool
|
||||
if tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM kg_object_gateway_intents i WHERE i.scope=$1 AND NOT EXISTS(SELECT 1 FROM kg_object_gateway_receipts r WHERE r.scope=i.scope AND r.operation=i.operation))`, g.Scope).Scan(&pending) != nil {
|
||||
return ErrPersistence
|
||||
}
|
||||
if pending {
|
||||
return ErrHeld
|
||||
}
|
||||
if _, err = tx.Exec(ctx, "INSERT INTO kg_object_gateway_grants(scope,epoch,owner,plan) VALUES($1,$2,$3,$4)", g.Scope, next.Epoch, next.Owner, next.Plan); err != nil {
|
||||
return ErrPersistence
|
||||
}
|
||||
if _, err = tx.Exec(ctx, "UPDATE kg_object_gateway_scopes SET epoch=$2 WHERE scope=$1", g.Scope, next.Epoch); err != nil {
|
||||
return ErrPersistence
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// reserve commits an immutable may-send intent. Even a commit timeout cannot be
|
||||
// followed by a send. Another process can reconcile, but cannot retry this PUT.
|
||||
func (g *Gateway) reserve(ctx context.Context, r Request, authorization *Grant) (bool, error) {
|
||||
tx, err := g.Pool.Begin(ctx)
|
||||
if err != nil {
|
||||
return false, ErrPersistence
|
||||
}
|
||||
defer tx.Rollback(ctx)
|
||||
var epoch int64
|
||||
if tx.QueryRow(ctx, "SELECT epoch FROM kg_object_gateway_scopes WHERE scope=$1 FOR UPDATE", g.Scope).Scan(&epoch) != nil {
|
||||
return false, ErrEpoch
|
||||
}
|
||||
if authorization != nil {
|
||||
var owner, plan string
|
||||
if epoch != authorization.Epoch {
|
||||
return false, ErrEpoch
|
||||
}
|
||||
if tx.QueryRow(ctx, "SELECT owner,plan FROM kg_object_gateway_grants WHERE scope=$1 AND epoch=$2", g.Scope, epoch).Scan(&owner, &plan) != nil {
|
||||
return false, ErrPersistence
|
||||
}
|
||||
if owner != authorization.Owner || plan != authorization.Plan {
|
||||
return false, ErrEpoch
|
||||
}
|
||||
}
|
||||
raw, _ := json.Marshal(r)
|
||||
var previous []byte
|
||||
err = tx.QueryRow(ctx, "SELECT request FROM kg_object_gateway_intents WHERE scope=$1 AND operation=$2", g.Scope, r.Operation).Scan(&previous)
|
||||
if err == nil {
|
||||
if string(previous) != string(raw) {
|
||||
return false, ErrConflict
|
||||
}
|
||||
return false, nil
|
||||
}
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return false, ErrPersistence
|
||||
}
|
||||
var owner, plan string
|
||||
if epoch != r.Grant.Epoch {
|
||||
return false, ErrEpoch
|
||||
}
|
||||
if tx.QueryRow(ctx, "SELECT owner,plan FROM kg_object_gateway_grants WHERE scope=$1 AND epoch=$2", g.Scope, epoch).Scan(&owner, &plan) != nil {
|
||||
return false, ErrPersistence
|
||||
}
|
||||
if owner != r.Grant.Owner || plan != r.Grant.Plan {
|
||||
return false, ErrEpoch
|
||||
}
|
||||
var pending bool
|
||||
if tx.QueryRow(ctx, `SELECT EXISTS(SELECT 1 FROM kg_object_gateway_intents i WHERE i.scope=$1 AND i.key=$2 AND NOT EXISTS(SELECT 1 FROM kg_object_gateway_receipts x WHERE x.scope=i.scope AND x.operation=i.operation))`, g.Scope, r.Key).Scan(&pending) != nil {
|
||||
return false, ErrPersistence
|
||||
}
|
||||
if pending {
|
||||
return false, ErrHeld
|
||||
}
|
||||
var frozen []byte
|
||||
var allowed Plan
|
||||
if tx.QueryRow(ctx, "SELECT body FROM kg_object_gateway_plans WHERE scope=$1 AND plan=$2", g.Scope, r.Grant.Plan).Scan(&frozen) != nil {
|
||||
return false, ErrPersistence
|
||||
}
|
||||
if json.Unmarshal(frozen, &allowed) != nil || !allowed.valid() || !allowed.allows(r) {
|
||||
return false, ErrConflict
|
||||
}
|
||||
if r.Action == "delete" {
|
||||
previous, err := g.receipt(ctx, r.CreatedBy)
|
||||
if err != nil || previous.State != "committed" || previous.Request.Key != r.Key || previous.Version != r.Version {
|
||||
return false, ErrConflict
|
||||
}
|
||||
}
|
||||
if _, err = tx.Exec(ctx, "INSERT INTO kg_object_gateway_intents(scope,operation,key,request) VALUES($1,$2,$3,$4)", g.Scope, r.Operation, r.Key, raw); err != nil {
|
||||
return false, ErrPersistence
|
||||
}
|
||||
if tx.Commit(ctx) != nil {
|
||||
return false, ErrPersistence
|
||||
}
|
||||
return true, nil
|
||||
}
|
||||
func (g *Gateway) receipt(ctx context.Context, id string) (Receipt, error) {
|
||||
var raw []byte
|
||||
var r Receipt
|
||||
err := g.Pool.QueryRow(ctx, "SELECT receipt FROM kg_object_gateway_receipts WHERE scope=$1 AND operation=$2", g.Scope, id).Scan(&raw)
|
||||
if err != nil {
|
||||
return r, err
|
||||
}
|
||||
if json.Unmarshal(raw, &r) != nil {
|
||||
return r, ErrPersistence
|
||||
}
|
||||
return r, nil
|
||||
}
|
||||
func (g *Gateway) finish(ctx context.Context, r Request, state string, v Version) (Receipt, error) {
|
||||
receipt := Receipt{r, state, v}
|
||||
raw, _ := json.Marshal(receipt)
|
||||
_, err := g.Pool.Exec(ctx, "INSERT INTO kg_object_gateway_receipts(scope,operation,receipt) VALUES($1,$2,$3) ON CONFLICT DO NOTHING", g.Scope, r.Operation, raw)
|
||||
if err != nil {
|
||||
return Receipt{}, ErrPersistence
|
||||
}
|
||||
got, err := g.receipt(ctx, r.Operation)
|
||||
if err != nil {
|
||||
return Receipt{}, ErrPersistence
|
||||
}
|
||||
if got != receipt {
|
||||
return Receipt{}, ErrConflict
|
||||
}
|
||||
return got, nil
|
||||
}
|
||||
func (g *Gateway) Execute(ctx context.Context, r Request, body []byte) (Receipt, error) {
|
||||
return g.execute(ctx, r, body, nil)
|
||||
}
|
||||
func (g *Gateway) execute(ctx context.Context, r Request, body []byte, authorization *Grant) (Receipt, error) {
|
||||
if err := r.validate(); err != nil {
|
||||
return Receipt{}, err
|
||||
}
|
||||
if r.Bytes > g.MaxBytes || r.Action == "create" && (int64(len(body)) != r.Bytes || Digest(body) != r.SHA256) || r.Action == "delete" && len(body) != 0 {
|
||||
return Receipt{}, ErrConflict
|
||||
}
|
||||
if err := g.Ready(ctx); err != nil {
|
||||
return Receipt{}, err
|
||||
}
|
||||
fresh, err := g.reserve(ctx, r, authorization)
|
||||
if err != nil {
|
||||
return Receipt{}, err
|
||||
}
|
||||
if !fresh {
|
||||
return g.Reconcile(ctx, r)
|
||||
}
|
||||
if r.Action == "create" {
|
||||
_, exists, err := g.Backend.Observe(ctx, r.Key, "")
|
||||
if err != nil {
|
||||
return Receipt{}, ErrHeld
|
||||
}
|
||||
if exists {
|
||||
return g.finish(ctx, r, "rejected", Version{})
|
||||
}
|
||||
v, err := g.Backend.Put(ctx, r.Key, body, r.token())
|
||||
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 g.finish(ctx, r, "committed", v)
|
||||
}
|
||||
v, exists, err := g.Backend.Observe(ctx, r.Key, r.Version.ID)
|
||||
if err != nil {
|
||||
return Receipt{}, ErrHeld
|
||||
}
|
||||
if exists && v != r.Version {
|
||||
return Receipt{}, ErrConflict
|
||||
}
|
||||
if exists {
|
||||
if g.Backend.Delete(ctx, r.Key, r.Version) != nil {
|
||||
return Receipt{}, ErrHeld
|
||||
}
|
||||
}
|
||||
return g.Reconcile(ctx, r)
|
||||
}
|
||||
func (g *Gateway) Reconcile(ctx context.Context, r Request) (Receipt, error) {
|
||||
if err := r.validate(); err != nil {
|
||||
return Receipt{}, err
|
||||
}
|
||||
if err := g.Ready(ctx); err != nil {
|
||||
return Receipt{}, err
|
||||
}
|
||||
var raw []byte
|
||||
if g.Pool.QueryRow(ctx, "SELECT request FROM kg_object_gateway_intents WHERE scope=$1 AND operation=$2", g.Scope, r.Operation).Scan(&raw) != nil {
|
||||
return Receipt{}, ErrConflict
|
||||
}
|
||||
want, _ := json.Marshal(r)
|
||||
if string(raw) != string(want) {
|
||||
return Receipt{}, ErrConflict
|
||||
}
|
||||
got, err := g.receipt(ctx, r.Operation)
|
||||
if err == nil {
|
||||
return got, nil
|
||||
}
|
||||
if !errors.Is(err, pgx.ErrNoRows) {
|
||||
return Receipt{}, ErrPersistence
|
||||
}
|
||||
if r.Action == "delete" {
|
||||
_, exists, err := g.Backend.Observe(ctx, r.Key, r.Version.ID)
|
||||
if err != nil || exists {
|
||||
return Receipt{}, ErrHeld
|
||||
}
|
||||
return g.finish(ctx, r, "removed", r.Version)
|
||||
}
|
||||
versions, err := g.Backend.List(ctx, r.Key)
|
||||
if err != nil {
|
||||
return Receipt{}, ErrHeld
|
||||
}
|
||||
var found []Version
|
||||
for _, v := range versions {
|
||||
if v.Owner == r.token() {
|
||||
if !r.matches(v) {
|
||||
return Receipt{}, ErrHeld
|
||||
}
|
||||
found = append(found, v)
|
||||
}
|
||||
}
|
||||
if len(found) != 1 {
|
||||
return Receipt{}, ErrHeld
|
||||
}
|
||||
exact, exists, err := g.Backend.Observe(ctx, r.Key, found[0].ID)
|
||||
if err != nil || !exists || exact != found[0] {
|
||||
return Receipt{}, ErrHeld
|
||||
}
|
||||
return g.finish(ctx, r, "committed", exact)
|
||||
}
|
||||
@@ -0,0 +1,399 @@
|
||||
package objectgateway_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/ed25519"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"fmt"
|
||||
"io"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/http/httputil"
|
||||
"net/url"
|
||||
"os"
|
||||
"os/exec"
|
||||
"path/filepath"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/credentials"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3/types"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
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")
|
||||
if dsn == "" {
|
||||
t.Skip("isolated gateway PG/MinIO opt-in required")
|
||||
}
|
||||
u, e := url.Parse(dsn)
|
||||
if e != nil || !strings.HasPrefix(strings.TrimPrefix(u.Path, "/"), "kg_library_test_gateway_") || u.Hostname() != "127.0.0.1" {
|
||||
t.Fatal("unsafe gateway test database")
|
||||
}
|
||||
ctx := context.Background()
|
||||
pool, e := pgxpool.New(ctx, dsn)
|
||||
if e != nil {
|
||||
t.Fatal("PG unavailable")
|
||||
}
|
||||
t.Cleanup(pool.Close)
|
||||
if _, e = pool.Exec(ctx, g.Schema); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
endpoint := os.Getenv("KG_GATEWAY_TEST_ENDPOINT")
|
||||
if endpoint != "http://127.0.0.1:19100" {
|
||||
t.Fatal("unsafe test MinIO endpoint")
|
||||
}
|
||||
bucket := "kg-library-test-gateway-" + g.Digest([]byte(t.Name() + time.Now().String()))[:16]
|
||||
client := s3.New(s3.Options{Region: "us-east-1", BaseEndpoint: aws.String(endpoint), UsePathStyle: true, Credentials: credentials.NewStaticCredentialsProvider(os.Getenv("KG_GATEWAY_TEST_ACCESS_KEY"), os.Getenv("KG_GATEWAY_TEST_SECRET_KEY"), "")})
|
||||
if _, e = client.CreateBucket(ctx, &s3.CreateBucketInput{Bucket: aws.String(bucket)}); e != nil {
|
||||
t.Fatal("create isolated bucket failed")
|
||||
}
|
||||
if _, e = client.PutBucketVersioning(ctx, &s3.PutBucketVersioningInput{Bucket: aws.String(bucket), VersioningConfiguration: &types.VersioningConfiguration{Status: types.BucketVersioningStatusEnabled}}); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
list, e := client.ListObjectVersions(ctx, &s3.ListObjectVersionsInput{Bucket: aws.String(bucket)})
|
||||
if e != nil {
|
||||
t.Error("residue list unavailable")
|
||||
return
|
||||
}
|
||||
if len(list.Versions) != 0 || len(list.DeleteMarkers) != 0 {
|
||||
t.Errorf("preserving residue bucket %s: versions=%d markers=%d", bucket, len(list.Versions), len(list.DeleteMarkers))
|
||||
return
|
||||
}
|
||||
if _, e = client.DeleteBucket(ctx, &s3.DeleteBucketInput{Bucket: aws.String(bucket)}); e != nil {
|
||||
t.Error("delete empty test bucket failed")
|
||||
}
|
||||
t.Logf("exact sandbox %s: versions=0 markers=0; empty bucket deleted", bucket)
|
||||
})
|
||||
return ctx, pool, &g.S3Backend{Client: client, Bucket: bucket, MaxBytes: 1 << 20}
|
||||
}
|
||||
func planFor(grant g.Grant, requests ...g.Request) g.Plan {
|
||||
p := g.Plan{Digest: grant.Plan, Owner: grant.Owner}
|
||||
for _, r := range requests {
|
||||
p.Objects = append(p.Objects, g.ObjectBinding{Operation: r.Operation, Key: r.Key, SHA256: r.SHA256, Bytes: r.Bytes})
|
||||
}
|
||||
return p
|
||||
}
|
||||
func request(label string, grant g.Grant) g.Request {
|
||||
body := []byte("gateway fixture " + label)
|
||||
return g.Request{Grant: grant, Operation: g.Digest([]byte(label)), Key: "unchanged/" + label, Action: "create", SHA256: g.Digest(body), Bytes: int64(len(body))}
|
||||
}
|
||||
func cleanup(t *testing.T, ctx context.Context, gw *g.Gateway, receipt g.Receipt) {
|
||||
t.Helper()
|
||||
r := receipt.Request
|
||||
r.Operation = g.Digest([]byte(r.Operation + "delete"))
|
||||
r.Action = "delete"
|
||||
r.CreatedBy = receipt.Request.Operation
|
||||
r.Version = receipt.Version
|
||||
if got, e := gw.Execute(ctx, r, nil); e != nil || got.State != "removed" {
|
||||
t.Fatalf("exact cleanup: %v %s", e, got.State)
|
||||
}
|
||||
}
|
||||
func TestGatewayReadinessRequiresJournal(t *testing.T) {
|
||||
ctx, pool, backend := fixture(t)
|
||||
// An isolated search_path lacks the journal while PG settings remain healthy.
|
||||
conn, e := pool.Acquire(ctx)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
conn.Release()
|
||||
cfg := pool.Config()
|
||||
cfg.ConnConfig.RuntimeParams["search_path"] = "pg_catalog"
|
||||
other, e := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer other.Close()
|
||||
gw := &g.Gateway{Pool: other, Scope: "missing-journal", Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
|
||||
if e := gw.Ready(ctx); !errors.Is(e, g.ErrPersistence) {
|
||||
t.Fatalf("missing durable journal accepted: %v", e)
|
||||
}
|
||||
}
|
||||
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}
|
||||
if _, exists, err := backend.Observe(ctx, "missing-key-probe", ""); err != nil || exists {
|
||||
t.Fatalf("initial authoritative absence unavailable: %v exists=%v", err, exists)
|
||||
}
|
||||
if e := gw.InstallPlan(ctx, planFor(grant, request(t.Name(), grant))); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e := gw.Advance(ctx, 0, grant); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
req := request(t.Name(), grant)
|
||||
body := []byte("gateway fixture " + t.Name())
|
||||
one, e := gw.Execute(ctx, req, body)
|
||||
if e != nil || one.State != "committed" {
|
||||
t.Fatalf("create %v %s", e, one.State)
|
||||
}
|
||||
two, e := gw.Execute(ctx, req, body)
|
||||
if e != nil || two != one {
|
||||
t.Fatal("replay changed receipt", e)
|
||||
}
|
||||
bad := req
|
||||
bad.Key += "-different"
|
||||
if _, e = gw.Execute(ctx, bad, body); !errors.Is(e, g.ErrConflict) {
|
||||
t.Fatal("operation rebound", e)
|
||||
}
|
||||
for _, table := range []string{"intents", "receipts", "grants", "plans"} {
|
||||
if _, e = pool.Exec(ctx, "DELETE FROM kg_object_gateway_"+table+" WHERE scope=$1", gw.Scope); e == nil {
|
||||
t.Fatal("immutable evidence deleted", table)
|
||||
}
|
||||
}
|
||||
for _, table := range []string{"plans", "intents", "receipts", "grants"} {
|
||||
tx, e := pool.Begin(ctx)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
_, e = tx.Exec(ctx, "TRUNCATE kg_object_gateway_"+table+" CASCADE")
|
||||
_ = tx.Rollback(ctx)
|
||||
if e == nil {
|
||||
cleanup(t, ctx, gw, one)
|
||||
t.Fatal("immutable evidence truncation accepted", table)
|
||||
}
|
||||
}
|
||||
cleanup(t, ctx, gw, one)
|
||||
next := grant
|
||||
next.Epoch = 2
|
||||
if e = gw.Advance(ctx, 1, next); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
late := request("late", grant)
|
||||
if _, e = gw.Execute(ctx, late, []byte("gateway fixture late")); !errors.Is(e, g.ErrEpoch) {
|
||||
t.Fatal("old epoch sent", e)
|
||||
}
|
||||
}
|
||||
|
||||
func signedAudit(t *testing.T, scope string) (string, string) {
|
||||
t.Helper()
|
||||
pub, priv, e := ed25519.GenerateKey(rand.Reader)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
// This is a test authority. It exercises verification, NOT production exclusivity.
|
||||
a := g.Attestation{Protocol: g.Protocol, Scope: scope, GatewayID: "isolated-fixture", IssuedAt: time.Now().Add(-time.Minute), ExpiresAt: time.Now().Add(30 * time.Minute), WriterInventory: g.Digest([]byte("fixture inventory")), PolicyEvidence: g.Digest([]byte("fixture policy")), DenialEvidence: g.Digest([]byte("fixture denial")), DrainEvidence: g.Digest([]byte("fixture drain"))}
|
||||
raw, _ := json.Marshal(a)
|
||||
signed, _ := json.Marshal(g.SignedAttestation{Payload: raw, Signature: ed25519.Sign(priv, raw)})
|
||||
path := filepath.Join(t.TempDir(), "audit.json")
|
||||
if os.WriteFile(path, signed, 0600) != nil {
|
||||
t.Fatal("audit write failed")
|
||||
}
|
||||
return path, base64.StdEncoding.EncodeToString(pub)
|
||||
}
|
||||
func startGateway(t *testing.T, env []string, client *g.Client) *exec.Cmd {
|
||||
t.Helper()
|
||||
binary := os.Getenv("KG_GATEWAY_TEST_BINARY")
|
||||
if binary == "" {
|
||||
t.Fatal("actual gateway binary is required")
|
||||
}
|
||||
cmd := exec.Command(binary)
|
||||
cmd.Env = env
|
||||
log, e := os.Create(filepath.Join(t.TempDir(), "service.log"))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
cmd.Stdout = log
|
||||
cmd.Stderr = log
|
||||
if e = cmd.Start(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
t.Cleanup(func() { _ = cmd.Process.Kill(); _ = cmd.Wait(); _ = log.Close() })
|
||||
for i := 0; i < 100; i++ {
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
|
||||
e = client.Ready(ctx)
|
||||
cancel()
|
||||
if e == nil {
|
||||
return cmd
|
||||
}
|
||||
time.Sleep(30 * time.Millisecond)
|
||||
}
|
||||
raw, _ := os.ReadFile(log.Name())
|
||||
t.Fatalf("actual gateway not ready: %s", raw)
|
||||
return nil
|
||||
}
|
||||
func TestGatewayActualServiceTwoInterruptions(t *testing.T) {
|
||||
ctx, pool, backend := fixture(t)
|
||||
upstream, _ := url.Parse(os.Getenv("KG_GATEWAY_TEST_ENDPOINT"))
|
||||
proxy := httputil.NewSingleHostReverseProxy(upstream)
|
||||
beforeSend := make(chan struct{}, 2)
|
||||
allowSend := make(chan struct{}, 2)
|
||||
committed := make(chan struct{}, 2)
|
||||
release := make(chan struct{}, 2)
|
||||
var puts atomic.Int32
|
||||
proxy.ModifyResponse = func(resp *http.Response) error {
|
||||
if resp.Request.Method == "PUT" && !strings.Contains(resp.Request.URL.RawQuery, "versioning") {
|
||||
puts.Add(1)
|
||||
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
|
||||
committed <- struct{}{}
|
||||
select {
|
||||
case <-release:
|
||||
case <-resp.Request.Context().Done():
|
||||
}
|
||||
return errors.New("injected lost response after actual MinIO commit")
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
proxy.ErrorHandler = func(w http.ResponseWriter, r *http.Request, e error) { http.Error(w, "injected_transport_loss", 502) }
|
||||
p := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.Method == "PUT" && !strings.Contains(r.URL.RawQuery, "versioning") {
|
||||
beforeSend <- struct{}{}
|
||||
select {
|
||||
case <-allowSend:
|
||||
case <-r.Context().Done():
|
||||
return
|
||||
}
|
||||
}
|
||||
proxy.ServeHTTP(w, r)
|
||||
}))
|
||||
defer p.Close()
|
||||
scope := g.Digest([]byte("minio\x00" + p.URL + "\x00" + backend.Bucket))
|
||||
audit, pub := signedAudit(t, scope)
|
||||
listener, e := net.Listen("tcp", "127.0.0.1:0")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
addr := listener.Addr().String()
|
||||
listener.Close()
|
||||
data := g.Digest([]byte("data " + scope))
|
||||
control := 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)
|
||||
env := append(os.Environ(), "OBJECT_GATEWAY_LISTEN="+addr, "OBJECT_GATEWAY_DATABASE_URL="+os.Getenv("KG_GATEWAY_TEST_DATABASE_URL"), "OBJECT_GATEWAY_PROVIDER=minio", "OBJECT_GATEWAY_ENDPOINT="+p.URL, "OBJECT_GATEWAY_BUCKET="+backend.Bucket, "OBJECT_GATEWAY_ACCESS_KEY="+os.Getenv("KG_GATEWAY_TEST_ACCESS_KEY"), "OBJECT_GATEWAY_SECRET_KEY="+os.Getenv("KG_GATEWAY_TEST_SECRET_KEY"), "OBJECT_GATEWAY_AUDIT_PUBLIC_KEY="+pub, "OBJECT_GATEWAY_AUDIT_FILE="+audit, "OBJECT_GATEWAY_ID=isolated-fixture", "OBJECT_GATEWAY_DATA_TOKEN="+data, "OBJECT_GATEWAY_CONTROL_TOKEN="+control)
|
||||
cmd := startGateway(t, env, client)
|
||||
grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte("actual-worker")), Plan: g.Digest([]byte("frozen-actual-plan"))}
|
||||
if e = client.InstallPlan(ctx, planFor(grant, request("actual-0", grant))); e == nil {
|
||||
t.Fatal("data client installed plan")
|
||||
}
|
||||
if e = admin.InstallPlan(ctx, planFor(grant, request("actual-0", grant), request("actual-1", grant))); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = admin.Advance(ctx, 0, grant); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e = client.Advance(ctx, 0, grant); e == nil {
|
||||
t.Fatal("data client acquired control authority")
|
||||
}
|
||||
for iteration := 0; iteration < 2; iteration++ {
|
||||
label := fmt.Sprintf("actual-%d", iteration)
|
||||
r := request(label, grant)
|
||||
body := []byte("gateway fixture " + label)
|
||||
done := make(chan error, 1)
|
||||
go func() { _, e := client.Execute(ctx, r, body); done <- e }()
|
||||
select {
|
||||
case <-beforeSend:
|
||||
case <-time.After(15 * time.Second):
|
||||
t.Fatal("gateway did not send to proxy")
|
||||
}
|
||||
if _, e = client.Reconcile(ctx, r); !errors.Is(e, g.ErrHeld) {
|
||||
t.Fatal("not-yet-visible PUT treated as terminal", e)
|
||||
}
|
||||
blockedNext := grant
|
||||
blockedNext.Epoch++
|
||||
if e = admin.Advance(ctx, grant.Epoch, blockedNext); !errors.Is(e, g.ErrHeld) {
|
||||
t.Fatal("epoch crossed delayed precommit request", e)
|
||||
}
|
||||
allowSend <- struct{}{}
|
||||
select {
|
||||
case <-committed:
|
||||
case <-time.After(15 * time.Second):
|
||||
t.Fatal("actual MinIO PUT did not commit")
|
||||
}
|
||||
next := grant
|
||||
next.Epoch++
|
||||
if e = admin.Advance(ctx, grant.Epoch, next); !errors.Is(e, g.ErrHeld) {
|
||||
t.Fatal("epoch crossed in-flight write", e)
|
||||
}
|
||||
sameKey := r
|
||||
sameKey.Operation = g.Digest([]byte(label + "other"))
|
||||
if _, e = client.Execute(ctx, sameKey, body); !errors.Is(e, g.ErrHeld) {
|
||||
t.Fatal("same-key competitor admitted", e)
|
||||
}
|
||||
if e = cmd.Process.Kill(); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
_ = cmd.Wait()
|
||||
release <- struct{}{}
|
||||
select {
|
||||
case <-done:
|
||||
case <-time.After(5 * time.Second):
|
||||
t.Fatal("dead gateway call did not end")
|
||||
}
|
||||
t.Logf("actual gateway SIGKILL %d after MinIO commit before receipt", iteration+1)
|
||||
cmd = startGateway(t, env, client)
|
||||
receipt, e := client.Reconcile(ctx, r)
|
||||
if e != nil || receipt.State != "committed" {
|
||||
t.Fatalf("restart reconcile %v %s", e, receipt.State)
|
||||
}
|
||||
repeated, e := client.Execute(ctx, r, body)
|
||||
if e != nil || receipt != repeated {
|
||||
t.Fatal("restart duplicate not idempotent", e)
|
||||
}
|
||||
del := r
|
||||
del.Action = "delete"
|
||||
del.CreatedBy = r.Operation
|
||||
del.Operation = g.Digest([]byte(label + "cleanup"))
|
||||
del.Version = receipt.Version
|
||||
cleaned, e := client.Execute(ctx, del, nil)
|
||||
if e != nil || cleaned.State != "removed" {
|
||||
t.Fatal("actual exact cleanup failed", e)
|
||||
}
|
||||
if e = admin.Advance(ctx, grant.Epoch, next); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
late := request(label+"late", grant)
|
||||
if _, e = client.Execute(ctx, late, []byte("gateway fixture "+label+"late")); !errors.Is(e, g.ErrEpoch) {
|
||||
t.Fatal("late stale epoch admitted", e)
|
||||
}
|
||||
grant = next
|
||||
}
|
||||
if puts.Load() != 2 {
|
||||
t.Fatalf("blind PUT replay count=%d", puts.Load())
|
||||
}
|
||||
var n int
|
||||
if pool.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_receipts WHERE scope=$1", scope).Scan(&n) != nil || n != 4 {
|
||||
t.Fatalf("durable receipts=%d", n)
|
||||
}
|
||||
_ = cmd.Process.Kill()
|
||||
_ = cmd.Wait()
|
||||
if e = client.Ready(ctx); e == nil {
|
||||
t.Fatal("unavailable gateway accepted")
|
||||
}
|
||||
t.Log("actual binary + HTTP + durable PG + MinIO: two kills/restarts, 2 PUTs, 4 receipts, exact cleanup")
|
||||
}
|
||||
|
||||
func TestGatewayClientRejectsBadProtocolAndLeaks(t *testing.T) {
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Query().Get("secret") != "" {
|
||||
t.Error("secret in URL")
|
||||
}
|
||||
_, _ = io.WriteString(w, `{"protocol":"other","scope":"scope","ready":true}`)
|
||||
}))
|
||||
defer server.Close()
|
||||
c, e := g.NewClient(server.URL, strings.Repeat("x", 32), "scope")
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if c.Ready(context.Background()) == nil {
|
||||
t.Fatal("wrong protocol accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,316 @@
|
||||
package objectgateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"crypto/subtle"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
type ExecuteRequest struct {
|
||||
Authorization *Grant `json:"authorization,omitempty"`
|
||||
Request Request `json:"request"`
|
||||
Body []byte `json:"body,omitempty"`
|
||||
}
|
||||
type AdvanceRequest struct {
|
||||
Expected int64 `json:"expected"`
|
||||
Grant Grant `json:"grant"`
|
||||
}
|
||||
type Capabilities struct {
|
||||
AutomaticGrants bool `json:"automatic_grants"`
|
||||
Protocol string `json:"protocol"`
|
||||
Scope string `json:"scope"`
|
||||
Ready bool `json:"ready"`
|
||||
}
|
||||
type HTTPServer struct {
|
||||
Gateway *Gateway
|
||||
DataToken, ControlToken string
|
||||
}
|
||||
|
||||
func (s HTTPServer) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
token := s.DataToken
|
||||
if r.URL.Path == "/v1/advance" || r.URL.Path == "/v1/plans" {
|
||||
token = s.ControlToken
|
||||
}
|
||||
if len(token) < 32 || s.DataToken == s.ControlToken || subtle.ConstantTimeCompare([]byte(r.Header.Get("Authorization")), []byte("Bearer "+token)) != 1 {
|
||||
http.Error(w, "gateway_unauthorized", 401)
|
||||
return
|
||||
}
|
||||
if r.Header.Get("X-KG-Gateway-Protocol") != Protocol || r.Header.Get("X-KG-Gateway-Scope") != s.Gateway.Scope {
|
||||
http.Error(w, "gateway_protocol_or_target_mismatch", 409)
|
||||
return
|
||||
}
|
||||
fail := func(e error) {
|
||||
code := 503
|
||||
if errors.Is(e, ErrEpoch) || errors.Is(e, ErrConflict) || errors.Is(e, ErrHeld) {
|
||||
code = 409
|
||||
}
|
||||
http.Error(w, e.Error(), code)
|
||||
}
|
||||
decode := func(v any) bool {
|
||||
r.Body = http.MaxBytesReader(w, r.Body, s.Gateway.MaxBytes*2+16384)
|
||||
d := json.NewDecoder(r.Body)
|
||||
d.DisallowUnknownFields()
|
||||
if d.Decode(v) != nil || d.Decode(&struct{}{}) != io.EOF {
|
||||
http.Error(w, "gateway_bad_request", 400)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
if r.Method == "GET" && r.URL.Path == "/v1/capabilities" {
|
||||
if e := s.Gateway.Ready(r.Context()); e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
if authority, ok := s.Gateway.Authority.(interface{ Ready(context.Context) error }); ok {
|
||||
if e := authority.Ready(r.Context()); e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(Capabilities{Protocol: Protocol, Scope: s.Gateway.Scope, Ready: true, AutomaticGrants: s.Gateway.Authority != nil})
|
||||
return
|
||||
}
|
||||
if r.Method != "POST" {
|
||||
http.Error(w, "gateway_route_not_found", 404)
|
||||
return
|
||||
}
|
||||
switch r.URL.Path {
|
||||
case "/v1/acquire":
|
||||
var in Claim
|
||||
if !decode(&in) {
|
||||
return
|
||||
}
|
||||
out, e := s.Gateway.Acquire(r.Context(), in)
|
||||
if e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(out)
|
||||
case "/v1/plans":
|
||||
if s.Gateway.Authority != nil {
|
||||
fail(ErrConflict)
|
||||
return
|
||||
}
|
||||
var in Plan
|
||||
if !decode(&in) {
|
||||
return
|
||||
}
|
||||
if e := s.Gateway.InstallPlan(r.Context(), in); e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(in)
|
||||
case "/v1/advance":
|
||||
if s.Gateway.Authority != nil {
|
||||
fail(ErrConflict)
|
||||
return
|
||||
}
|
||||
var in AdvanceRequest
|
||||
if !decode(&in) {
|
||||
return
|
||||
}
|
||||
if e := s.Gateway.Advance(r.Context(), in.Expected, in.Grant); e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(in)
|
||||
case "/v1/execute", "/v1/reconcile":
|
||||
var in ExecuteRequest
|
||||
if !decode(&in) {
|
||||
return
|
||||
}
|
||||
var out Receipt
|
||||
var e error
|
||||
if r.URL.Path == "/v1/execute" {
|
||||
if in.Authorization != nil {
|
||||
out, e = s.Gateway.ExecuteAuthorized(r.Context(), *in.Authorization, in.Request, in.Body)
|
||||
} else {
|
||||
out, e = s.Gateway.Execute(r.Context(), in.Request, in.Body)
|
||||
}
|
||||
} else {
|
||||
out, e = s.Gateway.Reconcile(r.Context(), in.Request)
|
||||
}
|
||||
if e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(out)
|
||||
case "/v1/resolve":
|
||||
var in Request
|
||||
if !decode(&in) {
|
||||
return
|
||||
}
|
||||
out, e := s.Gateway.Resolve(r.Context(), in)
|
||||
if e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(out)
|
||||
case "/v1/observe":
|
||||
var in struct {
|
||||
Key string `json:"key"`
|
||||
Version string `json:"version"`
|
||||
}
|
||||
if !decode(&in) {
|
||||
return
|
||||
}
|
||||
if in.Key == "" {
|
||||
http.Error(w, "gateway_bad_key", 400)
|
||||
return
|
||||
}
|
||||
if e := s.Gateway.Ready(r.Context()); e != nil {
|
||||
fail(e)
|
||||
return
|
||||
}
|
||||
v, exists, e := s.Gateway.Backend.Observe(r.Context(), in.Key, in.Version)
|
||||
if e != nil {
|
||||
http.Error(w, "gateway_backend_read_failed", 503)
|
||||
return
|
||||
}
|
||||
_ = json.NewEncoder(w).Encode(struct {
|
||||
Version Version `json:"version"`
|
||||
Exists bool `json:"exists"`
|
||||
}{v, exists})
|
||||
default:
|
||||
http.Error(w, "gateway_route_not_found", 404)
|
||||
}
|
||||
}
|
||||
|
||||
type Client struct {
|
||||
Endpoint, Token, Scope string
|
||||
HTTP *http.Client
|
||||
}
|
||||
|
||||
func NewClient(endpoint, token, scope string) (*Client, error) {
|
||||
u, e := url.Parse(endpoint)
|
||||
if e != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "" || u.Path != "" || len(token) < 32 || scope == "" {
|
||||
return nil, errors.New("gateway_configuration_invalid")
|
||||
}
|
||||
if u.Scheme != "https" && (u.Scheme != "http" || (u.Hostname() != "127.0.0.1" && u.Hostname() != "::1")) {
|
||||
return nil, errors.New("gateway_transport_requires_tls")
|
||||
}
|
||||
return &Client{endpoint, token, scope, &http.Client{Timeout: 2 * time.Minute, CheckRedirect: func(*http.Request, []*http.Request) error { return errors.New("gateway_redirect_refused") }}}, nil
|
||||
}
|
||||
func (c *Client) call(ctx context.Context, path string, in, out any) error {
|
||||
method := "GET"
|
||||
var body io.Reader
|
||||
if in != nil {
|
||||
raw, e := json.Marshal(in)
|
||||
if e != nil {
|
||||
return ErrConflict
|
||||
}
|
||||
method = "POST"
|
||||
body = struct{ io.Reader }{bytes.NewReader(raw)}
|
||||
}
|
||||
req, e := http.NewRequestWithContext(ctx, method, c.Endpoint+path, body)
|
||||
if e != nil {
|
||||
return errors.New("gateway_request_invalid")
|
||||
}
|
||||
req.Header.Set("Authorization", "Bearer "+c.Token)
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-KG-Gateway-Protocol", Protocol)
|
||||
req.Header.Set("X-KG-Gateway-Scope", c.Scope)
|
||||
resp, e := c.HTTP.Do(req)
|
||||
if e != nil {
|
||||
return errors.New("gateway_unreachable_or_outcome_unknown")
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
if resp.StatusCode != 200 {
|
||||
raw, _ := io.ReadAll(io.LimitReader(resp.Body, 128))
|
||||
reason := strings.TrimSpace(string(raw))
|
||||
switch reason {
|
||||
case ErrAuthority.Error():
|
||||
return ErrAuthority
|
||||
case ErrAuthorityPrivileges.Error():
|
||||
return ErrAuthorityPrivileges
|
||||
case ErrEpoch.Error():
|
||||
return ErrEpoch
|
||||
case ErrConflict.Error():
|
||||
return ErrConflict
|
||||
case ErrHeld.Error():
|
||||
return ErrHeld
|
||||
case ErrPersistence.Error():
|
||||
return ErrPersistence
|
||||
case ErrIsolation.Error():
|
||||
return ErrIsolation
|
||||
}
|
||||
return errors.New("gateway_request_refused")
|
||||
}
|
||||
if json.NewDecoder(io.LimitReader(resp.Body, 1<<20)).Decode(out) != nil {
|
||||
return errors.New("gateway_response_invalid")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (c *Client) Ready(ctx context.Context) error { return c.checkReady(ctx, false) }
|
||||
func (c *Client) ReadyForAcquisition(ctx context.Context) error { return c.checkReady(ctx, true) }
|
||||
func (c *Client) checkReady(ctx context.Context, automatic bool) error {
|
||||
var caps Capabilities
|
||||
if e := c.call(ctx, "/v1/capabilities", nil, &caps); e != nil {
|
||||
return e
|
||||
}
|
||||
if automatic && !caps.AutomaticGrants {
|
||||
return ErrAuthority
|
||||
}
|
||||
if caps.Protocol != Protocol || caps.Scope != c.Scope || !caps.Ready {
|
||||
return errors.New("gateway_protocol_or_target_mismatch")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (c *Client) InstallPlan(ctx context.Context, p Plan) error {
|
||||
var out Plan
|
||||
if e := c.call(ctx, "/v1/plans", p, &out); e != nil {
|
||||
return e
|
||||
}
|
||||
want, _ := json.Marshal(p)
|
||||
got, _ := json.Marshal(out)
|
||||
if string(want) != string(got) {
|
||||
return ErrConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (c *Client) Advance(ctx context.Context, expected int64, g Grant) error {
|
||||
var out AdvanceRequest
|
||||
in := AdvanceRequest{expected, g}
|
||||
if e := c.call(ctx, "/v1/advance", in, &out); e != nil {
|
||||
return e
|
||||
}
|
||||
if in != out {
|
||||
return ErrConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (c *Client) Execute(ctx context.Context, r Request, body []byte) (Receipt, error) {
|
||||
var out Receipt
|
||||
e := c.call(ctx, "/v1/execute", ExecuteRequest{Request: r, Body: body}, &out)
|
||||
if e == nil && (out.Request != r || !out.valid()) {
|
||||
e = ErrConflict
|
||||
}
|
||||
return out, e
|
||||
}
|
||||
func (c *Client) Reconcile(ctx context.Context, r Request) (Receipt, error) {
|
||||
var out Receipt
|
||||
e := c.call(ctx, "/v1/reconcile", ExecuteRequest{Request: r}, &out)
|
||||
if e == nil && (out.Request != r || !out.valid()) {
|
||||
e = ErrConflict
|
||||
}
|
||||
return out, e
|
||||
}
|
||||
func (c *Client) Observe(ctx context.Context, key, id string) (Version, bool, error) {
|
||||
var out struct {
|
||||
Version Version `json:"version"`
|
||||
Exists bool `json:"exists"`
|
||||
}
|
||||
e := c.call(ctx, "/v1/observe", struct {
|
||||
Key string `json:"key"`
|
||||
Version string `json:"version"`
|
||||
}{key, id}, &out)
|
||||
return out.Version, out.Exists, e
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package objectgateway_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
g "knowledge-governance/internal/objectgateway"
|
||||
)
|
||||
|
||||
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}
|
||||
if e := gw.InstallPlan(ctx, planFor(grant, request(t.Name(), grant))); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e := gw.Advance(ctx, 0, grant); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
token := strings.Repeat("a", 32)
|
||||
server := httptest.NewServer(g.HTTPServer{Gateway: gw, DataToken: token, ControlToken: strings.Repeat("b", 32)})
|
||||
defer server.Close()
|
||||
wrong, _ := g.NewClient(server.URL, token, "wrong-target")
|
||||
req := request(t.Name(), grant)
|
||||
receipt, e := wrong.Execute(ctx, req, []byte("gateway fixture "+t.Name()))
|
||||
if e == nil {
|
||||
cleanup(t, ctx, gw, receipt)
|
||||
t.Fatal("mutation accepted with wrong target identity")
|
||||
}
|
||||
var n int
|
||||
if pool.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_intents WHERE scope=$1", gw.Scope).Scan(&n) != nil || n != 0 {
|
||||
t.Fatal("wrong target wrote intent")
|
||||
}
|
||||
}
|
||||
func TestGatewayClientRejectsIncompleteReceipt(t *testing.T) {
|
||||
grant := g.Grant{Epoch: 1, Owner: g.Digest([]byte("owner")), Plan: g.Digest([]byte("plan"))}
|
||||
req := request("receipt", grant)
|
||||
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
_ = json.NewEncoder(w).Encode(g.Receipt{Request: req, State: "committed"})
|
||||
}))
|
||||
defer server.Close()
|
||||
c, _ := g.NewClient(server.URL, strings.Repeat("a", 32), "scope")
|
||||
if _, e := c.Execute(context.Background(), req, []byte("gateway fixture receipt")); e == nil {
|
||||
t.Fatal("committed receipt with missing exact version accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package objectgateway_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
g "knowledge-governance/internal/objectgateway"
|
||||
"testing"
|
||||
)
|
||||
|
||||
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}
|
||||
if e := gateway.InstallPlan(ctx, planFor(grant, request(t.Name(), grant))); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e := gateway.Advance(ctx, 0, grant); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
// Deferred failure fires on COMMIT, not on INSERT. This exercises the uncertain
|
||||
// persistence boundary while confirming no provider request is sent.
|
||||
_, e := pool.Exec(ctx, `CREATE FUNCTION kg_gateway_fixture_commit_failure() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN RAISE EXCEPTION 'injected durable commit failure'; END $$;
|
||||
CREATE CONSTRAINT TRIGGER kg_gateway_fixture_commit_failure AFTER INSERT ON kg_object_gateway_intents DEFERRABLE INITIALLY DEFERRED FOR EACH ROW EXECUTE FUNCTION kg_gateway_fixture_commit_failure()`)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
t.Cleanup(func() {
|
||||
_, e := pool.Exec(ctx, `DROP TRIGGER kg_gateway_fixture_commit_failure ON kg_object_gateway_intents; DROP FUNCTION kg_gateway_fixture_commit_failure()`)
|
||||
if e != nil {
|
||||
t.Error(e)
|
||||
}
|
||||
})
|
||||
req := request(t.Name(), grant)
|
||||
if _, e = gateway.Execute(ctx, req, []byte("gateway fixture "+t.Name())); !errors.Is(e, g.ErrPersistence) {
|
||||
t.Fatal("commit error not propagated", e)
|
||||
}
|
||||
if backend.calls != 0 {
|
||||
t.Fatal("object request after failed journal commit")
|
||||
}
|
||||
var n int
|
||||
if pool.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_intents WHERE scope=$1", gateway.Scope).Scan(&n) != nil || n != 0 {
|
||||
t.Fatal("failed transaction left intent")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
package objectgateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
)
|
||||
|
||||
// Plan is frozen by the authenticated controller, not by the data client. Digest
|
||||
// is the upstream write-set digest; the controller must verify that write set.
|
||||
// This allowlist prevents a valid epoch from authorizing arbitrary extra keys.
|
||||
type Plan struct {
|
||||
Digest string `json:"digest"`
|
||||
Owner string `json:"owner"`
|
||||
Objects []ObjectBinding `json:"objects"`
|
||||
}
|
||||
type ObjectBinding struct {
|
||||
Operation string `json:"operation"`
|
||||
Key string `json:"key"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Bytes int64 `json:"bytes"`
|
||||
}
|
||||
|
||||
func (p Plan) valid() bool {
|
||||
if !validHash(p.Digest) || !validHash(p.Owner) {
|
||||
return false
|
||||
}
|
||||
keys, ops := map[string]bool{}, map[string]bool{}
|
||||
for _, o := range p.Objects {
|
||||
r := Request{Grant: Grant{1, p.Owner, p.Digest}, Operation: o.Operation, Key: o.Key, Action: "create", SHA256: o.SHA256, Bytes: o.Bytes}
|
||||
if r.validate() != nil || keys[o.Key] || ops[o.Operation] {
|
||||
return false
|
||||
}
|
||||
keys[o.Key] = true
|
||||
ops[o.Operation] = true
|
||||
}
|
||||
return true
|
||||
}
|
||||
func (p Plan) allows(r Request) bool {
|
||||
op := r.Operation
|
||||
if r.Action == "delete" {
|
||||
op = r.CreatedBy
|
||||
}
|
||||
if p.Owner != r.Grant.Owner || p.Digest != r.Grant.Plan {
|
||||
return false
|
||||
}
|
||||
for _, o := range p.Objects {
|
||||
if o.Operation == op && o.Key == r.Key && o.SHA256 == r.SHA256 && o.Bytes == r.Bytes {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (g *Gateway) InstallPlan(ctx context.Context, p Plan) error {
|
||||
if !p.valid() {
|
||||
return ErrConflict
|
||||
}
|
||||
for _, o := range p.Objects {
|
||||
if o.Bytes > g.MaxBytes {
|
||||
return ErrConflict
|
||||
}
|
||||
}
|
||||
if e := g.Ready(ctx); e != nil {
|
||||
return e
|
||||
}
|
||||
raw, _ := json.Marshal(p)
|
||||
_, e := g.Pool.Exec(ctx, "INSERT INTO kg_object_gateway_plans(scope,plan,body) VALUES($1,$2,$3) ON CONFLICT DO NOTHING", g.Scope, p.Digest, raw)
|
||||
if e != nil {
|
||||
return ErrPersistence
|
||||
}
|
||||
var found []byte
|
||||
if g.Pool.QueryRow(ctx, "SELECT body FROM kg_object_gateway_plans WHERE scope=$1 AND plan=$2", g.Scope, p.Digest).Scan(&found) != nil {
|
||||
return ErrPersistence
|
||||
}
|
||||
if string(found) != string(raw) {
|
||||
return ErrConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package objectgateway_test
|
||||
|
||||
import (
|
||||
"errors"
|
||||
g "knowledge-governance/internal/objectgateway"
|
||||
"testing"
|
||||
)
|
||||
|
||||
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}
|
||||
if e := gateway.Advance(ctx, 0, grant); !errors.Is(e, g.ErrConflict) {
|
||||
t.Fatal("unregistered plan grant", e)
|
||||
}
|
||||
allowed := request("allowed-plan-key", grant)
|
||||
plan := planFor(grant, allowed)
|
||||
if e := gateway.InstallPlan(ctx, plan); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
changed := planFor(grant, request("extra-plan-key", grant))
|
||||
if e := gateway.InstallPlan(ctx, changed); !errors.Is(e, g.ErrConflict) {
|
||||
t.Fatal("immutable plan rebound", e)
|
||||
}
|
||||
if e := gateway.Advance(ctx, 0, grant); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
req := request(t.Name(), grant)
|
||||
if _, e := gateway.Execute(ctx, req, []byte("gateway fixture "+t.Name())); !errors.Is(e, g.ErrConflict) {
|
||||
t.Fatal("unplanned key admitted", e)
|
||||
}
|
||||
receipt, e := gateway.Execute(ctx, allowed, []byte("gateway fixture allowed-plan-key"))
|
||||
if e != nil || receipt.State != "committed" {
|
||||
t.Fatal("valid planned key refused", e)
|
||||
}
|
||||
cleanup(t, ctx, gateway, receipt)
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
// Package objectgateway implements non-preemptive object write ownership.
|
||||
package objectgateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"strings"
|
||||
)
|
||||
|
||||
const Protocol = "kg-object-gateway-v1"
|
||||
|
||||
var (
|
||||
ErrHeld = errors.New("gateway_held_unresolved_intent")
|
||||
ErrEpoch = errors.New("gateway_epoch_or_plan_mismatch")
|
||||
ErrConflict = errors.New("gateway_identity_conflict")
|
||||
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")
|
||||
)
|
||||
|
||||
type Grant struct {
|
||||
Epoch int64 `json:"epoch"`
|
||||
Owner string `json:"owner"`
|
||||
Plan string `json:"plan"`
|
||||
}
|
||||
type Version struct {
|
||||
ID string `json:"version_id"`
|
||||
Owner string `json:"owner"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Bytes int64 `json:"bytes"`
|
||||
ETag string `json:"etag"`
|
||||
}
|
||||
type Request struct {
|
||||
Grant Grant `json:"grant"`
|
||||
Operation string `json:"operation"`
|
||||
Key string `json:"key"`
|
||||
Action string `json:"action"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Bytes int64 `json:"bytes"`
|
||||
CreatedBy string `json:"created_by,omitempty"`
|
||||
Version Version `json:"version,omitempty"`
|
||||
}
|
||||
type Receipt struct {
|
||||
Request Request `json:"request"`
|
||||
State string `json:"state"`
|
||||
Version Version `json:"version"`
|
||||
}
|
||||
|
||||
// Backend never retries mutations. List is complete and scoped to exactly key.
|
||||
// Not finding a PUT is never evidence that its request cannot still arrive.
|
||||
type Backend interface {
|
||||
Ready(context.Context) error
|
||||
Observe(context.Context, string, string) (Version, bool, error)
|
||||
List(context.Context, string) ([]Version, error)
|
||||
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 {
|
||||
b, e := hex.DecodeString(s)
|
||||
return e == nil && len(b) == 32 && strings.ToLower(s) == s
|
||||
}
|
||||
func (g Grant) valid() bool { return g.Epoch > 0 && validHash(g.Owner) && validHash(g.Plan) }
|
||||
func (r Request) validate() error {
|
||||
if !r.Grant.valid() || !validHash(r.Operation) || r.Key == "" || len(r.Key) > 2048 || strings.ContainsAny(r.Key, "\x00\r\n") || strings.HasPrefix(r.Key, "/") || !validHash(r.SHA256) || r.Bytes < 0 {
|
||||
return ErrConflict
|
||||
}
|
||||
if r.Action != "create" && r.Action != "delete" {
|
||||
return ErrConflict
|
||||
}
|
||||
if r.Action == "create" && (r.CreatedBy != "" || r.Version != (Version{})) {
|
||||
return ErrConflict
|
||||
}
|
||||
if r.Action == "delete" && (!validHash(r.CreatedBy) || !validVersion(r.Version) || r.Version.SHA256 != r.SHA256 || r.Version.Bytes != r.Bytes) {
|
||||
return ErrConflict
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func validVersion(v Version) bool {
|
||||
return v.ID != "" && v.ID != "null" && validHash(v.Owner) && validHash(v.SHA256) && v.Bytes >= 0 && v.ETag != ""
|
||||
}
|
||||
|
||||
// Claim binds backend ownership to the complete immutable gateway request.
|
||||
func (r Request) Claim() string { return r.token() }
|
||||
func (r Request) token() string { raw, _ := json.Marshal(r); return Digest(raw) }
|
||||
func (r Receipt) valid() bool {
|
||||
if r.Request.validate() != nil {
|
||||
return false
|
||||
}
|
||||
switch r.State {
|
||||
case "committed":
|
||||
return r.Request.Action == "create" && r.Request.matches(r.Version)
|
||||
case "rejected":
|
||||
return r.Request.Action == "create" && r.Version == (Version{})
|
||||
case "removed":
|
||||
return r.Request.Action == "delete" && r.Version == r.Request.Version
|
||||
}
|
||||
return false
|
||||
}
|
||||
func (r Request) matches(v Version) bool {
|
||||
return validVersion(v) && v.Owner == r.token() && v.Bytes == r.Bytes && v.SHA256 == r.SHA256
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package objectgateway
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"errors"
|
||||
"io"
|
||||
|
||||
"github.com/aws/aws-sdk-go-v2/aws"
|
||||
"github.com/aws/aws-sdk-go-v2/aws/signer/v4"
|
||||
"github.com/aws/aws-sdk-go-v2/service/s3"
|
||||
"github.com/aws/smithy-go"
|
||||
)
|
||||
|
||||
// S3Backend is for independently versioned S3/MinIO stores. No SDK mutation retries.
|
||||
type S3Backend struct {
|
||||
Client *s3.Client
|
||||
Bucket string
|
||||
MaxBytes int64
|
||||
}
|
||||
|
||||
func (s *S3Backend) Ready(ctx context.Context) error {
|
||||
r, e := s.Client.GetBucketVersioning(ctx, &s3.GetBucketVersioningInput{Bucket: aws.String(s.Bucket)})
|
||||
if e != nil || string(r.Status) != "Enabled" {
|
||||
return errors.New("gateway_backend_versioning_unverified")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
func (s *S3Backend) Observe(ctx context.Context, key, id string) (Version, bool, error) {
|
||||
req := &s3.GetObjectInput{Bucket: aws.String(s.Bucket), Key: aws.String(key)}
|
||||
if id != "" {
|
||||
req.VersionId = aws.String(id)
|
||||
}
|
||||
got, e := s.Client.GetObject(ctx, req)
|
||||
if e != nil {
|
||||
var api smithy.APIError
|
||||
if errors.As(e, &api) && (api.ErrorCode() == "NoSuchKey" || api.ErrorCode() == "NoSuchVersion") {
|
||||
return Version{}, false, nil
|
||||
}
|
||||
return Version{}, false, errors.New("gateway_backend_read_failed")
|
||||
}
|
||||
defer got.Body.Close()
|
||||
if got.ContentLength == nil || *got.ContentLength < 0 || *got.ContentLength > s.MaxBytes {
|
||||
return Version{}, false, errors.New("gateway_backend_size_invalid")
|
||||
}
|
||||
body, e := io.ReadAll(io.LimitReader(got.Body, s.MaxBytes+1))
|
||||
if e != nil || int64(len(body)) != *got.ContentLength {
|
||||
return Version{}, false, errors.New("gateway_backend_body_incomplete")
|
||||
}
|
||||
v := Version{aws.ToString(got.VersionId), got.Metadata["kg-release-owner"], Digest(body), int64(len(body)), aws.ToString(got.ETag)}
|
||||
// Existing unowned objects are observable but cannot be claimed/deleted.
|
||||
if v.ID == "" || v.ID == "null" || v.ETag == "" || id != "" && v.ID != id {
|
||||
return Version{}, false, errors.New("gateway_backend_version_invalid")
|
||||
}
|
||||
return v, true, nil
|
||||
}
|
||||
func (s *S3Backend) List(ctx context.Context, key string) ([]Version, error) {
|
||||
got, e := s.Client.ListObjectVersions(ctx, &s3.ListObjectVersionsInput{Bucket: aws.String(s.Bucket), Prefix: aws.String(key), MaxKeys: aws.Int32(1000)})
|
||||
if e != nil || aws.ToBool(got.IsTruncated) {
|
||||
return nil, errors.New("gateway_backend_listing_incomplete")
|
||||
}
|
||||
var versions []Version
|
||||
for _, m := range got.DeleteMarkers {
|
||||
if aws.ToString(m.Key) == key {
|
||||
return nil, errors.New("gateway_backend_delete_marker_conflict")
|
||||
}
|
||||
}
|
||||
for _, v := range got.Versions {
|
||||
if aws.ToString(v.Key) == key {
|
||||
one, exists, e := s.Observe(ctx, key, aws.ToString(v.VersionId))
|
||||
if e != nil || !exists {
|
||||
return nil, errors.New("gateway_backend_listing_changed")
|
||||
}
|
||||
versions = append(versions, one)
|
||||
}
|
||||
}
|
||||
return versions, nil
|
||||
}
|
||||
func (s *S3Backend) Put(ctx context.Context, key string, body []byte, owner string) (Version, error) {
|
||||
// SDK hashing requires a seekable body. RetryMaxAttempts=1 prevents SDK
|
||||
// retries; PUT carries no HTTP idempotency header or replay authorization.
|
||||
reader := bytes.NewReader(body)
|
||||
got, e := s.Client.PutObject(v4.SetPayloadHash(ctx, Digest(body)), &s3.PutObjectInput{Bucket: aws.String(s.Bucket), Key: aws.String(key), Body: reader, ContentLength: aws.Int64(int64(len(body))), Metadata: map[string]string{"kg-release-owner": owner}}, func(o *s3.Options) { o.RetryMaxAttempts = 1 })
|
||||
if e != nil || aws.ToString(got.VersionId) == "" {
|
||||
return Version{}, ErrHeld
|
||||
}
|
||||
v, exists, e := s.Observe(ctx, key, aws.ToString(got.VersionId))
|
||||
if e != nil || !exists {
|
||||
return Version{}, ErrHeld
|
||||
}
|
||||
return v, nil
|
||||
}
|
||||
func (s *S3Backend) Delete(ctx context.Context, key string, v Version) error {
|
||||
if !validVersion(v) {
|
||||
return ErrConflict
|
||||
}
|
||||
_, e := s.Client.DeleteObject(ctx, &s3.DeleteObjectInput{Bucket: aws.String(s.Bucket), Key: aws.String(key), VersionId: aws.String(v.ID)}, func(o *s3.Options) { o.RetryMaxAttempts = 1 })
|
||||
if e != nil {
|
||||
return ErrHeld
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
-- Independent governance journal; never install in a WeKnora business schema.
|
||||
CREATE TABLE IF NOT EXISTS kg_object_gateway_plans (
|
||||
scope text NOT NULL,
|
||||
plan text NOT NULL,
|
||||
body bytea NOT NULL,
|
||||
PRIMARY KEY(scope,plan)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS kg_object_gateway_scopes (
|
||||
scope text PRIMARY KEY,
|
||||
epoch bigint NOT NULL DEFAULT 0
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS kg_object_gateway_grants (
|
||||
scope text NOT NULL REFERENCES kg_object_gateway_scopes(scope),
|
||||
epoch bigint NOT NULL CHECK (epoch > 0),
|
||||
owner text NOT NULL,
|
||||
plan text NOT NULL,
|
||||
PRIMARY KEY(scope,epoch)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS kg_object_gateway_intents (
|
||||
scope text NOT NULL REFERENCES kg_object_gateway_scopes(scope),
|
||||
operation text NOT NULL,
|
||||
key text NOT NULL,
|
||||
request bytea NOT NULL,
|
||||
recorded_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
PRIMARY KEY(scope,operation)
|
||||
);
|
||||
CREATE INDEX IF NOT EXISTS kg_object_gateway_key ON kg_object_gateway_intents(scope,key);
|
||||
CREATE TABLE IF NOT EXISTS kg_object_gateway_receipts (
|
||||
scope text NOT NULL,
|
||||
operation text NOT NULL,
|
||||
receipt bytea NOT NULL,
|
||||
recorded_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
PRIMARY KEY(scope,operation),
|
||||
FOREIGN KEY(scope,operation) REFERENCES kg_object_gateway_intents(scope,operation)
|
||||
);
|
||||
CREATE TABLE IF NOT EXISTS kg_object_gateway_deliveries (
|
||||
scope text NOT NULL,
|
||||
job text NOT NULL,
|
||||
attempt_epoch bigint NOT NULL CHECK(attempt_epoch>0),
|
||||
claim bytea NOT NULL,
|
||||
grant_epoch bigint NOT NULL,
|
||||
grant_body bytea NOT NULL,
|
||||
PRIMARY KEY(scope,job,attempt_epoch),
|
||||
FOREIGN KEY(scope,grant_epoch) REFERENCES kg_object_gateway_grants(scope,epoch)
|
||||
);
|
||||
CREATE OR REPLACE FUNCTION kg_object_gateway_immutable() RETURNS trigger LANGUAGE plpgsql AS $$
|
||||
BEGIN
|
||||
RAISE EXCEPTION 'object gateway evidence is immutable';
|
||||
END;
|
||||
$$;
|
||||
DO $$ BEGIN
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname='kg_object_gateway_deliveries_immutable') THEN
|
||||
CREATE TRIGGER kg_object_gateway_deliveries_immutable BEFORE UPDATE OR DELETE ON kg_object_gateway_deliveries FOR EACH ROW EXECUTE FUNCTION kg_object_gateway_immutable();
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname='kg_object_gateway_plans_immutable') THEN
|
||||
CREATE TRIGGER kg_object_gateway_plans_immutable BEFORE UPDATE OR DELETE ON kg_object_gateway_plans FOR EACH ROW EXECUTE FUNCTION kg_object_gateway_immutable();
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname='kg_object_gateway_intents_immutable') THEN
|
||||
CREATE TRIGGER kg_object_gateway_intents_immutable BEFORE UPDATE OR DELETE ON kg_object_gateway_intents FOR EACH ROW EXECUTE FUNCTION kg_object_gateway_immutable();
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname='kg_object_gateway_receipts_immutable') THEN
|
||||
CREATE TRIGGER kg_object_gateway_receipts_immutable BEFORE UPDATE OR DELETE ON kg_object_gateway_receipts FOR EACH ROW EXECUTE FUNCTION kg_object_gateway_immutable();
|
||||
END IF;
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname='kg_object_gateway_grants_immutable') THEN
|
||||
CREATE TRIGGER kg_object_gateway_grants_immutable BEFORE UPDATE OR DELETE ON kg_object_gateway_grants FOR EACH ROW EXECUTE FUNCTION kg_object_gateway_immutable();
|
||||
END IF;
|
||||
END $$;
|
||||
DO $$ DECLARE t text; BEGIN
|
||||
FOREACH t IN ARRAY ARRAY['plans','grants','intents','receipts','deliveries'] LOOP
|
||||
IF NOT EXISTS (SELECT 1 FROM pg_trigger WHERE tgname='kg_object_gateway_'||t||'_no_truncate') THEN
|
||||
EXECUTE format('CREATE TRIGGER %I BEFORE TRUNCATE ON %I FOR EACH STATEMENT EXECUTE FUNCTION kg_object_gateway_immutable()', 'kg_object_gateway_'||t||'_no_truncate', 'kg_object_gateway_'||t);
|
||||
END IF;
|
||||
END LOOP;
|
||||
END $$;
|
||||
@@ -0,0 +1,60 @@
|
||||
package objectgateway
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"github.com/jackc/pgx/v5"
|
||||
)
|
||||
|
||||
// Resolve preserves the immutable send epoch and backend claim of an operation.
|
||||
// An absent intent is not a claim about an earlier send; Execute still reserves
|
||||
// atomically and refuses stale authorizations before any new side effect.
|
||||
func (g *Gateway) Resolve(ctx context.Context, desired Request) (Request, error) {
|
||||
if e := desired.validate(); e != nil {
|
||||
return Request{}, e
|
||||
}
|
||||
if e := g.Ready(ctx); e != nil {
|
||||
return Request{}, e
|
||||
}
|
||||
var raw []byte
|
||||
e := g.Pool.QueryRow(ctx, "SELECT request FROM kg_object_gateway_intents WHERE scope=$1 AND operation=$2", g.Scope, desired.Operation).Scan(&raw)
|
||||
if errors.Is(e, pgx.ErrNoRows) {
|
||||
return desired, nil
|
||||
}
|
||||
if e != nil {
|
||||
return Request{}, ErrPersistence
|
||||
}
|
||||
var original Request
|
||||
if json.Unmarshal(raw, &original) != nil || original.validate() != nil {
|
||||
return Request{}, ErrPersistence
|
||||
}
|
||||
if !sameOperation(original, desired) || original.Grant.Epoch > desired.Grant.Epoch {
|
||||
return Request{}, ErrConflict
|
||||
}
|
||||
return original, nil
|
||||
}
|
||||
func sameOperation(a, b Request) bool { a.Grant.Epoch = b.Grant.Epoch; return a == b }
|
||||
|
||||
func (g *Gateway) ExecuteAuthorized(ctx context.Context, authorization Grant, r Request, body []byte) (Receipt, error) {
|
||||
if !authorization.valid() || authorization.Owner != r.Grant.Owner || authorization.Plan != r.Grant.Plan || authorization.Epoch < r.Grant.Epoch {
|
||||
return Receipt{}, ErrEpoch
|
||||
}
|
||||
return g.execute(ctx, r, body, &authorization)
|
||||
}
|
||||
func (c *Client) ExecuteAuthorized(ctx context.Context, authorization Grant, r Request, body []byte) (Receipt, error) {
|
||||
var out Receipt
|
||||
e := c.call(ctx, "/v1/execute", ExecuteRequest{Request: r, Body: body, Authorization: &authorization}, &out)
|
||||
if e == nil && (out.Request != r || !out.valid()) {
|
||||
e = ErrConflict
|
||||
}
|
||||
return out, e
|
||||
}
|
||||
func (c *Client) Resolve(ctx context.Context, desired Request) (Request, error) {
|
||||
var out Request
|
||||
e := c.call(ctx, "/v1/resolve", desired, &out)
|
||||
if e == nil && (out.validate() != nil || !sameOperation(out, desired) || out.Grant.Epoch > desired.Grant.Epoch) {
|
||||
e = ErrConflict
|
||||
}
|
||||
return out, e
|
||||
}
|
||||
@@ -0,0 +1,111 @@
|
||||
package objectgateway_test
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
g "knowledge-governance/internal/objectgateway"
|
||||
)
|
||||
|
||||
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}
|
||||
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 {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e := gateway.Advance(ctx, 0, first); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
old, e := gateway.Execute(ctx, sent, []byte("gateway fixture takeover-sent"))
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
// Always clean only this test's exact original version, including on RED.
|
||||
cleanupGrant := first
|
||||
defer func() { copy := old; copy.Request.Grant = cleanupGrant; cleanup(t, ctx, gateway, copy) }()
|
||||
var original []byte
|
||||
if e = pool.QueryRow(ctx, "SELECT request FROM kg_object_gateway_intents WHERE scope=$1 AND operation=$2", gateway.Scope, sent.Operation).Scan(&original); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
next := first
|
||||
next.Epoch++
|
||||
if e = gateway.Advance(ctx, 1, next); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
cleanupGrant = next
|
||||
data, control := g.Digest([]byte("takeover-data")), g.Digest([]byte("takeover-control"))
|
||||
server := httptest.NewServer(g.HTTPServer{Gateway: gateway, DataToken: data, ControlToken: control})
|
||||
defer server.Close()
|
||||
post := func(path string, in any) (int, []byte) {
|
||||
raw, _ := json.Marshal(in)
|
||||
req, _ := http.NewRequestWithContext(ctx, "POST", server.URL+path, bytes.NewReader(raw))
|
||||
req.Header.Set("Authorization", "Bearer "+data)
|
||||
req.Header.Set("X-KG-Gateway-Protocol", g.Protocol)
|
||||
req.Header.Set("X-KG-Gateway-Scope", gateway.Scope)
|
||||
resp, e := http.DefaultClient.Do(req)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
return resp.StatusCode, body
|
||||
}
|
||||
code, body := post("/v1/execute", map[string]any{"request": sent, "authorization": next, "body": []byte("gateway fixture takeover-sent")})
|
||||
if code != 200 {
|
||||
t.Fatalf("new authorization cannot replay immutable original request: status=%d", code)
|
||||
}
|
||||
var replay g.Receipt
|
||||
if json.Unmarshal(body, &replay) != nil || replay != old {
|
||||
t.Fatal("replay rewrote original receipt")
|
||||
}
|
||||
desired := sent
|
||||
desired.Grant = next
|
||||
code, body = post("/v1/resolve", desired)
|
||||
var resolved g.Request
|
||||
if code != 200 || json.Unmarshal(body, &resolved) != nil || resolved != sent {
|
||||
t.Fatal("original send identity not resolved", code)
|
||||
}
|
||||
changed := sent
|
||||
changed.SHA256 = g.Digest([]byte("different"))
|
||||
if code, _ = post("/v1/resolve", changed); code == 200 {
|
||||
t.Fatal("operation rebound body")
|
||||
}
|
||||
if code, _ = post("/v1/execute", map[string]any{"request": unsent, "authorization": first, "body": []byte("gateway fixture takeover-unsent")}); code == 200 {
|
||||
t.Fatal("stale epoch created unsent key")
|
||||
}
|
||||
unsent.Grant = next
|
||||
code, body = post("/v1/execute", map[string]any{"request": unsent, "authorization": next, "body": []byte("gateway fixture takeover-unsent")})
|
||||
var created g.Receipt
|
||||
if code != 200 || json.Unmarshal(body, &created) != nil || created.State != "committed" {
|
||||
t.Fatal("new epoch did not continue unsent key", code)
|
||||
}
|
||||
cleanup(t, ctx, gateway, created)
|
||||
var after []byte
|
||||
if e = pool.QueryRow(ctx, "SELECT request FROM kg_object_gateway_intents WHERE scope=$1 AND operation=$2", gateway.Scope, sent.Operation).Scan(&after); e != nil || !bytes.Equal(after, original) {
|
||||
t.Fatal("immutable intent changed", e)
|
||||
}
|
||||
versions, e := backend.List(ctx, sent.Key)
|
||||
if e != nil || len(versions) != 1 || versions[0] != old.Version {
|
||||
t.Fatal("replay created extra version", e)
|
||||
}
|
||||
// Deletion is a new send in the current epoch, not a rewritten create intent.
|
||||
deletion := sent
|
||||
deletion.Grant = next
|
||||
deletion.Operation = g.Digest([]byte(sent.Operation + "delete"))
|
||||
deletion.Action = "delete"
|
||||
deletion.CreatedBy = sent.Operation
|
||||
deletion.Version = old.Version
|
||||
code, _ = post("/v1/execute", map[string]any{"request": deletion, "authorization": next})
|
||||
if code != 200 {
|
||||
t.Fatal("new epoch exact cleanup refused", code)
|
||||
}
|
||||
// deferred cleanup replays the same already settled delete request below.
|
||||
old.Request.Grant = next
|
||||
t.Log("new epoch replay retained original request/receipt/claim; unsent key committed once; stale request rejected")
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
package objectgateway_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"testing"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
g "knowledge-governance/internal/objectgateway"
|
||||
)
|
||||
|
||||
type stoppedBeforeSend struct {
|
||||
g.Backend
|
||||
calls int
|
||||
}
|
||||
|
||||
func (b *stoppedBeforeSend) Put(context.Context, string, []byte, string) (g.Version, error) {
|
||||
b.calls++
|
||||
return g.Version{}, errors.New("injected uncertain send with no visible version")
|
||||
}
|
||||
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}
|
||||
if e := gateway.InstallPlan(ctx, planFor(grant, request(t.Name(), grant))); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
if e := gateway.Advance(ctx, 0, grant); e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
req := request(t.Name(), grant)
|
||||
body := []byte("gateway fixture " + t.Name())
|
||||
if _, e := gateway.Execute(ctx, req, body); !errors.Is(e, g.ErrHeld) {
|
||||
t.Fatal(e)
|
||||
}
|
||||
restarted := *gateway
|
||||
for i := 0; i < 2; i++ {
|
||||
if _, e := restarted.Execute(ctx, req, body); !errors.Is(e, g.ErrHeld) {
|
||||
t.Fatal("absent version treated as terminal", e)
|
||||
}
|
||||
}
|
||||
if backend.calls != 1 {
|
||||
t.Fatal("PUT replayed", backend.calls)
|
||||
}
|
||||
next := grant
|
||||
next.Epoch++
|
||||
if e := restarted.Advance(ctx, 1, next); !errors.Is(e, g.ErrHeld) {
|
||||
t.Fatal("unknown operation allowed epoch handover", e)
|
||||
}
|
||||
var n int
|
||||
if pool.QueryRow(ctx, "SELECT count(*) FROM kg_object_gateway_receipts WHERE scope=$1", gateway.Scope).Scan(&n) != nil || n != 0 {
|
||||
t.Fatal("absence wrote false terminal receipt")
|
||||
}
|
||||
}
|
||||
func TestGatewayReadOnlyPersistenceBlocksSend(t *testing.T) {
|
||||
ctx, pool, backend := fixture(t)
|
||||
cfg := pool.Config()
|
||||
cfg.ConnConfig.RuntimeParams["default_transaction_read_only"] = "on"
|
||||
other, e := pgxpool.NewWithConfig(ctx, cfg)
|
||||
if e != nil {
|
||||
t.Fatal(e)
|
||||
}
|
||||
defer other.Close()
|
||||
gateway := &g.Gateway{Pool: other, Scope: backend.Bucket, Backend: backend, Isolation: verifiedFixture{}, MaxBytes: 1 << 20}
|
||||
if e = gateway.Ready(ctx); !errors.Is(e, g.ErrPersistence) {
|
||||
t.Fatal("read-only persistence accepted", e)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user