{{ message }}
Repository navigation
Expand file tree
/
Copy pathconfigure_gcp_signal_test.go
More file actions
330 lines (314 loc) · 12.4 KB
/
Copy pathconfigure_gcp_signal_test.go
File metadata and controls
330 lines (314 loc) · 12.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
//go:build darwin || linux
package main
import (
"bytes"
"context"
"encoding/base64"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/httptest"
"os"
"os/exec"
"path/filepath"
"strings"
"sync"
"syscall"
"testing"
"time"
"github.com/stretchr/testify/require"
)
func TestRunConfigureGCP_InterruptCleansMintedKey(t *testing.T) {
if dir := os.Getenv("CUDLY_GCP_SIGNAL_CHILD"); dir != "" {
if err := runGCPInterruptChild(dir); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
os.Exit(0) // The test harness cannot write to the deliberately full stdout pipe.
}
for _, sig := range []syscall.Signal{syscall.SIGINT, syscall.SIGTERM} {
t.Run(sig.String(), func(t *testing.T) {
child, dir, stdout, stderr := startGCPInterruptChild(t, "upload")
defer stdout.Close()
var keyFile string
requireMarker(t, child, stderr, "minted key.json with fixture secret", func() bool {
matches, err := filepath.Glob(filepath.Join(dir, "cudly-gcp-key-*", "key.json"))
if err != nil || len(matches) != 1 {
return false
}
data, err := os.ReadFile(matches[0])
if err != nil || !bytes.Contains(data, []byte("fixture-secret")) {
return false
}
keyFile = matches[0]
return true
})
require.NoError(t, child.Process.Signal(sig))
err := child.Wait()
require.NoFileExists(t, keyFile)
require.NoDirExists(t, filepath.Dir(keyFile))
require.NoError(t, err, "child stderr: %s", stderr.String())
deleted, err := os.ReadFile(filepath.Join(dir, "deleted"))
require.NoError(t, err)
require.Equal(t, "/v1/projects/fixture-project/serviceAccounts/cudly-service-account@fixture-project.iam.gserviceaccount.com/keys/fixture-key", string(deleted))
})
}
}
func TestRunConfigureGCP_InterruptDuringMint(t *testing.T) {
child, dir, stdout, stderr := startGCPInterruptChild(t, "mint")
defer stdout.Close()
requireMarker(t, child, stderr, "creating marker", func() bool {
_, err := os.Stat(filepath.Join(dir, "creating"))
return err == nil
})
require.NoError(t, child.Process.Signal(os.Interrupt))
require.NoError(t, child.Wait(), "child stderr: %s", stderr.String())
matches, err := filepath.Glob(filepath.Join(dir, "cudly-gcp-key-*"))
require.NoError(t, err)
require.Empty(t, matches)
require.NoFileExists(t, filepath.Join(dir, "minted"))
}
func TestRunConfigureGCP_InterruptAtPromptExits(t *testing.T) {
child, dir, stdout, stderr := startGCPInterruptChild(t, "prompt")
defer stdout.Close()
var output strings.Builder
for !strings.Contains(output.String(), "the local copy is removed after upload) ") {
var b [1]byte
_, err := stdout.Read(b[:])
require.NoError(t, err)
output.WriteByte(b[0])
}
require.NoError(t, child.Process.Signal(os.Interrupt))
require.Error(t, child.Wait(), "child stderr: %s", stderr.String())
status, ok := child.ProcessState.Sys().(syscall.WaitStatus)
require.True(t, ok)
require.True(t, status.Signaled())
require.Equal(t, syscall.SIGINT, status.Signal())
require.NoFileExists(t, filepath.Join(dir, "minted"))
}
func TestRunConfigureGCP_SecondInterruptAbortsSlowDelete(t *testing.T) {
child, dir, stdout, stderr := startGCPInterruptChild(t, "slowdelete")
defer stdout.Close()
requireMarker(t, child, stderr, "minted key.json with fixture secret", func() bool {
matches, err := filepath.Glob(filepath.Join(dir, "cudly-gcp-key-*", "key.json"))
if err != nil || len(matches) != 1 {
return false
}
data, err := os.ReadFile(matches[0])
return err == nil && bytes.Contains(data, []byte("fixture-secret"))
})
require.NoError(t, child.Process.Signal(os.Interrupt))
// Key the second signal on the message the handler prints after it
// restores default signal handling; an earlier one would be swallowed.
requireMarker(t, child, stderr, "Interrupted message", func() bool {
return strings.Contains(stderr.String(), "Interrupted: finishing cleanup")
})
requireMarker(t, child, stderr, "deleting marker", func() bool {
_, err := os.Stat(filepath.Join(dir, "deleting"))
return err == nil
})
require.Contains(t, stderr.String(), "if aborted, delete it with: gcloud iam service-accounts keys delete fixture-key --iam-account=cudly-service-account@fixture-project.iam.gserviceaccount.com")
matches, err := filepath.Glob(filepath.Join(dir, "cudly-gcp-key-*"))
require.NoError(t, err)
require.Empty(t, matches, "local key must be removed before the slow remote delete")
require.NoError(t, child.Process.Signal(os.Interrupt))
done := make(chan error, 1)
go func() { done <- child.Wait() }()
select {
case err := <-done:
require.Error(t, err, "child stderr: %s", stderr.String())
status, ok := child.ProcessState.Sys().(syscall.WaitStatus)
require.True(t, ok)
require.True(t, status.Signaled())
require.Equal(t, syscall.SIGINT, status.Signal())
case <-time.After(5 * time.Second):
t.Fatalf("second SIGINT did not abort the child\nchild stderr: %q", stderr.String())
}
}
func TestRunConfigureGCP_SuccessPrintsNoInterruptText(t *testing.T) {
child, _, stdout, stderr := startGCPInterruptChild(t, "success")
defer stdout.Close()
out, err := io.ReadAll(stdout)
require.NoError(t, err)
require.NoError(t, child.Wait(), "child stderr: %s", stderr.String())
require.Contains(t, string(out), "GCP configuration complete!")
require.NotContains(t, stderr.String(), "Interrupted")
require.NotContains(t, stderr.String(), "Deleting minted key")
}
// syncBuffer lets the test read child stderr while exec is still copying it.
type syncBuffer struct {
mu sync.Mutex
buf bytes.Buffer
}
func (b *syncBuffer) Write(p []byte) (int, error) {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.Write(p)
}
func (b *syncBuffer) String() string {
b.mu.Lock()
defer b.mu.Unlock()
return b.buf.String()
}
// requireMarker polls cond for 10s. On timeout it fails with the child's
// stderr and process state; child stdout is left untouched because one
// scenario keeps it deliberately full.
func requireMarker(t *testing.T, child *exec.Cmd, stderr *syncBuffer, what string, cond func() bool) {
t.Helper()
deadline := time.Now().Add(10 * time.Second)
for !cond() {
if time.Now().After(deadline) {
t.Fatalf("timed out after 10s waiting for %s\nchild state: %s\nchild stderr: %q", what, childState(child), stderr.String())
}
time.Sleep(10 * time.Millisecond)
}
}
// childState reaps the child if it already exited, so a later Wait would
// fail; it is only called on the failing path.
func childState(child *exec.Cmd) string {
var ws syscall.WaitStatus
pid, err := syscall.Wait4(child.Process.Pid, &ws, syscall.WNOHANG, nil)
switch {
case err != nil:
return fmt.Sprintf("wait4 failed: %v", err)
case pid == 0:
return fmt.Sprintf("still running (pid %d)", child.Process.Pid)
case ws.Signaled():
return fmt.Sprintf("exited, killed by signal %v", ws.Signal())
default:
return fmt.Sprintf("exited with code %d", ws.ExitStatus())
}
}
func startGCPInterruptChild(t *testing.T, phase string) (*exec.Cmd, string, io.ReadCloser, *syncBuffer) {
t.Helper()
// The child inherits this env; it sets its own secretsmanager endpoint.
clearAWSEndpointOverrides(t)
dir := t.TempDir()
adc := filepath.Join(dir, "adc.json")
require.NoError(t, os.WriteFile(adc, []byte(`{"type":"authorized_user","client_id":"fixture","client_secret":"fixture","refresh_token":"fixture"}`), 0600))
require.NoError(t, os.WriteFile(filepath.Join(dir, "gcloud"), []byte("#!/bin/sh\n[ \"$*\" = \"config set project fixture-project\" ]\n"), 0700))
ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second)
t.Cleanup(cancel)
child := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestRunConfigureGCP_InterruptCleansMintedKey$")
child.Env = append(os.Environ(), "CUDLY_GCP_SIGNAL_CHILD="+dir, "CUDLY_GCP_SIGNAL_PHASE="+phase, "GOOGLE_APPLICATION_CREDENTIALS="+adc,
"TMPDIR="+dir, "PATH="+dir, "AWS_ACCESS_KEY_ID=fixture", "AWS_SECRET_ACCESS_KEY=fixture",
"AWS_SESSION_TOKEN=", "AWS_PROFILE=", "AWS_REGION=us-east-1", "AWS_EC2_METADATA_DISABLED=true")
stdin, err := child.StdinPipe()
require.NoError(t, err)
t.Cleanup(func() { _ = stdin.Close() })
stdout, err := child.StdoutPipe()
require.NoError(t, err)
stderr := new(syncBuffer)
child.Stderr = stderr
require.NoError(t, child.Start())
t.Cleanup(func() { _ = child.Process.Kill() })
input := "s\ns\ns\nfixture-project\ns\ncudly-service-account@fixture-project.iam.gserviceaccount.com\ns\n"
if phase != "prompt" {
input += "r\n"
}
_, err = io.WriteString(stdin, input)
require.NoError(t, err)
return child, dir, stdout, stderr
}
func runGCPInterruptChild(dir string) error {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := io.Copy(io.Discard, r.Body); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "application/json")
switch {
case r.URL.Path == "/token":
_, _ = io.WriteString(w, `{"access_token":"fixture","token_type":"Bearer","expires_in":3600}`)
case r.Method == http.MethodDelete:
if os.Getenv("CUDLY_GCP_SIGNAL_PHASE") == "slowdelete" {
if err := os.WriteFile(filepath.Join(dir, "deleting"), nil, 0600); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
<-r.Context().Done()
return
}
if err := os.WriteFile(filepath.Join(dir, "deleted"), []byte(r.URL.Path), 0600); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
_, _ = io.WriteString(w, `{}`)
case strings.HasSuffix(r.URL.Path, "/keys"):
if os.Getenv("CUDLY_GCP_SIGNAL_PHASE") == "mint" {
if err := os.WriteFile(filepath.Join(dir, "creating"), nil, 0600); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
<-r.Context().Done()
return
}
if err := os.WriteFile(filepath.Join(dir, "minted"), nil, 0600); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if err := fillGCPChildStdout(); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
material := base64.StdEncoding.EncodeToString([]byte(`{"type":"service_account","project_id":"fixture-project","client_email":"cudly-service-account@fixture-project.iam.gserviceaccount.com","private_key":"fixture-secret"}`))
_, _ = fmt.Fprintf(w, `{"name":"projects/fixture-project/serviceAccounts/cudly-service-account@fixture-project.iam.gserviceaccount.com/keys/fixture-key","privateKeyData":%q}`, material)
case r.Header.Get("X-Amz-Target") == "secretsmanager.ListSecrets":
if os.Getenv("CUDLY_GCP_SIGNAL_PHASE") == "success" {
_, _ = io.WriteString(w, `{"SecretList":[]}`)
return
}
<-r.Context().Done()
case os.Getenv("CUDLY_GCP_SIGNAL_PHASE") == "success" && r.Header.Get("X-Amz-Target") != "":
_, _ = io.WriteString(w, `{}`)
default:
http.Error(w, "unexpected fixture request", http.StatusBadRequest)
}
}))
defer server.Close()
transport := http.DefaultTransport.(*http.Transport).Clone()
transport.Proxy = nil
transport.DialTLSContext = func(ctx context.Context, _, _ string) (net.Conn, error) {
return (&net.Dialer{}).DialContext(ctx, "tcp", strings.TrimPrefix(server.URL, "http://"))
}
http.DefaultTransport = transport
if err := os.Setenv("AWS_ENDPOINT_URL_SECRETS_MANAGER", server.URL); err != nil {
return err
}
gcpOpts = GCPConfigOptions{StackName: "fixture-stack"}
if os.Getenv("CUDLY_GCP_SIGNAL_PHASE") == "success" {
credsFile := filepath.Join(dir, "operator-key.json")
if err := os.WriteFile(credsFile, []byte(`{"type":"service_account","project_id":"fixture-project","client_email":"cudly-service-account@fixture-project.iam.gserviceaccount.com","private_key":"fixture-secret"}`), 0600); err != nil {
return err
}
gcpOpts.CredentialsFile = credsFile
return runConfigureGCP(nil, nil)
}
err := runConfigureGCP(nil, nil)
if !errors.Is(err, context.Canceled) {
return fmt.Errorf("expected cancellation from the real coordinator, got %w", err)
}
if os.Getenv("CUDLY_GCP_SIGNAL_PHASE") == "mint" && !strings.Contains(err.Error(), "may have been created") {
return fmt.Errorf("interrupted CreateKey must warn that a key may exist, got %w", err)
}
return nil
}
func fillGCPChildStdout() error {
if err := syscall.SetNonblock(1, true); err != nil {
return err
}
defer syscall.SetNonblock(1, false)
for _, chunk := range [][]byte{bytes.Repeat([]byte("x"), 4096), []byte("x")} {
for {
if _, err := syscall.Write(1, chunk); err != nil {
if errors.Is(err, syscall.EAGAIN) {
break
}
return err
}
}
}
return nil
}
You can’t perform that action at this time.
