-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi_test.go
More file actions
656 lines (542 loc) · 16.7 KB
/
Copy pathapi_test.go
File metadata and controls
656 lines (542 loc) · 16.7 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
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
// Package integration provides API integration tests for CubeOS.
// Run with: go test -tags=integration ./tests/integration/...
//
//go:build integration
// +build integration
package integration
import (
"bytes"
"encoding/base64"
"encoding/json"
"fmt"
"net/http"
"os"
"testing"
"time"
)
var (
baseURL = getEnv("CUBEOS_API_URL", "http://10.42.24.1:6010")
username = getEnv("CUBEOS_USERNAME", "admin")
password = getEnv("CUBEOS_PASSWORD", "cubeos")
token string
)
func getEnv(key, defaultValue string) string {
if v := os.Getenv(key); v != "" {
return v
}
return defaultValue
}
// TestMain authenticates before running tests
func TestMain(m *testing.M) {
// Authenticate
var err error
token, err = authenticate()
if err != nil {
fmt.Printf("Failed to authenticate: %v\n", err)
os.Exit(1)
}
fmt.Printf("Authenticated successfully, token obtained\n")
// Run tests
code := m.Run()
os.Exit(code)
}
func authenticate() (string, error) {
body := map[string]string{
"username": username,
"password": password,
}
jsonBody, _ := json.Marshal(body)
resp, err := http.Post(baseURL+"/api/v1/auth/login", "application/json", bytes.NewReader(jsonBody))
if err != nil {
return "", err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return "", fmt.Errorf("login failed with status %d", resp.StatusCode)
}
var result struct {
AccessToken string `json:"access_token"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return "", err
}
return result.AccessToken, nil
}
func authRequest(method, path string, body interface{}) (*http.Response, error) {
var reqBody *bytes.Reader
if body != nil {
jsonBody, _ := json.Marshal(body)
reqBody = bytes.NewReader(jsonBody)
} else {
reqBody = bytes.NewReader(nil)
}
req, err := http.NewRequest(method, baseURL+path, reqBody)
if err != nil {
return nil, err
}
req.Header.Set("Authorization", "Bearer "+token)
req.Header.Set("Content-Type", "application/json")
client := &http.Client{Timeout: 30 * time.Second}
return client.Do(req)
}
// ============================================================
// Health Tests
// ============================================================
func TestHealth(t *testing.T) {
resp, err := http.Get(baseURL + "/health")
if err != nil {
t.Fatalf("Health check failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
if result["status"] != "healthy" {
t.Errorf("Expected status 'healthy', got '%v'", result["status"])
}
}
// ============================================================
// Apps API Tests
// ============================================================
func TestListApps(t *testing.T) {
resp, err := authRequest("GET", "/api/v1/apps", nil)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
var result struct {
Apps []map[string]interface{} `json:"apps"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
t.Fatalf("Failed to decode response: %v", err)
}
t.Logf("Found %d apps", len(result.Apps))
}
func TestListAppsWithFilter(t *testing.T) {
// Test type filter
resp, err := authRequest("GET", "/api/v1/apps?type=system", nil)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
var result struct {
Apps []map[string]interface{} `json:"apps"`
}
json.NewDecoder(resp.Body).Decode(&result)
// All returned apps should be system type
for _, app := range result.Apps {
if app["type"] != "system" {
t.Errorf("Expected type 'system', got '%v'", app["type"])
}
}
}
func TestGetAppNotFound(t *testing.T) {
resp, err := authRequest("GET", "/api/v1/apps/nonexistent-app-xyz", nil)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNotFound {
t.Errorf("Expected status 404, got %d", resp.StatusCode)
}
}
// ============================================================
// Network API Tests
// ============================================================
func TestGetNetworkStatus(t *testing.T) {
resp, err := authRequest("GET", "/api/v1/network/status", nil)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
var result struct {
Mode string `json:"mode"`
Internet bool `json:"internet"`
Subnet string `json:"subnet"`
GatewayIP string `json:"gateway_ip"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
t.Fatalf("Failed to decode response: %v", err)
}
// Validate mode is one of expected values
validModes := map[string]bool{"offline": true, "online_eth": true, "online_wifi": true}
if !validModes[result.Mode] {
t.Errorf("Invalid network mode: %s", result.Mode)
}
// Validate subnet format
if result.Subnet == "" {
t.Error("Subnet should not be empty")
}
t.Logf("Network mode: %s, Internet: %v, Subnet: %s", result.Mode, result.Internet, result.Subnet)
}
func TestScanWiFiNetworks(t *testing.T) {
resp, err := authRequest("GET", "/api/v1/network/wifi/scan", nil)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
// May return 200 with empty list or error if no WiFi hardware
if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusInternalServerError {
t.Errorf("Expected status 200 or 500, got %d", resp.StatusCode)
}
if resp.StatusCode == http.StatusOK {
var result struct {
Networks []map[string]interface{} `json:"networks"`
}
json.NewDecoder(resp.Body).Decode(&result)
t.Logf("Found %d WiFi networks", len(result.Networks))
}
}
// ============================================================
// VPN API Tests
// ============================================================
func TestGetVPNStatus(t *testing.T) {
resp, err := authRequest("GET", "/api/v1/vpn/status", nil)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
var result struct {
Connected bool `json:"connected"`
}
json.NewDecoder(resp.Body).Decode(&result)
t.Logf("VPN connected: %v", result.Connected)
}
func TestListVPNConfigs(t *testing.T) {
resp, err := authRequest("GET", "/api/v1/vpn/configs", nil)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
var result struct {
Configs []map[string]interface{} `json:"configs"`
}
json.NewDecoder(resp.Body).Decode(&result)
t.Logf("Found %d VPN configs", len(result.Configs))
}
func TestAddVPNConfigValidation(t *testing.T) {
// Test with missing required fields
resp, err := authRequest("POST", "/api/v1/vpn/configs", map[string]string{
"name": "test-vpn",
// Missing type and config
})
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusBadRequest {
t.Errorf("Expected status 400 for missing fields, got %d", resp.StatusCode)
}
}
func TestVPNConfigLifecycle(t *testing.T) {
// Skip if running in CI without VPN support
if os.Getenv("SKIP_VPN_TESTS") != "" {
t.Skip("Skipping VPN tests")
}
configName := fmt.Sprintf("test-vpn-%d", time.Now().Unix())
// Create a minimal WireGuard config for testing
wgConfig := `[Interface]
PrivateKey = cGFzc3dvcmQ=
Address = 10.0.0.2/24
[Peer]
PublicKey = cHVibGljLWtleQ==
Endpoint = vpn.example.com:51820
AllowedIPs = 0.0.0.0/0`
// Add config
resp, err := authRequest("POST", "/api/v1/vpn/configs", map[string]string{
"name": configName,
"type": "wireguard",
"config": base64.StdEncoding.EncodeToString([]byte(wgConfig)),
})
if err != nil {
t.Fatalf("Failed to add VPN config: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusCreated {
t.Fatalf("Expected status 201, got %d", resp.StatusCode)
}
// Verify it exists
resp, err = authRequest("GET", "/api/v1/vpn/configs/"+configName, nil)
if err != nil {
t.Fatalf("Failed to get VPN config: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
// Delete config
resp, err = authRequest("DELETE", "/api/v1/vpn/configs/"+configName, nil)
if err != nil {
t.Fatalf("Failed to delete VPN config: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
// Verify it's deleted
resp, err = authRequest("GET", "/api/v1/vpn/configs/"+configName, nil)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
resp.Body.Close()
if resp.StatusCode != http.StatusNotFound {
t.Errorf("Expected status 404 after deletion, got %d", resp.StatusCode)
}
}
func TestGetPublicIP(t *testing.T) {
resp, err := authRequest("GET", "/api/v1/vpn/public-ip", nil)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
// May fail if no internet connection
if resp.StatusCode == http.StatusOK {
var result struct {
PublicIP string `json:"public_ip"`
}
json.NewDecoder(resp.Body).Decode(&result)
t.Logf("Public IP: %s", result.PublicIP)
} else {
t.Logf("Could not get public IP (status %d) - may be offline", resp.StatusCode)
}
}
// ============================================================
// Mounts API Tests
// ============================================================
func TestListMounts(t *testing.T) {
resp, err := authRequest("GET", "/api/v1/mounts", nil)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
var result struct {
Mounts []map[string]interface{} `json:"mounts"`
}
json.NewDecoder(resp.Body).Decode(&result)
t.Logf("Found %d mounts", len(result.Mounts))
}
func TestAddMountValidation(t *testing.T) {
// Test with missing required fields
resp, err := authRequest("POST", "/api/v1/mounts", map[string]string{
"name": "test-mount",
// Missing type and remote_path
})
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusBadRequest {
t.Errorf("Expected status 400 for missing fields, got %d", resp.StatusCode)
}
}
func TestAddMountInvalidSMBPath(t *testing.T) {
resp, err := authRequest("POST", "/api/v1/mounts", map[string]interface{}{
"name": "test-smb",
"type": "smb",
"remote_path": "invalid-path", // Should start with //
})
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusBadRequest {
t.Errorf("Expected status 400 for invalid SMB path, got %d", resp.StatusCode)
}
}
func TestAddMountInvalidNFSPath(t *testing.T) {
resp, err := authRequest("POST", "/api/v1/mounts", map[string]interface{}{
"name": "test-nfs",
"type": "nfs",
"remote_path": "invalid-path", // Should contain :
})
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusBadRequest {
t.Errorf("Expected status 400 for invalid NFS path, got %d", resp.StatusCode)
}
}
func TestMountNotFound(t *testing.T) {
resp, err := authRequest("GET", "/api/v1/mounts/nonexistent-mount-xyz", nil)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNotFound {
t.Errorf("Expected status 404, got %d", resp.StatusCode)
}
}
func TestTestMountConnection(t *testing.T) {
// Test with invalid host - should fail but not crash
resp, err := authRequest("POST", "/api/v1/mounts/test", map[string]interface{}{
"type": "smb",
"remote_path": "//192.0.2.1/share", // TEST-NET-1, won't exist
})
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
var result struct {
Success bool `json:"success"`
Error string `json:"error"`
}
json.NewDecoder(resp.Body).Decode(&result)
// Connection should fail but API should return properly
if result.Success {
t.Error("Expected connection to fail for non-existent host")
}
}
// ============================================================
// Profiles API Tests
// ============================================================
func TestListProfiles(t *testing.T) {
resp, err := authRequest("GET", "/api/v1/profiles", nil)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
var result struct {
Profiles []map[string]interface{} `json:"profiles"`
ActiveProfile string `json:"active_profile"`
}
json.NewDecoder(resp.Body).Decode(&result)
t.Logf("Found %d profiles, active: %s", len(result.Profiles), result.ActiveProfile)
}
func TestGetProfileNotFound(t *testing.T) {
resp, err := authRequest("GET", "/api/v1/profiles/nonexistent-profile-xyz", nil)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusNotFound {
t.Errorf("Expected status 404, got %d", resp.StatusCode)
}
}
// ============================================================
// System API Tests
// ============================================================
func TestGetSystemInfo(t *testing.T) {
resp, err := authRequest("GET", "/api/v1/system/info", nil)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
// Check required fields
requiredFields := []string{"hostname", "os", "kernel", "architecture"}
for _, field := range requiredFields {
if _, ok := result[field]; !ok {
t.Errorf("Missing required field: %s", field)
}
}
t.Logf("System: %s, Kernel: %s, Arch: %s",
result["os"], result["kernel"], result["architecture"])
}
func TestGetSystemStats(t *testing.T) {
resp, err := authRequest("GET", "/api/v1/system/stats", nil)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
var result map[string]interface{}
json.NewDecoder(resp.Body).Decode(&result)
t.Logf("System stats: %+v", result)
}
// ============================================================
// Auth Tests
// ============================================================
func TestAuthRequired(t *testing.T) {
// Request without token should fail
req, _ := http.NewRequest("GET", baseURL+"/api/v1/apps", nil)
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusUnauthorized {
t.Errorf("Expected status 401 without auth, got %d", resp.StatusCode)
}
}
func TestInvalidToken(t *testing.T) {
req, _ := http.NewRequest("GET", baseURL+"/api/v1/apps", nil)
req.Header.Set("Authorization", "Bearer invalid-token-xyz")
client := &http.Client{Timeout: 10 * time.Second}
resp, err := client.Do(req)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusUnauthorized {
t.Errorf("Expected status 401 for invalid token, got %d", resp.StatusCode)
}
}
func TestRefreshToken(t *testing.T) {
resp, err := authRequest("POST", "/api/v1/auth/refresh", nil)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
var result struct {
AccessToken string `json:"access_token"`
}
json.NewDecoder(resp.Body).Decode(&result)
if result.AccessToken == "" {
t.Error("Expected non-empty refreshed access_token")
}
}
func TestGetMe(t *testing.T) {
resp, err := authRequest("GET", "/api/v1/auth/me", nil)
if err != nil {
t.Fatalf("Request failed: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
var result struct {
Username string `json:"username"`
Role string `json:"role"`
}
json.NewDecoder(resp.Body).Decode(&result)
if result.Username != username {
t.Errorf("Expected username '%s', got '%s'", username, result.Username)
}
}