|
| 1 | +// \\ SPIKE: Secure your secrets with SPIFFE. — https://spike.ist/ |
| 2 | +// \\\\\ Copyright 2024-present SPIKE contributors. |
| 3 | +// \\\\\\\ SPDX-License-Identifier: Apache-2.0 |
| 4 | + |
| 5 | +package integration |
| 6 | + |
| 7 | +import ( |
| 8 | + "fmt" |
| 9 | + "os" |
| 10 | + "testing" |
| 11 | + |
| 12 | + "github.com/spiffe/spike-sdk-go/api/entity/data" |
| 13 | + "github.com/spiffe/spike-sdk-go/config/env" |
| 14 | + "github.com/spiffe/spike-sdk-go/crypto" |
| 15 | + "github.com/spiffe/spike-sdk-go/security/mem" |
| 16 | + |
| 17 | + "github.com/spiffe/spike/app/nexus/internal/initialization/recovery" |
| 18 | + state "github.com/spiffe/spike/app/nexus/internal/state/base" |
| 19 | +) |
| 20 | + |
| 21 | +// TestMain isolates the package run: the sqlite backend writes into a |
| 22 | +// per-run temporary directory (fs.NexusDataFolder memoizes its result, |
| 23 | +// so the override must precede the first resolution), and the backend |
| 24 | +// store type is pinned to sqlite explicitly since the lifecycle under |
| 25 | +// test only exists for persistent backends. |
| 26 | +func TestMain(m *testing.M) { |
| 27 | + dir, mkErr := os.MkdirTemp("", "spike-state-integration-test-*") |
| 28 | + if mkErr != nil { |
| 29 | + fmt.Fprintln(os.Stderr, |
| 30 | + "failed to create a temporary data directory:", mkErr) |
| 31 | + os.Exit(1) |
| 32 | + } |
| 33 | + |
| 34 | + for key, value := range map[string]string{ |
| 35 | + env.NexusDataDir: dir, |
| 36 | + env.NexusBackendStore: "sqlite", |
| 37 | + } { |
| 38 | + if setErr := os.Setenv(key, value); setErr != nil { |
| 39 | + _ = os.RemoveAll(dir) |
| 40 | + fmt.Fprintln(os.Stderr, "failed to set "+key+":", setErr) |
| 41 | + os.Exit(1) |
| 42 | + } |
| 43 | + } |
| 44 | + |
| 45 | + code := m.Run() |
| 46 | + |
| 47 | + _ = os.RemoveAll(dir) |
| 48 | + os.Exit(code) |
| 49 | +} |
| 50 | + |
| 51 | +const ( |
| 52 | + secretPath = "integration/db/creds" |
| 53 | + policyName = "integration-workload-can-read" |
| 54 | +) |
| 55 | + |
| 56 | +// TestStateLifecycle walks the state layer through its whole life: |
| 57 | +// initialization, secret and policy writes, a duplicate initialization |
| 58 | +// (which must not recompute or corrupt anything), the export of |
| 59 | +// operator recovery shards, a simulated root-key loss, a shard-based |
| 60 | +// restore, and finally proof that the pre-crash data is readable again. |
| 61 | +// The stages depend on each other and run in order. |
| 62 | +func TestStateLifecycle(t *testing.T) { |
| 63 | + rootKey := &[crypto.AES256KeySize]byte{} |
| 64 | + for i := range rootKey { |
| 65 | + rootKey[i] = byte(i + 1) |
| 66 | + } |
| 67 | + |
| 68 | + // Stage 1: initialize and verify the root key is cached. |
| 69 | + state.Initialize(rootKey) |
| 70 | + if state.RootKeyZero() { |
| 71 | + t.Fatal("root key is not cached after Initialize") |
| 72 | + return |
| 73 | + } |
| 74 | + |
| 75 | + // Stage 2: write a secret and a policy through the real stack. |
| 76 | + secretValues := map[string]string{ |
| 77 | + "username": "spike", |
| 78 | + "password": "integration-v1", |
| 79 | + } |
| 80 | + if upsertErr := state.UpsertSecret(secretPath, secretValues); upsertErr != nil { |
| 81 | + t.Fatalf("failed to upsert the secret: %v", upsertErr) |
| 82 | + return |
| 83 | + } |
| 84 | + |
| 85 | + got, getErr := state.GetSecret(secretPath, 0) |
| 86 | + if getErr != nil { |
| 87 | + t.Fatalf("failed to read the secret back: %v", getErr) |
| 88 | + return |
| 89 | + } |
| 90 | + if got["password"] != secretValues["password"] { |
| 91 | + t.Fatalf("secret round trip mismatch: got %q", got["password"]) |
| 92 | + return |
| 93 | + } |
| 94 | + |
| 95 | + if _, policyErr := state.UpsertPolicy(data.Policy{ |
| 96 | + Name: policyName, |
| 97 | + SPIFFEIDPattern: `^spiffe://spike\.ist/workload/.*$`, |
| 98 | + PathPattern: `^integration/.*$`, |
| 99 | + Permissions: []data.PolicyPermission{"read"}, |
| 100 | + }); policyErr != nil { |
| 101 | + t.Fatalf("failed to upsert the policy: %v", policyErr) |
| 102 | + return |
| 103 | + } |
| 104 | + |
| 105 | + policy, policyGetErr := state.GetPolicy(policyName) |
| 106 | + if policyGetErr != nil { |
| 107 | + t.Fatalf("failed to read the policy back: %v", policyGetErr) |
| 108 | + return |
| 109 | + } |
| 110 | + if policy.PathPattern != `^integration/.*$` { |
| 111 | + t.Fatalf("policy round trip mismatch: got %q", policy.PathPattern) |
| 112 | + return |
| 113 | + } |
| 114 | + |
| 115 | + // Stage 3: a duplicate initialization must not recompute root key |
| 116 | + // material or recreate the backend. The observable invariant: the |
| 117 | + // secret written before the duplicate call stays readable, which |
| 118 | + // proves the backend (and the cipher derived from the original |
| 119 | + // key) survived intact. |
| 120 | + state.Initialize(rootKey) |
| 121 | + if state.RootKeyZero() { |
| 122 | + t.Fatal("root key lost after a duplicate Initialize") |
| 123 | + return |
| 124 | + } |
| 125 | + if _, rereadErr := state.GetSecret(secretPath, 0); rereadErr != nil { |
| 126 | + t.Fatalf("secret unreadable after duplicate Initialize: %v", rereadErr) |
| 127 | + return |
| 128 | + } |
| 129 | + |
| 130 | + // Stage 4: export recovery shards while healthy, as the operator |
| 131 | + // recover flow does, and keep only a threshold-sized subset to |
| 132 | + // prove reconstruction does not need every share. |
| 133 | + shardMap := recovery.NewPilotRecoveryShards() |
| 134 | + threshold := env.ShamirThresholdVal() |
| 135 | + if len(shardMap) < threshold { |
| 136 | + t.Fatalf("expected at least %d shards, got %d", |
| 137 | + threshold, len(shardMap)) |
| 138 | + return |
| 139 | + } |
| 140 | + |
| 141 | + shards := make([]crypto.ShamirShard, 0, threshold) |
| 142 | + for idx, value := range shardMap { |
| 143 | + if len(shards) == threshold { |
| 144 | + break |
| 145 | + } |
| 146 | + shards = append(shards, crypto.ShamirShard{ |
| 147 | + ID: uint64(idx), |
| 148 | + Value: value, |
| 149 | + }) |
| 150 | + } |
| 151 | + |
| 152 | + // Stage 5: simulate the crash by zeroing the cached root key, the |
| 153 | + // in-process equivalent of losing Nexus and every Keeper. |
| 154 | + state.LockRootKey() |
| 155 | + mem.ClearRawBytes(state.RootKeyNoLock()) |
| 156 | + state.UnlockRootKey() |
| 157 | + if !state.RootKeyZero() { |
| 158 | + t.Fatal("root key still cached after the simulated crash") |
| 159 | + return |
| 160 | + } |
| 161 | + |
| 162 | + // Stage 6: restore from the shard subset. The restore path |
| 163 | + // initializes the state first and only then reaches for a SPIFFE |
| 164 | + // source to hydrate the Keepers; that step fails via log.FatalErr, |
| 165 | + // which the panic mode converts into a recoverable panic. The panic |
| 166 | + // is therefore expected here, and it fires after the part under |
| 167 | + // test has completed. |
| 168 | + // |
| 169 | + // A malformed workload API address makes the source creation fail |
| 170 | + // at validation time. With no SPIFFE_ENDPOINT_SOCKET at all, |
| 171 | + // go-spiffe would instead dial the default socket with an |
| 172 | + // unbounded context and hang the test forever (the missing |
| 173 | + // SVID-acquisition timeout is tracked as its own task). |
| 174 | + t.Setenv("SPIFFE_ENDPOINT_SOCKET", "bogus://fail-fast") |
| 175 | + t.Setenv("SPIKE_STACK_TRACES_ON_LOG_FATAL", "true") |
| 176 | + func() { |
| 177 | + defer func() { |
| 178 | + if r := recover(); r == nil { |
| 179 | + t.Error("expected a panic at the SPIFFE-source boundary" + |
| 180 | + " after the state restore") |
| 181 | + } |
| 182 | + }() |
| 183 | + recovery.RestoreBackingStoreFromPilotShards(shards) |
| 184 | + }() |
| 185 | + |
| 186 | + // Stage 7: the restore must have recomputed the original root key |
| 187 | + // and the pre-crash data must be readable again. |
| 188 | + if state.RootKeyZero() { |
| 189 | + t.Fatal("root key not restored from shards") |
| 190 | + return |
| 191 | + } |
| 192 | + |
| 193 | + state.LockRootKey() |
| 194 | + restoredMatches := *state.RootKeyNoLock() == *rootKey |
| 195 | + state.UnlockRootKey() |
| 196 | + if !restoredMatches { |
| 197 | + t.Fatal("restored root key differs from the original") |
| 198 | + return |
| 199 | + } |
| 200 | + |
| 201 | + restored, restoredErr := state.GetSecret(secretPath, 0) |
| 202 | + if restoredErr != nil { |
| 203 | + t.Fatalf("secret unreadable after the restore: %v", restoredErr) |
| 204 | + return |
| 205 | + } |
| 206 | + if restored["password"] != secretValues["password"] { |
| 207 | + t.Fatalf("secret mismatch after the restore: got %q", |
| 208 | + restored["password"]) |
| 209 | + return |
| 210 | + } |
| 211 | + |
| 212 | + if _, policyRereadErr := state.GetPolicy(policyName); policyRereadErr != nil { |
| 213 | + t.Fatalf("policy unreadable after the restore: %v", policyRereadErr) |
| 214 | + return |
| 215 | + } |
| 216 | + |
| 217 | + // Stage 8: deletion and undeletion survive the restored state. |
| 218 | + if delErr := state.DeleteSecret(secretPath, []int{1}); delErr != nil { |
| 219 | + t.Fatalf("failed to delete the secret: %v", delErr) |
| 220 | + return |
| 221 | + } |
| 222 | + if _, deletedErr := state.GetSecret(secretPath, 1); deletedErr == nil { |
| 223 | + t.Error("expected an error reading a deleted secret version") |
| 224 | + } |
| 225 | + |
| 226 | + if undelErr := state.UndeleteSecret(secretPath, []int{1}); undelErr != nil { |
| 227 | + t.Fatalf("failed to undelete the secret: %v", undelErr) |
| 228 | + return |
| 229 | + } |
| 230 | + if _, revivedErr := state.GetSecret(secretPath, 1); revivedErr != nil { |
| 231 | + t.Fatalf("secret unreadable after undelete: %v", revivedErr) |
| 232 | + return |
| 233 | + } |
| 234 | +} |
0 commit comments