Files
mpc/e2e/approval_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

183 lines
5.8 KiB
Go

package e2e
import (
"context"
"crypto/sha256"
"os"
"strings"
"testing"
"time"
"github.com/luxfi/mpc/pkg/approval"
)
// e2eIntent is the test stand-in for pkg/intent.CanonicalIntent.
type e2eIntent struct {
body []byte
}
func (i *e2eIntent) Digest() [32]byte { return sha256.Sum256(i.body) }
func (i *e2eIntent) Bytes() []byte { return i.body }
func enableLocalDev(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")
}
// TestApproval_E2E_2of3_LocalDev exercises the full collect-and-verify flow
// with three independent approver keys, all backed by the local-dev
// software signer. This is the smoke test the CI pipeline runs without
// any HSM infrastructure.
func TestApproval_E2E_2of3_LocalDev(t *testing.T) {
enableLocalDev(t)
dev, err := approval.NewLocalDev(nil)
if err != nil {
t.Fatalf("NewLocalDev: %v", err)
}
o := approval.NewOrchestrator([]approval.ApprovalProvider{dev})
for _, a := range []string{"[email protected]", "[email protected]", "[email protected]"} {
if err := o.Bind(approval.ApproverBinding{
ApproverID: a,
ProviderName: "local-dev",
}); err != nil {
t.Fatalf("Bind(%s): %v", a, err)
}
}
intent := &e2eIntent{body: []byte("transfer 1000 LUX to grant recipient")}
bundle, err := o.CollectApprovals(context.Background(), intent,
[]string{"[email protected]", "[email protected]", "[email protected]"}, 2)
if err != nil {
t.Fatalf("CollectApprovals: %v", err)
}
if len(bundle) < 2 {
t.Fatalf("bundle has %d sigs, 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 returned false")
}
}
// TestApproval_E2E_MixedProviders binds approvers across TWO distinct
// providers — local-dev (Ed25519) and MLDSA (post-quantum). This is the
// configuration a real fund would run: every executive uses a *different*
// device class so a single supply-chain compromise cannot reach all of them.
func TestApproval_E2E_MixedProviders(t *testing.T) {
enableLocalDev(t)
dev, err := approval.NewLocalDev(nil)
if err != nil {
t.Fatalf("NewLocalDev: %v", err)
}
pq, err := approval.NewMLDSA(nil)
if err != nil {
t.Fatalf("NewMLDSA: %v", err)
}
if err := pq.(*approval.MLDSAProvider).Enroll("[email protected]", nil); err != nil {
t.Fatalf("MLDSA.Enroll: %v", err)
}
o := approval.NewOrchestrator([]approval.ApprovalProvider{dev, pq})
o.Bind(approval.ApproverBinding{ApproverID: "[email protected]", ProviderName: "local-dev"})
o.Bind(approval.ApproverBinding{ApproverID: "[email protected]", ProviderName: "mldsa"})
intent := &e2eIntent{body: []byte("multi-provider approval")}
bundle, err := o.CollectApprovals(context.Background(), intent, []string{"[email protected]", "[email protected]"}, 2)
if err != nil {
t.Fatalf("CollectApprovals: %v", err)
}
if len(bundle) != 2 {
t.Fatalf("bundle has %d, want 2", len(bundle))
}
// Confirm they used different providers — provenance check.
seen := map[string]bool{}
for _, sig := range bundle {
seen[sig.Provider] = true
}
if !seen["local-dev"] || !seen["mldsa"] {
t.Fatalf("missing provider in bundle: %+v", seen)
}
ok, err := o.VerifyBundle(context.Background(), intent, bundle, 2)
if err != nil {
t.Fatalf("VerifyBundle: %v", err)
}
if !ok {
t.Fatal("VerifyBundle = false")
}
}
// TestApproval_E2E_TamperedIntentRejected confirms re-verifying a bundle
// against a different intent payload fails — digest binding holds.
func TestApproval_E2E_TamperedIntentRejected(t *testing.T) {
enableLocalDev(t)
dev, err := approval.NewLocalDev(nil)
if err != nil {
t.Fatal(err)
}
o := approval.NewOrchestrator([]approval.ApprovalProvider{dev})
o.Bind(approval.ApproverBinding{ApproverID: "alice", ProviderName: "local-dev"})
original := &e2eIntent{body: []byte("send 10 LUX to alice")}
bundle, err := o.CollectApprovals(context.Background(), original, []string{"alice"}, 1)
if err != nil {
t.Fatalf("CollectApprovals: %v", err)
}
tampered := &e2eIntent{body: []byte("send 1000000 LUX to attacker")}
ok, _ := o.VerifyBundle(context.Background(), tampered, bundle, 1)
if ok {
t.Fatal("VerifyBundle accepted bundle for tampered intent — replay attack")
}
}
// TestApproval_E2E_FactoryRejectsLocalDevInProduction is the production
// safety guard test. The factory MUST refuse local-dev when MPC_ENV=production.
func TestApproval_E2E_FactoryRejectsLocalDevInProduction(t *testing.T) {
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", "production")
os.Setenv("MPC_LOCAL_APPROVAL", "")
if _, err := approval.NewProvider("local-dev", nil); err == nil {
t.Fatal("factory built local-dev in production: production safety guard failed")
} else if !strings.Contains(err.Error(), "forbidden in production") {
t.Fatalf("error %q does not mention production", err)
}
}
// TestApproval_E2E_DispatchTimeout asserts CollectApprovals returns
// promptly when context expires before threshold met.
func TestApproval_E2E_DispatchTimeout(t *testing.T) {
enableLocalDev(t)
dev, _ := approval.NewLocalDev(nil)
o := approval.NewOrchestrator([]approval.ApprovalProvider{dev})
o.Bind(approval.ApproverBinding{ApproverID: "alice", ProviderName: "local-dev"})
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
intent := &e2eIntent{body: []byte("deadline test")}
// local-dev signs immediately so this should succeed even with a tight deadline.
if _, err := o.CollectApprovals(ctx, intent, []string{"alice"}, 1); err != nil {
t.Fatalf("CollectApprovals(short deadline): %v", err)
}
}