Files
mpc/pkg/approval/orchestrator_test.go
zeekay 3bb399cbdd mpc: deployment-mode flag + audit dispatcher for fund-private clusters
Adds the topology contract that lets a fund run mpcd as its own private
cluster — no Lux primary network registration, no shared M-Chain audit
ledger — using the same code path and the same operator surface.

Mode flag at cmd/mpcd/main.go:
  --network=primary|private              # registration target
  --audit-store=mchain|local-worm|...    # audit log destination
  --registrar-url, --registrar-auth      # primary-mode announcement
  --audit-worm-path, --audit-mchain-url  # backend selectors

pkg/audit:
  - Append-only Merkle hash chain. Tampering with any historical event
    invalidates every subsequent hash. Canonical bytes use fixed-order
    concatenation (json.Marshal map ordering is non-deterministic).
  - WORMDispatcher: NDJSON append, replay-on-start, fsync per Append.
  - MChainDispatcher: batched POST of (batchHash, fromSeq, toSeq) to a
    configurable anchor RPC.
  - compositeDispatcher: fan-out to multiple legs with per-leg sealing.
  - S3 Glacier Vault / Azure Immutable / GCS Object Lock dispatchers
    fail closed — wired into the flag surface but gated behind the
    cloud-audit build tag, no silent fallback.

pkg/identity/bootstrap.go: identity creation + (primary-mode only)
registrar announcement. Same on-disk format as the previous
loadOrGenerateIdentity (which is now removed); private mode is silent.

deployments/k8s-private: fund-only Kustomize overlay. Standalone
namespace, NetworkPolicy that blocks egress to anything outside the
fund's VPC, hardware-WORM PVC for the audit log, KMS-driven secret
template.

deployments/k8s-primary: env-var patch overlay on the existing lux-mpc
base. composite(local-worm,mchain) by default.

deployments/terraform/{aws,gcp,azure}: VPC + audit storage modules.
terraform validate passes; EKS/GKE/AKS + HSM modules are stubbed and
not yet plan-tested.

deployments/onprem/README.md: WORM storage + PKCS#11 HSM checklist.

Tests (14 total, all passing):
  pkg/audit:           6/6  (chain, WORM replay, MChain batching, composite,
                             cloud stubs fail loud, double-seal rejected)
  pkg/identity:        4/4  (private no-call, primary call, primary empty
                             URL no-op, primary registrar 503 surfaces)
  internal/privatemode: 4/4 (no registrar traffic, restart, tamper-detect,
                             cloud stubs fail loud)

Companion runbook in lux/papers/lux-private-mpc-deployment/
(LaTeX, 5 pages, tectonic-clean).
2025-12-28 16:20:40 -08:00

166 lines
5.0 KiB
Go

package approval
import (
"context"
"errors"
"os"
"strings"
"testing"
"time"
)
func devEnv(t *testing.T) {
t.Helper()
prevEnv := os.Getenv("MPC_ENV")
prevFlag := os.Getenv("MPC_LOCAL_APPROVAL")
t.Cleanup(func() {
os.Setenv("MPC_ENV", prevEnv)
os.Setenv("MPC_LOCAL_APPROVAL", prevFlag)
})
os.Setenv("MPC_ENV", "test")
os.Setenv("MPC_LOCAL_APPROVAL", "true")
}
func makeBoundOrchestrator(t *testing.T, approvers []string) *Orchestrator {
t.Helper()
dev, err := NewLocalDev(nil)
if err != nil {
t.Fatal(err)
}
o := NewOrchestrator([]ApprovalProvider{dev})
for _, a := range approvers {
if err := o.Bind(ApproverBinding{ApproverID: a, ProviderName: "local-dev"}); err != nil {
t.Fatalf("Bind(%s): %v", a, err)
}
}
return o
}
func TestOrchestrator_2of3_Succeeds(t *testing.T) {
devEnv(t)
o := makeBoundOrchestrator(t, []string{"alice", "bob", "carol"})
intent := newTestIntent("2-of-3 approval")
bundle, err := o.CollectApprovals(context.Background(), intent, []string{"alice", "bob", "carol"}, 2)
if err != nil {
t.Fatalf("CollectApprovals: %v", err)
}
if len(bundle) < 2 {
t.Fatalf("bundle has %d signatures, want >= 2", len(bundle))
}
ok, err := o.VerifyBundle(context.Background(), intent, bundle, 2)
if err != nil {
t.Fatalf("VerifyBundle: %v", err)
}
if !ok {
t.Fatal("VerifyBundle = false")
}
}
func TestOrchestrator_AllSucceed(t *testing.T) {
devEnv(t)
o := makeBoundOrchestrator(t, []string{"alice", "bob", "carol"})
intent := newTestIntent("all-three approval")
bundle, err := o.CollectApprovals(context.Background(), intent, []string{"alice", "bob", "carol"}, 3)
if err != nil {
t.Fatalf("CollectApprovals: %v", err)
}
if len(bundle) != 3 {
t.Fatalf("bundle has %d signatures, want 3", len(bundle))
}
}
func TestOrchestrator_ThresholdTooHigh(t *testing.T) {
devEnv(t)
o := makeBoundOrchestrator(t, []string{"alice"})
intent := newTestIntent("impossible threshold")
if _, err := o.CollectApprovals(context.Background(), intent, []string{"alice"}, 5); err == nil {
t.Fatal("CollectApprovals with threshold > approvers: want error")
}
}
func TestOrchestrator_UnboundApprover(t *testing.T) {
devEnv(t)
dev, _ := NewLocalDev(nil)
o := NewOrchestrator([]ApprovalProvider{dev})
o.Bind(ApproverBinding{ApproverID: "alice", ProviderName: "local-dev"})
// "bob" is intentionally unbound.
intent := newTestIntent("missing binding")
if _, err := o.CollectApprovals(context.Background(), intent, []string{"alice", "bob"}, 2); err == nil {
t.Fatal("CollectApprovals with unbound approver: want error")
} else if !strings.Contains(err.Error(), "not bound") {
t.Fatalf("error %q does not mention 'not bound'", err)
}
}
func TestOrchestrator_DedupesApprovers(t *testing.T) {
devEnv(t)
o := makeBoundOrchestrator(t, []string{"alice"})
intent := newTestIntent("dedupe test")
bundle, err := o.CollectApprovals(context.Background(), intent, []string{"alice", "alice", "alice"}, 1)
if err != nil {
t.Fatalf("CollectApprovals: %v", err)
}
// dedupe shrinks to 1 unique approver, threshold 1 satisfied
if len(bundle) != 1 {
t.Fatalf("bundle has %d, want 1", len(bundle))
}
}
// slowProvider delays Approve for the configured duration so we can test
// context cancellation.
type slowProvider struct {
delay time.Duration
}
func (p *slowProvider) Provider() string { return "slow" }
func (p *slowProvider) GetPublicIdentity(_ context.Context, approverID string) (PublicIdentity, error) {
return PublicIdentity{ApproverID: approverID, Provider: "slow"}, nil
}
func (p *slowProvider) ApproveIntent(ctx context.Context, approverID string, _ CanonicalIntent) (ApprovalSignature, error) {
select {
case <-time.After(p.delay):
return ApprovalSignature{ApproverID: approverID, Provider: "slow"}, nil
case <-ctx.Done():
return ApprovalSignature{}, ctx.Err()
}
}
func (p *slowProvider) VerifyApproval(_ context.Context, _ CanonicalIntent, _ ApprovalSignature) (bool, error) {
return true, nil
}
func TestOrchestrator_ContextTimeout(t *testing.T) {
slow := &slowProvider{delay: 5 * time.Second}
o := NewOrchestrator([]ApprovalProvider{slow})
o.Bind(ApproverBinding{ApproverID: "alice", ProviderName: "slow"})
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
intent := newTestIntent("timeout test")
_, err := o.CollectApprovals(ctx, intent, []string{"alice"}, 1)
if err == nil {
t.Fatal("CollectApprovals on cancelled context: want error")
}
if !errors.Is(err, context.DeadlineExceeded) && !strings.Contains(err.Error(), "threshold 1 not met") {
t.Fatalf("unexpected error %v", err)
}
}
func TestOrchestrator_VerifyBundle_RejectsWrongCount(t *testing.T) {
devEnv(t)
o := makeBoundOrchestrator(t, []string{"alice"})
intent := newTestIntent("verify count")
bundle, err := o.CollectApprovals(context.Background(), intent, []string{"alice"}, 1)
if err != nil {
t.Fatal(err)
}
// Threshold 2 but only 1 signature → false.
ok, err := o.VerifyBundle(context.Background(), intent, bundle, 2)
if err != nil {
t.Fatal(err)
}
if ok {
t.Fatal("VerifyBundle accepted insufficient signatures")
}
}