-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathagent_test.go
More file actions
426 lines (353 loc) · 12 KB
/
Copy pathagent_test.go
File metadata and controls
426 lines (353 loc) · 12 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
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
package testrunner
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"runtime"
"testing"
"time"
)
// startTestAgent starts an agent on a random port and returns its base URL.
func startTestAgent(t *testing.T, cfg AgentConfig) (*Agent, string) {
t.Helper()
if cfg.Registry == nil {
cfg.Registry = NewRegistry()
}
agent := NewAgent(cfg)
ctx, cancel := context.WithCancel(context.Background())
t.Cleanup(cancel)
go agent.Start(ctx)
// Wait for listener.
for i := 0; i < 50; i++ {
if agent.ListenAddr() != "" {
break
}
time.Sleep(20 * time.Millisecond)
}
if agent.ListenAddr() == "" {
t.Fatal("agent didn't start")
}
baseURL := "http://" + agent.ListenAddr()
return agent, baseURL
}
func TestAgent_Health(t *testing.T) {
_, baseURL := startTestAgent(t, AgentConfig{Port: 0})
resp, err := http.Get(baseURL + "/health")
if err != nil {
t.Fatalf("GET /health: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatalf("status = %d", resp.StatusCode)
}
var hr HealthResponse
json.NewDecoder(resp.Body).Decode(&hr)
if !hr.OK {
t.Error("health not OK")
}
if hr.AgentID == "" {
t.Error("empty agent ID")
}
if hr.Hostname == "" {
t.Error("empty hostname")
}
}
func TestAgent_Health_NoAuth(t *testing.T) {
// /health should not require auth.
_, baseURL := startTestAgent(t, AgentConfig{Port: 0, Token: "secret"})
resp, err := http.Get(baseURL + "/health")
if err != nil {
t.Fatalf("GET /health: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Fatalf("/health without token should work, got %d", resp.StatusCode)
}
}
func TestAgent_Auth_Rejection(t *testing.T) {
_, baseURL := startTestAgent(t, AgentConfig{Port: 0, Token: "secret"})
// POST /phase without token → 401.
body := bytes.NewReader([]byte(`{}`))
resp, err := http.Post(baseURL+"/phase", "application/json", body)
if err != nil {
t.Fatalf("POST /phase: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusUnauthorized {
t.Errorf("expected 401, got %d", resp.StatusCode)
}
}
func TestAgent_Auth_ValidToken(t *testing.T) {
_, baseURL := startTestAgent(t, AgentConfig{Port: 0, Token: "secret"})
req, _ := http.NewRequest("POST", baseURL+"/phase", bytes.NewReader([]byte(`{"phase_index":0, "actions":[], "global_vars":{}}`)))
req.Header.Set("Content-Type", "application/json")
req.Header.Set(AuthTokenHeader, "secret")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("POST /phase: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != 200 {
t.Errorf("expected 200 with valid token, got %d", resp.StatusCode)
}
}
func TestAgent_Phase_EchoAction(t *testing.T) {
registry := NewRegistry()
registry.RegisterFunc("echo_val", TierCore, func(ctx context.Context, actx *ActionContext, act Action) (map[string]string, error) {
return map[string]string{"value": act.Params["msg"]}, nil
})
_, baseURL := startTestAgent(t, AgentConfig{Port: 0, Registry: registry})
phaseReq := PhaseRequest{
PhaseIndex: 0,
PhaseName: "test",
Actions: []Action{
{Action: "echo_val", SaveAs: "result", Params: map[string]string{"msg": "hello"}},
},
GlobalVars: map[string]string{},
}
body, _ := json.Marshal(phaseReq)
resp, err := http.Post(baseURL+"/phase", "application/json", bytes.NewReader(body))
if err != nil {
t.Fatalf("POST /phase: %v", err)
}
defer resp.Body.Close()
var phaseResp PhaseResponse
json.NewDecoder(resp.Body).Decode(&phaseResp)
if phaseResp.Error != "" {
t.Fatalf("phase error: %s", phaseResp.Error)
}
if len(phaseResp.Results) != 1 {
t.Fatalf("expected 1 result, got %d", len(phaseResp.Results))
}
if phaseResp.Results[0].Status != StatusPass {
t.Errorf("action status = %s", phaseResp.Results[0].Status)
}
if phaseResp.NewVars["result"] != "hello" {
t.Errorf("new_vars[result] = %q, want hello", phaseResp.NewVars["result"])
}
}
func TestAgent_Phase_FailStopsExecution(t *testing.T) {
registry := NewRegistry()
callOrder := []string{}
registry.RegisterFunc("a1", TierCore, func(ctx context.Context, actx *ActionContext, act Action) (map[string]string, error) {
callOrder = append(callOrder, "a1")
return nil, fmt.Errorf("fail")
})
registry.RegisterFunc("a2", TierCore, func(ctx context.Context, actx *ActionContext, act Action) (map[string]string, error) {
callOrder = append(callOrder, "a2")
return nil, nil
})
_, baseURL := startTestAgent(t, AgentConfig{Port: 0, Registry: registry})
phaseReq := PhaseRequest{
PhaseName: "test",
Actions: []Action{
{Action: "a1"},
{Action: "a2"}, // should not execute
},
GlobalVars: map[string]string{},
}
body, _ := json.Marshal(phaseReq)
resp, _ := http.Post(baseURL+"/phase", "application/json", bytes.NewReader(body))
defer resp.Body.Close()
var phaseResp PhaseResponse
json.NewDecoder(resp.Body).Decode(&phaseResp)
if phaseResp.Error == "" {
t.Error("expected error from failed action")
}
if len(callOrder) != 1 {
t.Errorf("expected only a1 to run, got %v", callOrder)
}
}
func TestAgent_Upload_PathSafety(t *testing.T) {
_, baseURL := startTestAgent(t, AgentConfig{Port: 0})
// Attempt path traversal → should be rejected.
req, _ := http.NewRequest("POST", baseURL+"/upload?path=/tmp/sw-test-runner/../etc/passwd", bytes.NewReader([]byte("evil")))
req.Header.Set("Content-Type", "application/octet-stream")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("upload: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
t.Errorf("expected 403 for path traversal, got %d", resp.StatusCode)
}
// Attempt outside base path.
req2, _ := http.NewRequest("POST", baseURL+"/upload?path=/etc/evil", bytes.NewReader([]byte("evil")))
req2.Header.Set("Content-Type", "application/octet-stream")
resp2, _ := http.DefaultClient.Do(req2)
defer resp2.Body.Close()
if resp2.StatusCode != http.StatusForbidden {
t.Errorf("expected 403 for outside base path, got %d", resp2.StatusCode)
}
}
func TestAgent_Upload_ValidPath(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("upload test requires /tmp on Unix")
}
_, baseURL := startTestAgent(t, AgentConfig{Port: 0})
// Create a temp subdir under /tmp/sw-test-runner/.
uploadDir := "/tmp/sw-test-runner/test-upload"
os.MkdirAll(uploadDir, 0755)
t.Cleanup(func() { os.RemoveAll(uploadDir) })
uploadPath := filepath.Join(uploadDir, "testfile.bin")
content := []byte("test binary content")
req, _ := http.NewRequest("POST", baseURL+"/upload?path="+uploadPath, bytes.NewReader(content))
req.Header.Set("Content-Type", "application/octet-stream")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("upload: %v", err)
}
defer resp.Body.Close()
var ur UploadResponse
json.NewDecoder(resp.Body).Decode(&ur)
if !ur.OK {
t.Fatalf("upload not OK: %s", ur.Error)
}
if ur.Size != int64(len(content)) {
t.Errorf("size = %d, want %d", ur.Size, len(content))
}
// Verify file contents.
got, _ := os.ReadFile(uploadPath)
if string(got) != string(content) {
t.Errorf("content mismatch")
}
}
func TestAgent_Exec_DisabledByDefault(t *testing.T) {
_, baseURL := startTestAgent(t, AgentConfig{Port: 0, AllowExec: false})
body, _ := json.Marshal(ExecRequest{Cmd: "echo hi"})
resp, err := http.Post(baseURL+"/exec", "application/json", bytes.NewReader(body))
if err != nil {
t.Fatalf("POST /exec: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
t.Errorf("expected 403 when exec disabled, got %d", resp.StatusCode)
}
}
func TestAgent_Exec_Enabled(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("exec test requires Unix shell")
}
_, baseURL := startTestAgent(t, AgentConfig{Port: 0, AllowExec: true})
body, _ := json.Marshal(ExecRequest{Cmd: "echo hello-exec"})
resp, err := http.Post(baseURL+"/exec", "application/json", bytes.NewReader(body))
if err != nil {
t.Fatalf("POST /exec: %v", err)
}
defer resp.Body.Close()
var er ExecResponse
json.NewDecoder(resp.Body).Decode(&er)
if er.ExitCode != 0 {
t.Errorf("exit code = %d, stderr: %s, error: %s", er.ExitCode, er.Stderr, er.Error)
}
if er.Stdout != "hello-exec\n" {
t.Errorf("stdout = %q", er.Stdout)
}
}
func TestAgent_Artifacts_PathSafety(t *testing.T) {
_, baseURL := startTestAgent(t, AgentConfig{Port: 0, Token: "secret"})
// Attempt with traversal.
req, _ := http.NewRequest("GET", baseURL+"/artifacts?dir=/tmp/sw-test-runner/../etc", nil)
req.Header.Set(AuthTokenHeader, "secret")
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("GET /artifacts: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusForbidden {
t.Errorf("expected 403 for traversal, got %d", resp.StatusCode)
}
// Attempt outside base path.
req2, _ := http.NewRequest("GET", baseURL+"/artifacts?dir=/etc", nil)
req2.Header.Set(AuthTokenHeader, "secret")
resp2, err := http.DefaultClient.Do(req2)
if err != nil {
t.Fatalf("GET /artifacts: %v", err)
}
defer resp2.Body.Close()
if resp2.StatusCode != http.StatusForbidden {
t.Errorf("expected 403 for outside base path, got %d", resp2.StatusCode)
}
}
func TestAgent_Artifacts_MissingDir(t *testing.T) {
_, baseURL := startTestAgent(t, AgentConfig{Port: 0})
req, _ := http.NewRequest("GET", baseURL+"/artifacts?dir=/tmp/sw-test-runner/nonexistent-"+fmt.Sprintf("%d", time.Now().UnixNano()), nil)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("GET /artifacts: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNotFound {
t.Errorf("expected 404 for missing dir, got %d", resp.StatusCode)
}
}
func TestAgent_Artifacts_NoAuth(t *testing.T) {
_, baseURL := startTestAgent(t, AgentConfig{Port: 0, Token: "secret"})
// No auth header should be rejected.
resp, err := http.Get(baseURL + "/artifacts?dir=/tmp/sw-test-runner/test")
if err != nil {
t.Fatalf("GET /artifacts: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusUnauthorized {
t.Errorf("expected 401, got %d", resp.StatusCode)
}
}
func TestAgent_Artifacts_ValidDir(t *testing.T) {
if runtime.GOOS == "windows" {
t.Skip("artifacts test requires /tmp on Unix")
}
_, baseURL := startTestAgent(t, AgentConfig{Port: 0})
// Create test directory with files.
dir := fmt.Sprintf("/tmp/sw-test-runner/test-artifacts-%d", time.Now().UnixNano())
os.MkdirAll(dir, 0755)
t.Cleanup(func() { os.RemoveAll(dir) })
os.WriteFile(filepath.Join(dir, "log.txt"), []byte("test log content"), 0644)
os.WriteFile(filepath.Join(dir, "dmesg.txt"), []byte("kernel messages"), 0644)
req, _ := http.NewRequest("GET", baseURL+"/artifacts?dir="+dir, nil)
resp, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatalf("GET /artifacts: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
body, _ := io.ReadAll(resp.Body)
t.Fatalf("expected 200, got %d: %s", resp.StatusCode, string(body))
}
if ct := resp.Header.Get("Content-Type"); ct != "application/gzip" {
t.Errorf("Content-Type = %q, want application/gzip", ct)
}
// Verify it's valid gzip+tar.
body, _ := io.ReadAll(resp.Body)
if len(body) == 0 {
t.Fatal("empty response body")
}
}
func TestAgent_Phase_VarSubstitution(t *testing.T) {
registry := NewRegistry()
registry.RegisterFunc("concat", TierCore, func(ctx context.Context, actx *ActionContext, act Action) (map[string]string, error) {
return map[string]string{"value": act.Params["a"] + "-" + act.Params["b"]}, nil
})
_, baseURL := startTestAgent(t, AgentConfig{Port: 0, Registry: registry})
phaseReq := PhaseRequest{
PhaseName: "test",
Actions: []Action{
{Action: "concat", SaveAs: "out", Params: map[string]string{"a": "{{ x }}", "b": "{{ y }}"}},
},
GlobalVars: map[string]string{"x": "hello", "y": "world"},
}
body, _ := json.Marshal(phaseReq)
resp, _ := http.Post(baseURL+"/phase", "application/json", bytes.NewReader(body))
defer resp.Body.Close()
respBody, _ := io.ReadAll(resp.Body)
var phaseResp PhaseResponse
json.Unmarshal(respBody, &phaseResp)
if phaseResp.NewVars["out"] != "hello-world" {
t.Errorf("var substitution failed: out = %q", phaseResp.NewVars["out"])
}
}